tags:

views:

194

answers:

3

hai am using the below binding to bind my value 'Name' to textblock1.

<TextBlock Text="{Binding Name}" />

now the problem is i want to bind another value called 'ID' with that same textblock1

is it possible to bind value like using Name + ID like that??? :)

+2  A: 

Use a ValueConverter

[ValueConversion(typeof(string), typeof(String))]
public class MyConverter: IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return string.Format("{0}:{1}", (string) value, (string) parameter);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {

        return DependencyProperty.UnsetValue;
    }
}

and in the markup

<src:MyConverter x:Key="MyConverter"/>

. . .

<TextBlock Text="{Binding Name, Converter={StaticResource MyConverter Parameter=ID}}" />
Preet Sangha
+10  A: 

You can use a MultiBinding combined with the StringFormat property. Usage would resemble the following:

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

Given a value of Name of 'Foo' and a value for ID of '1' you output in the TextBlock would be "Foo + 1".

Note that this is only supported in .NET 3.5 SP1 and 3.0 SP2.

Richard C. McGuire
Nice! I wish I knew this a couple weeks ago!!!
LnDCobra
+1 Much better than mine!
Preet Sangha
@LnDCobra - This was a little treat they tossed in w/ 3.5, people are usually excited when they find out about it :)
Richard C. McGuire
OUt of interst what does the {} in the format do?
Preet Sangha
@Preet - I'm actually not certain if the '{}' is necessary in this case, I included it since it was used on the MSDN sample. In general however, it is needed as an escape sequence for the XAML parser to avoid confusion with the Binding markup extension.
Richard C. McGuire
+1  A: 

If these are just going to be textblocks (and thus one way binding), and you just want to concatenate values, just bind two textblocks and put them in a horizontal stackpanel.

    <StackPanel Orientation="Horizontal">
        <TextBlock Text="{Binding Name}"/>
        <TextBlock Text="{Binding ID}"/>
    </StackPanel>

That will display the text (which is all Textblocks do) without having to do any more coding. You might put a small margin on them to make them look right though.

Cory

OffApps Cory
I realize that this may be a bit uncouth, but if you are going to mark something as "the answer" could you give it a up vote too? Those of us without gobs of rep appreciate it. in the grand scheme of things, it really doesn't come to much, but it does make us feel like we give out useful answer in a crowd of hundred pound brain toting developers.Cory
OffApps Cory