2011-01-20 96 views

回答

1

我建議使用MVVM方法來創建WPF應用程序。通常,這意味着您將停止處理離散事件,如SelectedIndex_Changed,而是綁定到ViewModel(VM)和/或Model(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)); 
     } 
    } 
} 
相關問題