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

时间:2018-09-06 10:03:35

标签: c# wpf mvvm combobox propertygrid

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

1 个答案:

答案 0 :(得分:2)

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

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

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