Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DisplayMemberPath concatenation

Tags:

.net

combobox

wpf

I am trying to bind two values to a ComboBox display value, but I do not know how to do.

This way does not work:

cboRegion.DisplayMemberPath = "idregion" + "description";

Does anyone know how to do that in C#?

like image 333
unairoldan Avatar asked Apr 17 '12 08:04

unairoldan


3 Answers

Unfortunately, this is not possible with DisplayMemberPath. You have the following alternatives:

  • 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 SELECT clause.

    If your combo box is bound to a POCO or entity framework object, add a property that returns the concatenation.

like image 86
Heinzi Avatar answered Nov 05 '22 23:11

Heinzi


You need to use a DataTemplate:

<ComboBox Name="cboRegion">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock>
                <Run Text="{Binding idregion}" />
                <Run Text="{Binding description}" />
            </TextBlock>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>
like image 27
Thomas Levesque Avatar answered Nov 06 '22 00:11

Thomas Levesque


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)

like image 1
user3542322 Avatar answered Nov 06 '22 01:11

user3542322