WPF 如何在 MVVM 中使用 ComboBoxes 选定项作为 xctk:PropertyGrid 的 SelectedObject

WPF How to use a ComboBoxes selected item as a xctk:PropertyGrid's SelectedObject in MVVM

我有一个组合框,其中包含不同类型的项目,因此我无法绑定到列表。我已经在 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 使用对象列表作为它的结构,所以它可能无法正常工作,根据我的需要单独设置项目。

您可以像这样将 SelectedObject 属性 绑定到 ComboBox 中当前选定的项目:

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

您可能不想将 ComboBoxItems 添加到 XAML 标记中的 ComboBox,因为这样您将绑定到 ComboBoxItem,但这是另一个故事。