【问题标题】:Selecting an item in a combobox in an MVVM framework在 MVVM 框架的组合框中选择一个项目
【发布时间】:2011-07-30 08:24:35
【问题描述】:

我将 WPF 组合框绑定到 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}" />

和绑定到 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 方法?

【问题讨论】:

  • 你实现了INotifyPropertyChanged接口吗?
  • 是的,每次 SelectedItemType 和 SelectIndexItemCategory 更改属性都会被点击。问题在这里 SelectIndexItemCategory = ItemCategoryList.IndexOf(SelectedItemCategory);
  • 如果您使用 SelectedItem 绑定而不是 Index 会发生什么?
  • 谢谢!这很简单!
  • @Tigran,你能把这个回答给 Taufiq 接受吗?

标签: c# wpf mvvm combobox


【解决方案1】:

SelectedItem 上使用绑定而不是SelectedIndex

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-03
    • 1970-01-01
    • 1970-01-01
    • 2019-03-29
    • 1970-01-01
    • 2012-05-16
    • 1970-01-01
    相关资源
    最近更新 更多