WPF xaml DataTrigger绑定无法正常工作

时间:2014-07-18 18:37:43

标签: wpf xaml data-binding binding datatrigger

我使用xaml和C#创建了一个简单的应用程序,它将边框颜色绑定到布尔方法IsToday后面的代码。但不知怎的,它不起作用。

有人可以帮忙吗?我也试过了INotifyPropertyChanged,但它不起作用。如果有人能提供帮助,感激不尽,谢谢!

代码背后:

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词典

 <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>

2 个答案:

答案 0 :(得分:2)

您必须为DataContext

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

当然这只是 最初 ,之后对IsToday所做的每次更改都不起作用。如您所知,我们必须实施INotifyPropertyChanged

答案 1 :(得分:0)

您只需从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>