首页 > 解决方案 > WPF 如何将 ComboBoxes 选定项用作 xctk:PropertyGrid 在 MVVM 中的 SelectedObject

问题描述

我有一个组合框,其中包含不同类型的项目,因此我无法绑定到列表。我已经单独设置了 xaml 中的项目,因为只有两个项目,所以在这种情况下不用担心维护开销。我还有一个属性网格(来自 Xceed),并且想将它的 selectedObject 设置为我的组合框的选定项。我正在使用 MVVM 模式,但找不到在 xaml 中设置属性网格选定对象的解决方案。这是组合框和属性网格的 xaml,没什么可看的,只是每个的声明。

<ComboBox Grid.Row="0" Name="TestComboBox" HorizontalAlignment="Left" Margin="0,0,0,0" VerticalAlignment="Top" Width="Auto">
    <ComboBoxItem <!-- Set the item binding for item 1 to property in view model-->>Item 1</ComboBoxItem>
    <ComboBoxItem <!-- Set the item binding for item 2 to property in view model-->>Item 2</ComboBoxItem>
<xctk:PropertyGrid Grid.Row="1" HorizontalAlignment="Left" Margin="0,0,0,0" VerticalAlignment="Top" SelectedObject="{Binding <!-- Bind to comboBoxes selected item-->}"/>

我不确定这是否可能,因为我认为 ComboBox 使用对象列表作为其结构,因此它可能无法正常工作,根据需要单独设置项目。

标签: c#wpfmvvmcomboboxpropertygrid

解决方案


您可以将SelectedObject属性绑定到当前选定的项目,ComboBox如下所示:

<xctk:PropertyGrid ... SelectedObject="{Binding SelectedItem, ElementName=TestComboBox}">

您可能不想在 XAML 标记中添加ComboBoxItemsComboBox因为那样您将绑定到 a ComboBoxItem,但那是另一回事了。


推荐阅读