在绑定到C# WPF中枚举的数据网格中填充组合框,可以按照以下步骤进行:
public enum ColorEnum
{
Red,
Green,
Blue
}
public class MainViewModel : INotifyPropertyChanged
{
private ColorEnum selectedColor;
public ColorEnum SelectedColor
{
get { return selectedColor; }
set
{
selectedColor = value;
OnPropertyChanged(nameof(SelectedColor));
}
}
public IEnumerable<ColorEnum> ColorOptions
{
get { return Enum.GetValues(typeof(ColorEnum)).Cast<ColorEnum>(); }
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
<Window x:Class="YourNamespace.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:YourNamespace"
Title="MainWindow" Height="450" Width="800">
<Window.DataContext>
<local:MainViewModel />
</Window.DataContext>
<Grid>
<DataGrid ItemsSource="{Binding ColorOptions}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTemplateColumn Header="Color">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox SelectedItem="{Binding SelectedColor, Mode=TwoWay}"
ItemsSource="{Binding DataContext.ColorOptions, RelativeSource={RelativeSource AncestorType=Window}}">
</ComboBox>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
在上述代码中,我们将数据网格的列定义为一个模板列,其中包含一个组合框。组合框的SelectedItem属性绑定到ViewModel类中的SelectedColor属性,ItemsSource属性绑定到ViewModel类中的ColorOptions属性。
这样,当运行应用程序时,数据网格中的每一行都会显示一个组合框,其中包含枚举的选项。用户可以从组合框中选择一个选项,并且选中的值将存储在ViewModel类的SelectedColor属性中。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云