我将一组对象绑定(bind)到 ComboBox 。我想要实现的是一个组合框,显示我的对象的两个属性。但是,我还没有弄清楚如何让组合框显示多个 DisplayMemberPaths 。这可能吗?

这是我目前设置绑定(bind)和设置 DisplayMemberPath 的方式:

Binding comboBinding = new Binding();
comboBinding.Source = squad_members; //squad_members is the object collection

BindingOperations.SetBinding(Character_ComboBox, ComboBox.ItemsSourceProperty, comboBinding);
Character_ComboBox.DisplayMemberPath = "Name"; //
//Character_ComboBox.DisplayMemberPath = "Name" + "Age"; //failed attempt
Character_ComboBox.SelectedValuePath = "Name";

最佳答案

首先,您应该在 XAML 中进行绑定(bind),而不是在代码后面。

您可以提供 ItemTemplate 并在 StringFormat 中使用 MultiBinding 像这样:

<ComboBox ItemsSource="{Binding YourCollection}">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock>
                <TextBlock.Text>
                    <MultiBinding StringFormat="{}{0} - {1}">
                        <Binding Path="Name"/>
                        <Binding Path="Age"/>
                    </MultiBinding>
                </TextBlock.Text>
            </TextBlock>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

如果您想在后面的代码中进行绑定(bind)。

您可以通过覆盖底层源类中的 ToString() 方法来 完全省略设置 DisplayMemberPath 。因为,如果未提供 DisplayMemberPath,则会在内部调用 ToString()。

假设您的集合是 List<Person> 类型,因此您可以在 Person 类上覆盖 ToString() :
public override string ToString()
{
    return Name + Age;
}

有了这个,绑定(bind)看起来像这样(不需要 DisplayMemberPath)
Binding comboBinding = new Binding();
comboBinding.Source = squad_members; //squad_members is the object collection

BindingOperations.SetBinding(Character_ComboBox,
                   ComboBox.ItemsSourceProperty, comboBinding);

关于c# - 多个 ComboBox.DisplayMemberPath 选项?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25346725/

10-10 07:35