WPF的DataGrid中使用ComboBox作为列的一种常见需求。在使用MVVM模式时,我们可以将ComboBox绑定到ViewModel中的属性,并使用DataGrid中的数据进行填充。
下面是一个简单的MVVM示例,演示如何将DataGrid中的ComboBox列绑定到ViewModel中的属性:
public class ViewModel : INotifyPropertyChanged
private ObservableCollection<string> _items;
public ObservableCollection<string> Items
get { return _items; }
set { _items = value; OnPropertyChanged(); }
private string _selectedItem;
public string SelectedItem
get { return _selectedItem; }
set { _selectedItem = value; OnPropertyChanged(); }
public ViewModel()
Items = new ObservableCollection<string> { "Item1", "Item2", "Item3" };
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
在XAML中设置DataGrid的列模板
<DataGrid ItemsSource="{Binding Data}">
<DataGrid.Columns>
<DataGridComboBoxColumn Header="Items" SelectedItemBinding="{Binding SelectedItem, Mode=TwoWay}">
<DataGridComboBoxColumn.ElementStyle>
<Style TargetType="ComboBox">
<Setter Property="ItemsSource" Value="{Binding DataContext.Items, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"/>
</Style>
</DataGridComboBoxColumn.ElementStyle>
<DataGridComboBoxColumn.EditingElementStyle>
<Style TargetType="ComboBox">
<Setter Property="ItemsSource" Value="{Binding DataContext.Items, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"/>
</Style>
</DataGridComboBoxColumn.EditingElementStyle>
</DataGridComboBoxColumn>
</DataGrid.Columns>
</DataGrid>
这个例子中,我们使用了DataGridComboBoxColumn,并绑定到ViewModel中的SelectedItem属性。ComboBox的ItemsSource使用了DataGrid的DataContext中的Items属性,因此我们需要通过RelativeSource指定绑定源。
希望这个例子能够帮助您实现MVVM模式下的DataGrid中ComboBox列的绑定。