.net DisplayMemberPath 串联
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10187375/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
DisplayMemberPath concatenation
提问by unairoldan
I am trying to bind two values to a ComboBox display value, but I do not know how to do.
我试图将两个值绑定到一个 ComboBox 显示值,但我不知道该怎么做。
This way does not work:
这种方式不起作用:
cboRegion.DisplayMemberPath = "idregion" + "description";
Does anyone know how to do that in C#?
有谁知道如何在 C# 中做到这一点?
回答by Heinzi
Unfortunately, this is not possible with DisplayMemberPath. You have the following alternatives:
不幸的是,这是不可能的DisplayMemberPath。您有以下选择:
Specify a DataTemplate
<ComboBox> <ComboBox.ItemTemplate> <DataTemplate> <TextBlock> <TextBlock.Text> <MultiBinding StringFormat="{}{0}: {1}"> <Binding Path="idregion"/> <Binding Path="description"/> </MultiBinding> </TextBlock.Text> </TextBlock> </DataTemplate> </ComboBox.ItemTemplate> </ComboBox>(If you are wondering about the empty braces in the StringFormat attribute, see: What do the {} brackets mean in the StringFormat section of a Binding syntax?)
Add a property or field to your data source. How to do that depends on your data source:
If your combo box is bound to a DataTable, add a DataColumn and fill its values in a loop. Alternatively, change your SQL and add the concatenated value to your
SELECTclause.If your combo box is bound to a POCO or entity framework object, add a property that returns the concatenation.
指定数据模板
<ComboBox> <ComboBox.ItemTemplate> <DataTemplate> <TextBlock> <TextBlock.Text> <MultiBinding StringFormat="{}{0}: {1}"> <Binding Path="idregion"/> <Binding Path="description"/> </MultiBinding> </TextBlock.Text> </TextBlock> </DataTemplate> </ComboBox.ItemTemplate> </ComboBox>(如果您想知道 StringFormat 属性中的空大括号,请参阅:绑定语法的 StringFormat 部分中的 {} 括号是什么意思?)
向数据源添加属性或字段。如何做到这一点取决于您的数据源:
如果您的组合框绑定到 DataTable,请添加一个 DataColumn 并在循环中填充其值。或者,更改您的 SQL 并将串联值添加到您的
SELECT子句中。如果您的组合框绑定到 POCO 或实体框架对象,请添加一个返回串联的属性。
回答by Thomas Levesque
You need to use a DataTemplate:
你需要使用一个DataTemplate:
<ComboBox Name="cboRegion">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock>
<Run Text="{Binding idregion}" />
<Run Text="{Binding description}" />
</TextBlock>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
回答by user3542322
You could create a view, concatenate the two fields, and then refer to the concatenated field name in your DisplayMemberPath property in c#, after referring to the new view in your itemssource property (and after updating your entity framework model)
您可以创建一个视图,连接两个字段,然后在引用 itemssource 属性中的新视图后(以及更新实体框架模型后)在 c# 中的 DisplayMemberPath 属性中引用连接的字段名称

