views:

143

answers:

2

Can I data bind two proporties values in a single textblock.

For Example some thing like following, though this is noth the correct code:

 <TextBlock Margin="5" Text="{Binding property1,Binding property2}" Style="{StaticResource Style1}" />

I want to display two values in a single text block .

Thanks, Subhendu

A: 

mmm, AFIK you can't do that.

however, you CAN do it a couple of ways.

One, create a Converter that takes your object and returns the two properties

    public class Formatter : IValueConverter
    {
       public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
       {
              // do some stuff with value to get your information
              return myvalue;
       }

      public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
      {
            throw new NotImplementedException();
      }

}

// make a static resource of your converter

<Resources>
    <myns:Converter x:Key="MyConverter"/>
</Resource>

// now use it in your binding

second, you can nest textblocks like so (well, maybe not in silverlight, but in WPF you can) ...

<TextBlock ...>
    <TextBlock .../>
    <TextBlock .../>
</TextBlock>
Muad'Dib
+1  A: 

When you use MVVM you would typically create a third property that concatenates the two others and bind to that one.

public string Prop1 { get; set; }

public string Prop2 { get; set; }

public string Prop3 { get {return string.Format("{0} {1}", Prop1, Prop2); } }

In you xaml, you would then bind to Prop3. If you want two way binding, you can implement a setter for Prop3 that updates Prop1 and Prop2.

Cheers, Phil

Phil

related questions