WPF DataTrigger不起作用。

时间:2014-11-05 14:15:28

标签: c# wpf styles datatrigger

我设计了一个WPF页面,应该可以更改主题(黑暗主题和灯光主题)。我是WPF的新手,使用DataTrigger找到了我的问题的解决方案,但它不起作用。 3个小时后我尝试了10种不同的解决方案/教程,但我不知道我做错了什么......

xml代码:

<Page
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
  xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
  xmlns:local="clr-namespace:VMQWPFApplication.Pages" x:Class="VMQWPFApplication.Pages.MainPage" 
  mc:Ignorable="d" 
  d:DesignHeight="400" d:DesignWidth="600"
Title="MainPage">

<Page.Resources>
    <Style x:Key="styleWithTrigger" TargetType="{x:Type Rectangle}">
        <Setter Property="Fill" Value="Blue"/>
        <Style.Triggers>
            <DataTrigger Binding="{Binding DarkTheme, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:MainPage}}}" Value="True">
                <Setter Property="Fill" Value="Red"/>
            </DataTrigger>
        </Style.Triggers>
    </Style>
</Page.Resources>

<DockPanel>
    <!--Toolbar-->
    ...

    <!--Body-->
    <Grid>
        <Rectangle Style="{StaticResource styleWithTrigger}"/>
    </Grid>
</DockPanel>

这里是cs:

namespace VMQWPFApplication.Pages
{
    /// <summary>
    /// Interaction logic for MainPage.xaml
    /// </summary>
    public partial class MainPage : Page
    {
        public bool DarkTheme { get; set; }

        public MainPage()
        {
            InitializeComponent();
            DarkTheme = false;
        }

        private void TestButton_Click(object sender, RoutedEventArgs e)
        {
            DarkTheme = true;
        }
    }
}

一开始矩形为蓝色,但不会改变。

1 个答案:

答案 0 :(得分:2)

您的MainPage.xaml.cs文件未实现INotifyPropertyChanged接口。为此,您应该添加/更改以下内容:

public partial class MainPage : Page, INotifyPropertyChanged

#region INotifyPorpertyChanged Memebers 

    public event PropertyChangedEventHandler PropertyChanged;

    protected void NotifyPropertyChanged(string propertyName = "")
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }

#endregion

我会将您的DarkTheme属性更改为:

private bool _darkTheme;
public bool DarkTheme { get { return _darkTheme; } set { _darkTheme = value; NotifyPropertyChanged("DarkTheme"); }

现在,当您更新DarkTheme时,它将引发Change Property Event。我还将DataContext放入Page make:

DataContext="{Binding RelativeSource={RelativeSource Self}}"