在App.xaml中,为UserCheckBox定义了一种样式。并且在DataTrigger中,属性值为LightStyle = true; UserCheckBox应该更改背景。但是他没有改变。 我尝试了通常的TextBlock并成功了。 如何解决?
App.xaml
<Application x:Class="COP.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ModernButton="clr-namespace:ModernButton;assembly=ModernButton"
xmlns:local="clr-namespace:COP"
xmlns:local1="clr-namespace:COP.ViewModel"
StartupUri="MainWindow.xaml">
<Application.Resources>
<Style x:Key="DefaultCheckBoxStyle" TargetType="local:UserCheckBox">
<Setter Property="Background" Value="#C3C3C3"/>
<Style.Triggers>
<DataTrigger Binding="{Binding LightStyle}" Value="True">
<Setter Property="Background" Value="White"/>
</DataTrigger>
</Style.Triggers>
</Style>
<Style x:Key="Sal" TargetType="TextBlock">
<Setter Property="Background" Value="#C3C3C3"/>
<Style.Triggers>
<DataTrigger Binding="{Binding LightStyle}" Value="True">
<Setter Property="Background" Value="White"/>
</DataTrigger>
</Style.Triggers>
<local1:MainViewModel x:Key="MyViewModel" />
</Application.Resources>
UserCheckBox.xaml.cs
public partial class UserCheckBox : UserControl, INotifyPropertyChanged
{
public UserCheckBox()
{
InitializeComponent();
DataContext = this;
MouseLeftButtonUp += delegate (object sender, MouseButtonEventArgs e) { IsChecked = !IsChecked; };
}
private bool _IsChecked = false;
public bool IsChecked
{
get { return _IsChecked; }
private set { _IsChecked = value; OnPropertyChanged("IsChecked"); }
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
Login.xaml
<Page x:Class="COP.Pages.Login"
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:COP.Pages"
xmlns:local1="clr-namespace:COP"
xmlns:ModernButton="clr-namespace:ModernButton;assembly=ModernButton"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="400"
Title="Login" DataContext="{DynamicResource MyViewModel}">
<Page.Resources>
<local1:BoolToStyle x:Key="Convert1"></local1:BoolToStyle>
</Page.Resources>
<Grid Height="Auto">
<local1:UserCheckBox x:Name="checkBox" HorizontalAlignment="Left" VerticalAlignment="Top" Style="{StaticResource DefaultCheckBoxStyle}">
</local1:UserCheckBox>
<TextBlock Margin="40,0,0,0" HorizontalAlignment="Left" Style="{StaticResource Sal}"></TextBlock>
</Grid>