c# - 在 MVVM 框架的组合框中选择一个项目

标签 c# wpf mvvm combobox

我将 WPF 组合框绑定(bind)到 ObservableCollection ItemCategoryList

 <ComboBox Grid.Column="1" Grid.Row="2" Height="Auto" HorizontalAlignment="Stretch" Margin="0" Name="comboBox1" VerticalAlignment="Stretch" Width="Auto" ItemsSource="{Binding Path= ItemCategoryList}" DisplayMemberPath="Name" SelectedItem="{Binding Path=SelectedItemCategory,UpdateSourceTrigger=PropertyChanged}"  SelectedIndex="{Binding Path=SelectIndexItemCategory}" />

并且绑定(bind)到 ObservableCollection ItemTypeList 和 ItemType 的 DataGrid 具有 ItemCategory 类型的嵌套对象 ItemCategory

    <DataGrid AutoGenerateColumns="False" Grid.ColumnSpan="3" Grid.Row="3" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Width="Auto" Margin="10" 
              ItemsSource="{Binding ItemTypeList}"
              SelectedItem="{Binding SelectedItemType}" 
              CanUserDeleteRows="False" 
              CanUserAddRows="False">
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding Path=ItemTypeID}" Header="ItemTypeID" IsReadOnly="True" Visibility="Hidden" />
            <DataGridTextColumn Binding="{Binding Path=Name}" Header="Item Type Name" IsReadOnly="True" />
            <DataGridTextColumn Binding="{Binding Path=ItemCategory.Name}" Header="Item Category" IsReadOnly="True" />
        </DataGrid.Columns>
    </DataGrid>

现在,当我在数据网格中选择一行时,我希望组合框选择该 ItemType 的相应 ItemCategory

    private ItemType selectedItemType;

    public ItemType SelectedItemType
    {
        get { return selectedItemType; }
        set { 
            selectedItemType = value;
            RaisePropertyChanged("SelectedItemType");
            if (selectedItemType != null)
            {
                ItemTypeName = selectedItemType.Name;
                SelectIndexItemCategory = ItemCategoryList.IndexOf(SelectedItemCategory);
            }


        }
    }

    private int selectIndexItemCategory;

    public int SelectIndexItemCategory
    {
        get { return selectIndexItemCategory; }
        set { selectIndexItemCategory = value;
        RaisePropertyChanged("SelectIndexItemCategory");
        }
    }

编辑:

问题似乎出在这里:

SelectIndexItemCategory = ItemCategoryList.IndexOf(SelectedItemCategory);

Collection 中没有我可以使用的 find 方法吗?

最佳答案

SelectedItem 上使用绑定(bind)而不是 SelectedIndex

关于c# - 在 MVVM 框架的组合框中选择一个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6881984/

相关文章:

C#:通过进程名获取所有窗口的WindowHandles

c# - 没有输出的单元测试类

ios - 为基于 iOS 的项目实现 MVC vs MVVM vs VIPER 的真实场景

c# - View 模型命令中的 BindingExpression 路径错误

c# - 将属性设置为另一个属性的值

c# - 内存中的 EF Core SQLite 异常 : SQLite Error 1: 'near "MAX": syntax error'

c# - 获取一个Microsoft.VisualStudio.TextLogic版本14必须安装在GAC中

.net - 有哪些方法可用于在 Storyboard Animations 中使用非固定值?

WPF ListView 始终聚焦最后添加的项目?

mvvm - MVVM Light中DataService和IDataService的作用是什么