1

I have a viewmodel class that is assigned to my usercontrol

class UserControlViewModel
{
  public bool A { get; set; }
  public bool B { get; set; }
}

I'd like to bind some color to Background property that depends on A and B viewmodel properties. Something like:

A = true, B = true : Black 
A = false, B = false: White
A = true, B = false: Green
A = false, B = true: Red

<UserControl Background="{Binding Path=???}" />

I guess it's possible to create converter for my case that should accept UserControlViewModel instance and convert A and B properties into Brush instance and vise versa.

Or may be I shall create another property that implements conversion logic:

class UserControlViewModel
{
  public bool A { get; set; }
  public bool B { get; set; }
  public Brush MyBrush { 
    get {
          if (A && B) return Brushes.Black; 
          ...
    }
 }
}

What is the best way to solve my problem?

user149691
  • 587
  • 1
  • 5
  • 19

1 Answers1

3

Use DataTriggers instead:

<UserControl ...>
    <UserControl.Style>
        <Style TargetType="UserControl">
            <Style.Triggers>
                <MultiDataTrigger>
                    <MultiDataTrigger.Conditions>
                         <Condition Binding="{Binding A}" Value="True"/>
                         <Condition Binding="{Binding B}" Value="True"/>
                    </MultiDataTrigger.Conditions>

                    <Setter Property="Background" Value="Black"/>
                </MultiDataTrigger>

                <MultiDataTrigger>
                    <MultiDataTrigger.Conditions>
                         <Condition Binding="{Binding A}" Value="False"/>
                         <Condition Binding="{Binding B}" Value="False"/>
                    </MultiDataTrigger.Conditions>

                    <Setter Property="Background" Value="White"/>
                </MultiDataTrigger>

                <!-- and so on... -->

            </Style.Triggers>
        </Style>
    </UserControl.Style>
</UserControl>
Federico Berasategui
  • 43,562
  • 11
  • 100
  • 154
  • Thank you, @HighCore, now I realize what datatriggers for. But I also concerned about best practices when choose between converters, readonly viewmodel properties and datatrigger. I guess DataTriggers are not very flexible. What if I'm gonna put brush colors to configuration file or even database one day? Or what shall I do if logic is a bit more complicated? – user149691 Jul 04 '15 at 03:38
  • Thank you anyway, HighCore. I have found several articles on this subject:http://stackoverflow.com/questions/19466354/wpf-triggers-vs-converter – user149691 Jul 04 '15 at 10:38