我在这里做错了什么?
我尝试在背景为红色时更改TextBox的文本值。
我可以使用任何其他属性触发此触发器(例如,当Width = 123时,文本正在正确更改) - 所以它必须是我的" Red"值
我试过这种方式:
<Style TargetType="{x:Type TextBox}" x:Key="t">
<Style.Triggers>
<Trigger Property="Background">
<Trigger.Value>
<SolidColorBrush Color="Red"/>
</Trigger.Value>
</Trigger>
<Trigger.Setters>
<Setter Property="Text" Value="Haha! Red detected!"/>
</Trigger.Setters>
</Trigger>
</Style.Triggers>
</Style>
那样
<Style TargetType="{x:Type TextBox}" x:Key="t">
<Style.Triggers>
<Trigger Property="Background" Value="Red"/>
<Trigger.Setters>
<Setter Property="Text" Value="Haha! Red detected!"/>
</Trigger.Setters>
</Trigger>
</Style.Triggers>
</Style>
没有反应。
这里是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>
<Style TargetType="{x:Type TextBox}" x:Key="t">
<Style.Triggers>
<Trigger Property="Background">
<Trigger.Value>
<SolidColorBrush Color="Red"/>
</Trigger.Value>
<Trigger.Setters>
<Setter Property="Text" Value="It's working!"/>
</Trigger.Setters>
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
<StackPanel>
<TextBox x:Name="tb" Style="{StaticResource t}" Text="White background" Background="White"></TextBox>
<Button Height="68" Content="ChangeBackground" Click="Button_Click"></Button>
</StackPanel>
</Window>
和代码隐藏
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApplication3
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
tb.Background = new SolidColorBrush(Colors.Red);
}
}
}
答案 0 :(得分:3)
Brush
不会覆盖Equals
,因此会通过引用进行比较,因此 Red 将始终等于 Red 。你需要比较颜色
<Style TargetType="{x:Type TextBox}" x:Key="t">
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=Background.Color}" Value="Red">
<Setter Property="Text" Value="Haha! Red detected!"/>
</DataTrigger>
</Style.Triggers>
</Style>