根据另一个更新 DataGridComboBoxColumn 的项目源

Update itemsource of a DataGridComboBoxColumn depending on another

我正在使用带有 2 个 DataGridComboBoxColumns 的 Datagrid,我正在尝试根据第一列中选​​择的 'league' 更新第二列的项目源。

我的xaml:

            <DataGrid Name="DataTable" ItemsSource="{Binding Data}" AutoGenerateColumns="false">
                <DataGrid.Columns>
                    <DataGridComboBoxColumn x:Name="DataTableLeague" Header="League"  DisplayMemberPath="League.Name" SelectedValuePath="League.Name" SelectedValueBinding="{Binding LeagueName}">
                        <DataGridComboBoxColumn.EditingElementStyle>
                            <Style TargetType="{x:Type ComboBox}">
                                <EventSetter Event="SelectionChanged" Handler="CmbLeague_SelectionChanged" />
                            </Style>
                        </DataGridComboBoxColumn.EditingElementStyle>
                    </DataGridComboBoxColumn>
                    <DataGridComboBoxColumn x:Name="DataTableClub" Header="Club" DisplayMemberPath="Name" SelectedValuePath="Name" SelectedValueBinding="{Binding ClubName}"/>
                </DataGrid.Columns>
            </DataGrid>

隐藏代码:

public Editor()
{
      InitializeComponent();
      DataContext = this;
      DataTableLeague.ItemsSource = Leagues;         
}

private void CmbLeague_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    // ???
}

List<League> Leagues 包含 List<Clubs> 并且只能用作来源。选择存储在名为 Data.

的 ObservableCollection 中

您可以将第二个 ComboBoxItemsSource 绑定到数据对象的源 属性 并将其设置在 setter 中,而不是处理事件LeagueName 属性 绑定到第一个 ComboBox.

的选定值

确保您的数据对象实现 INotifyPropertyChanged 接口,并在您为第二个 ItemsSource 属性 设置源 属性 时发出更改通知 ComboBox,例如:

public class DataItem : INotifyPropertyChanged
{
    private string _leagueName;
    public string LeagueName
    {
        get { return _leagueName; }
        set 
        { 
            _leagueName = value;
            NotifyPropertyChanged();

            Teams = ...;
        }
    }


    private IEnumerable<Team> _teams;
    public IEnumerable<Team> Teams
    {
        get { return _teams; }
        set { _teams = value; NotifyPropertyChanged(); }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

}

XAML:

 <DataGridComboBoxColumn x:Name="DataTableClub" ItemsSource="{Binding Teams}" ... />

while seems to be a solid approach, i would like to see a solution using the CmbLeague_SelectionChanged event

好吧,您可以转换传递给事件处理程序的 ComboBoxDataContext,然后设置 属性:

private void CmbLeague_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    ComboBox cmb = (ComboBox)sender;
    if (cmb.DataContext is DataItem dataItem)
    {
        dataItem.Teams = ...;
    }
}

尽管如此,您仍然需要在数据 class 中实施 INotifyPropertyChanged