Wpf 如何将组合框类别项绑定到它';s类

Wpf 如何将组合框类别项绑定到它';s类,wpf,xaml,Wpf,Xaml,我有一个组合框,其中包含类别对象 <ComboBox Name="cbxCategory" Grid.Row="0" Grid.Column="1" FontSize="14" SelectedValue="{Binding Category, Mode=TwoWay}" Style="{StaticResource RegularControlStyles}"> <ComboBox.ItemTemplate> <DataTemplate&g

我有一个组合框,其中包含类别对象

<ComboBox Name="cbxCategory" Grid.Row="0" Grid.Column="1" FontSize="14" SelectedValue="{Binding Category, Mode=TwoWay}" Style="{StaticResource RegularControlStyles}">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <ComboBoxItem Content="{Binding CategoryName}" />
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>
除两个组合框(类别和子类别)外,所有字段都绑定良好

问题是combobox保存一个Category对象,EventFilter保存它的id。我可以做的一个解决方案就是更改属性:

public int CategoryId{get;set;}
致:

public int Category{get;set;}
但我不想那样做,我想保留身份证。 那我怎么做呢

我应该使用转换器吗? 如果我将组合框的绑定更改为:

SelectedValue=“{Binding CategoryId,Mode=TwoWay}”
它不能正常工作,因为它包含类别

有人能帮我吗


非常感谢。

您需要将
组合框的
SelectedValuePath
属性设置为属性名称。。。在本例中,我猜您的
类别
类中有一个名为“Id”的属性。然后,
SelectedValue
属性将提供所选
Category
对象中“Id”属性的值

您可以在MSDN的页面上找到更多信息

<ComboBox Name="cbxCategory" Grid.Row="0" Grid.Column="1" FontSize="14" 
    SelectedValuePath="CategoryId" SelectedValue="{Binding EventFilterItems.CategoryId}" 
    DisplayMemberPath="CategoryName" Style="{StaticResource RegularControlStyles}" />
您可能想要或需要设置
DisplayMemberPath
属性。。。这定义了所选
类别
对象的哪个属性将显示在控件中

您可以在MSDN的页面上找到更多信息

<ComboBox Name="cbxCategory" Grid.Row="0" Grid.Column="1" FontSize="14" 
    SelectedValuePath="CategoryId" SelectedValue="{Binding EventFilterItems.CategoryId}" 
    DisplayMemberPath="CategoryName" Style="{StaticResource RegularControlStyles}" />

请注意,您需要将
组合框的
SelectedValue
属性绑定到当前
EventFilter
对象的
CategoryId
属性