简体   繁体   English

WPF与组合框绑定

[英]WPF Binding with Combobox

I have in WPF a combobox this way: 我在WPF中有这样一个组合框:

combobox.ItemsSource = await clientelocal.ObtenerVariablesAsync();
combobox.DisplayMemberPath = "Nombre"; 

In DisplayMemberPath I want to have two fields, something like: DisplayMemberPath我想要两个字段,例如:

combobox.ItemsSource = await clientelocal.ObtenerVariablesAsync();
combobox.DisplayMemberPath = "ID + Nombre";

but not how to do it, any ideas? 但不是怎么做,有什么想法吗?

Set the collection just like your doing but don't set the DisplayMemberPath. 像您一样设置集合,但不要设置DisplayMemberPath。 Here is an example: 这是一个例子:

MyComboBox.ItemsSource = await clientelocal.ObtenerVariablesAsync(); MyComboBox.ItemsSource =等待clientelocal.ObtenerVariablesAsync();

Then do this in the XAML: 然后在XAML中执行以下操作:

<ComboBox Name="MyComboBox">
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding Id}"/>
                    <TextBlock Text="{Binding Nombre}"/>
                </StackPanel>
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>

The key is that item template, you can do whatever you like in there to change the look of the items, give them color, change the padding through margins etc... 关键是项目模板,您可以在其中执行任何操作来更改项目的外观,为其赋予颜色,更改边距的填充等。

Instead of setting DisplayMemberPath , you need to define custom ItemTemplate to display more than one properties : 除了设置DisplayMemberPath ,您还需要定义自定义ItemTemplate来显示多个属性:

<ComboBox>
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal" >
                <TextBlock Text="{Binding ID}" Margin="0,0,10,0"/>
                <TextBlock Text="{Binding Nombre}"/>
            </StackPanel>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM