Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF binding to two properties

Tags:

binding

wpf

I have a WPF control that has a Message property.

I currently have this:

 <dxlc:LayoutItem >
            <local:Indicator Message="{Binding PropertyOne}" />
 </dxlc:LayoutItem>

But i need that Message property to be bound to two properties.

Obviously can't be done like this, but this can help explain what it is I want:

<dxlc:LayoutItem >
            <local:Indicator Message="{Binding PropertyOne && Binding PropertyTwo}" />
 </dxlc:LayoutItem>
like image 380
mo alaz Avatar asked Apr 22 '14 16:04

mo alaz


3 Answers

<TextBlock.Text>
    <MultiBinding StringFormat="{}{0} {1}">
        <Binding Path="FirstName"/>
        <Binding Path="LastName"/>
    </MultiBinding>
</TextBlock.Text>
like image 199
adPartage Avatar answered Nov 05 '22 05:11

adPartage


Try use the MultiBinding:

Describes a collection of Binding objects attached to a single binding target property.

Example:

XAML

<TextBlock>
   <TextBlock.Text>
       <MultiBinding Converter="{StaticResource myNameConverter}"
                     ConverterParameter="FormatLastFirst">
          <Binding Path="FirstName"/>
          <Binding Path="LastName"/>
       </MultiBinding>
   </TextBlock.Text>
</TextBlock>

Converter

public class NameConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        string name;

        switch ((string)parameter)
        {
            case "FormatLastFirst":
                name = values[1] + ", " + values[0];
                break;
            case "FormatNormal":
                default:
                name = values[0] + " " + values[1];
                break;
        }

        return name;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        string[] splitValues = ((string)value).Split(' ');
        return splitValues;
    }
}
like image 39
Anatoliy Nikolaev Avatar answered Nov 05 '22 05:11

Anatoliy Nikolaev


You can't do And operation in XAML.

Create wrapper property in your view model class which will return and of two properties and bind with that property instead.

public bool UnionWrapperProperty
{
   get
   {
      return PropertyOne && PropertyTwo;
   }
}

XAML

<local:Indicator Message="{Binding UnionWrapperProperty}" />

Another approach would be to use MultiValueConverter. Pass two properties to it and return And value from the converter instead.

like image 8
Rohit Vats Avatar answered Nov 05 '22 04:11

Rohit Vats