如何正确将DataGrid中的ComboBox绑定到ViewModel的List或Enum?
问题:DataGrid中ComboBox列的实现疑问
我尝试在DataGrid的ComboBox列中让用户选择选项,先后用了Binding和x:Bind两种方式,但一开始的代码无法正常工作——我原本觉得逻辑没问题,实际却存在问题。初始代码如下:
初始代码
ViewModel
public partial class CustomerModel : ObservableObject { private ObservableCollection<DataType> _objects; public ObservableCollection<DataType> Objects { get => _objects; set => SetProperty(ref _objects, value); } private ObservableCollection<string> _field; public ObservableCollection<string> Field { get => _field; set => SetProperty(ref _field, value); } public CustomerModel() { Objects = new(); Field = new ObservableCollection<string> { "Test", "Test" }; } public class DataType : ObservableObject { public int ID { get; set; } public string Name { get; set; } public string Caption { get; set; } public bool Numeric { get; set; } public DataType() { } } }
XAML
<controls:DataGrid x:Name="dataGrid1" KeyDown="dataGrid1_KeyDown" ItemsSource="{x:Bind Model.Objects}" AutoGenerateColumns="False" > <controls:DataGrid.Columns> <controls:DataGridComboBoxColumn Header="Field" ItemsSource="{x:Bind Model.Field}" Tag="Field"/> </controls:DataGrid.Columns> </controls:DataGrid>
更新后的可运行代码
现在我写出了能正常运行的更新代码,想请教这段代码是否合理:
ViewModel
public partial class CustomerModel : ObservableObject { public enum Choices { A, B, C } [ObservableProperty] private ObservableCollection<DataType> _objects; public CustomerModel() { Objects = new(); var data = new DataType(); Objects.Add(data); } public static Choices[] ChoicesOptions { get; } = Enum.GetValues<Choices>(); public partial class DataType : ObservableObject { public int ID { get; set; } public string Name { get; set; } public string Caption { get; set; } public bool Numeric { get; set; } [ObservableProperty] private Choices _choice; } }
XAML
<controls:DataGridComboBoxColumn Header="Field" Binding="{Binding Choice}" ItemsSource="{x:Bind local:CustomerModel.ChoicesOptions, Mode=OneTime}" Tag="Field"/>
额外疑问
另外我注意到有人会在后台代码中实例化ViewModel,请问这是否必要?我的后台代码如下:
public sealed partial class DataGridPage : Page { public DataGridPage() { this.InitializeComponent(); } }
内容的提问来源于stack exchange,提问作者miniHessel
相关产品推荐
相关产品推荐

