WPF 4.0 Datagrid を使用してアプリケーションを開発しています。私の Datagrid グリッドには、1 つの datagridcomboboxcolumn と 1 つの datagridtextcolumn があります。datagridcomboboxcolumn の SelectedIndex_Changed イベントを使用してデータグリッド テキスト セルの値を変更する方法は?
3948 次
1 に答える
1
WPF アプリケーションの作成には MVVM アプローチを使用することをお勧めします。一般に、これは、などの個別のイベントの処理を停止しSelectedIndex_Changed
、代わりに ViewModel (VM) および/または Model (M) 内の監視可能なオブジェクトにバインドすることを意味します。
このアーキテクチャを使用すると、問題を簡単に解決できます。SelectedItemBinding
DataGridComboBoxColumn を 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));
}
}
}
于 2011-01-20T16:21:24.580 に答える