user3854148
user3854148

Reputation: 49

WPF xaml DataTrigger binding not working

I have created a simple application using xaml and C# which binds the border color to the code behind boolean method IsToday. But somehow it's not working.

Can somebody help please? I've tried INotifyPropertyChanged as well but it doesn't work. Grateful if someone could help, thanks!

Code behind:

namespace WpfApplication3
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            IsToday = true;
            InitializeComponent();
        }

        public bool IsToday { get; set; }
    }
}

XAML

<Window x:Class="WpfApplication3.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <ResourceDictionary Source="Dictionary1.xaml">
        </ResourceDictionary>
    </Window.Resources>
        <Grid>
        <Border Style="{StaticResource Highlight}">
        </Border>
    </Grid>
</Window>

XAML Dictionary

 <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
        <Style TargetType="Border" x:Key="Highlight">
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsToday}" Value="True">
                    <Setter Property="Background" Value="Red"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding IsToday}" Value="False">
                    <Setter Property="Background" Value="Blue"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </ResourceDictionary>

Upvotes: 0

Views: 842

Answers (2)

Yuliam Chandra
Yuliam Chandra

Reputation: 14640

You can just set the context from xaml.

<Window x:Class="WpfApplication3.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525"
        DataContext="{Binding RelativeSource={RelativeSource Self}}">
    <!-- your code -->
</Window>

Upvotes: 0

King King
King King

Reputation: 63317

You have to set DataContext for your Window:

 public MainWindow() {
      InitializeComponent();
      DataContext = this;
      IsToday = true;
 }

Of course this works just initially, every changes made to IsToday after that won't work. As you know we have to implement the INotifyPropertyChanged.

Upvotes: 2

Related Questions