C# WPF数据触发器不';不行。
我设计了一个WPF页面,应该可以改变主题(黑暗主题和光明主题)。我是WPF的新手,使用DataTrigger找到了问题的解决方案,但它不起作用。3小时后,我尝试了10种不同的解决方案/教程,但我不知道我做错了什么 xml代码:C# WPF数据触发器不';不行。,c#,wpf,styles,datatrigger,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"
<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>
...
这里是政务司司长:
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;
}
}
}
名称空间VMQWPFApplication.Pages
{
///
///MainPage.xaml的交互逻辑
///
公共部分类主页:第页
{
公共布尔暗场{get;set;}
公共主页()
{
初始化组件();
暗色调=假;
}
私有无效测试按钮\u单击(对象发送方,路由目标)
{
暗色调=真;
}
}
}
开始时,矩形为蓝色,但不会更改。您的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"); }
现在,当您更新暗色调时,它将引发更改属性事件。我还会将DataContext放入页面组成中:
DataContext="{Binding RelativeSource={RelativeSource Self}}"
搜索INotifyPropertyChanged
,您必须为viewmodel实现该接口,并正确引发已更改的属性。@MrApfelstrudelMainPage
未实现INotifyPropertyChanged
接口,并且DarkTheme
未引发PropertyChanged
事件或使DarkTheme
aDependencyProperty
同时将数据上下文放在页面标记中。DataContext=“{Binding RelativeSource{RelativeSource Self}}”我尝试了另一个解决方案,但INotifyPropertyChanged无效。这个有效^^^谢谢:)