Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to show a list of Customer objects in a WPF ItemsControl. I've created a DataTemplate for this:

    <DataTemplate DataType="{x:Type myNameSpace:Customer}">
        <StackPanel Orientation="Horizontal" Margin="10">
            <CheckBox"></CheckBox>
            <TextBlock Text="{Binding Path=Number}"></TextBlock>
            <TextBlock Text=" - "></TextBlock>
            <TextBlock Text="{Binding Path=Name}"></TextBlock>
        </StackPanel>
    </DataTemplate>

So what I want basically is a simple list (with checkboxes) that contains NUMBER - NAME. Isn't there a way in which I can concat the number and name directly in the Binding part?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
365 views
Welcome To Ask or Share your Answers For Others

1 Answer

There is StringFormat property (in .NET 3.5 SP1), which you probably can use. And usefull WPF binding cheat sheat can found here. If it doesn't help, you can allways write your own ValueConverter or custom property for your object.

Just checked, you can use StringFormat with multibinding. In your case code will be something like this:

<TextBlock>
  <TextBlock.Text>
    <MultiBinding StringFormat=" {0} - {1}">
        <Binding Path="Number"/>
        <Binding Path="Name"/>
    </MultiBinding>
  </TextBlock.Text>
</TextBlock>

I had to start format string with space, otherwise Visual Studio wouldn't build, but I think you will find way get around it :)

Edit
The space is needed in the StringFormat to keep the parser from treating {0} as an actual binding. Other alternatives:

<!-- use a space before the first format -->
<MultiBinding StringFormat=" {0} - {1}">

<!-- escape the formats -->
<MultiBinding StringFormat="{0} - {1}">

<!-- use {} before the first format -->
<MultiBinding StringFormat="{}{0} - {1}">

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...