tags:

views:

38

answers:

2

Hello, I have an object, say Person, which has First Name and Last Name properties. on my WPF UI, I have a Label which needs to bind to the full name. how can i concatinate in xaml. . i dont want to create another readonly property like FullName{get FisrtName+""+LastName} . can we do this in XAML?. Thanks, Rey.

+4  A: 

A couple of options:

Option 1: Single TextBlock (or Label) with a MultiBinding:

<TextBlock>
    <TextBlock.Text>
        <MultiBinding StringFormat="{}{0} {1}">
            <Binding Path="FirstName" />
            <Binding Path="LastName" />
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>

Option 2: Multiple TextBlocks (or Labels) in a horizontal StackPanel:

<StackPanel Orientation="Horizontal">
    <TextBlock Text="{Binding FirstName}" />
    <TextBlock Text=" " />
    <TextBlock Text="{Binding LastName}" />
</StackPanel>

Personally I'd go with option 1.

Matt Hamilton
+1 for MultiBinding. It's so under-appreciated.
Josh Einstein
I will follow Option 1. Thanks for the Answer.
Rey
one more thing Matt, How can i display fullname in case of a DatagridComboBoxColumn. Like in the following XAML.<dg:DataGridComboBoxColumn Header="Person Name" ItemsSource="{Binding Source={StaticResource PersonContactVM}, Path=PersonList}" DisplayMemberPath="FirstName"<!-- here i want to display Fullname --> SelectedItemBinding="{Binding Person}" SelectedValuePath="ID"/>
Rey
I haven't played with the DataGrid at all, so I can't give you a good answer. You won't be able to do it with DisplayMemberPath, but you might be able to do it if there's an ItemTemplate or equivalent in DataGrid.
Matt Hamilton
+2  A: 

I love the MultiBinding approach Matt described. However, I should also note that depending on the architecture of your application creating the FullName property that you didn't want to create is an equally valid (and arguably a more desirable) choice.

If you were using Model-View-ViewModel, you would have a ViewModel that would expose a FullName property for the sole purpose of binding it to the view.

For example, if the requirements suddenly changed such that you needed to be able to format it as First + Last or Last, First depending on a configuration setting it'd be much easier to do on the ViewModel. Likewise, writing a unit test to validate that a change to FirstName or LastName also results in an appropriate change in FullName is not practical using the straight XAML approach.

But like I said it all depends on the architecture of your application.

Josh Einstein
I almost included something in my post about doing it in code-behind (eg MVVM). So +1 for that. Mutual admiration society or what? :)
Matt Hamilton
We are using the MVVM Pattern. in this case, on my UI i have a DataGrid with column FullName. This DataGrid's ItemsSource is ObservableCollection of Persons. so i can't really have a FullName in my ViewModel. Thanks for the reply..
Rey