WPF - Conditional binding with trigger

/* By Dylan SUN*/

WPF conditional binding enables the application to have different behaviors based on a pre-defined condition.

For example, you could use conditional binding to change the background color of your WPF application main window.

Suppose you have the following window declaration in you WPF application.

<Window x:Class="MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:views="clr-namespace:Views"
        xmlns:viewModels="clr-namespace:ViewModels"
        xmlns:controls="clr-namespace:Controls"
        Title="Main Application"
        Height="900"
        Width="1024"
        DataContext="{Binding Main, Source={StaticResource Locator}}">

You could add the following line in the window declaration :

Style="{DynamicResource ResourceKey=MainWindowStyle}"

And use the trigger to change the background color based on the binded property’s (EnvironmentIsSelected) value.

<Style TargetType="{x:Type Window}" x:Key="MainWindowStyle">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=EnvironmentIsSelected}" Value="False">
<Setter Property="Background" Value="Pink"/>
</DataTrigger>
<DataTrigger Binding="{Binding Path=EnvironmentIsSelected}" Value="True">
<Setter Property="Background" Value="{Binding SelectedEnvironment.Color}"/>
</DataTrigger>
</Style.Triggers>
</Style>

I Hope you find this article helpful!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章