繁体   English   中英

WPF DataTrigger不起作用。

[英]WPF DataTrigger doesn't work.

我设计了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;
        }
    }
}

矩形开始时是蓝色,但不会改变。

您的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组成:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM