我正在使用WPF 4.0 Datagrid开发一个应用程序。我的Datagrid网格有一个datagridcomboboxcolumn和一个datagridtextcolumn。如何使用datagridcomboboxcolumn的SelectedIndex_Changed事件更改datagrid文本单元格值?
答案 0 :(得分:1)
我建议使用MVVM方法来创建WPF应用程序。通常,这意味着您将停止处理诸如SelectedIndex_Changed
之类的离散事件,而是绑定到ViewModel(VM)和/或模型(M)中的可观察对象。
使用这种架构,解决您的问题很容易。只需将DataGridComboBoxColumn的SelectedItemBinding
绑定到DataGrid的ItemSource对象上的属性即可。然后,将DataGridTextColumn绑定到该属性。这在代码中有更好的解释:
查看:强>
<!-- Previous Window XAML omitted, but you must set it's DataContext to the ViewModel -->
<DataGrid
CanUserAddRows="False"
AutoGenerateColumns="False"
ItemsSource="{Binding People}"
>
<DataGrid.Columns>
<DataGridTextColumn
Header="Selected Name"
Binding="{Binding Name}"
/>
<DataGridComboBoxColumn
Header="Available Names"
SelectedItemBinding="{Binding Name}"
>
<DataGridComboBoxColumn.ElementStyle>
<Style TargetType="{x:Type ComboBox}">
<Setter Property="ItemsSource" Value="{Binding Names}" />
</Style>
</DataGridComboBoxColumn.ElementStyle>
<DataGridComboBoxColumn.EditingElementStyle>
<Style TargetType="{x:Type ComboBox}">
<Setter Property="ItemsSource" Value="{Binding Names}" />
</Style>
</DataGridComboBoxColumn.EditingElementStyle>
</DataGridComboBoxColumn>
</DataGrid.Columns>
</DataGrid>
<强>视图模型:强>
internal class MainWindowViewModel : ViewModelBase
{
private ObservableCollection<Person> _people;
public ObservableCollection<Person> People
{
get
{
_people = _people ?? new ObservableCollection<Person>()
{
new Person(),
new Person(),
new Person(),
};
return _people;
}
}
}
<强>型号:强>
internal class Person : INotifyPropertyChanged
{
private static ObservableCollection<string> _names = new ObservableCollection<string>()
{
"Chris",
"Steve",
"Pete",
};
public ObservableCollection<string> Names
{
get { return _names; }
}
private string _name;
public string Name
{
get { return _name; }
set
{
if (_name != value)
{
_name = value;
this.RaisePropertyChanged(() => this.Name);
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged<T>(Expression<Func<T>> expr)
{
var memberExpr = expr.Body as MemberExpression;
if (memberExpr != null)
{
var handler = this.PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(memberExpr.Member.Name));
}
}
else
{
throw new ArgumentException(String.Format("'{0}' is not a valid expression", expr));
}
}
}