为什么TextBlock保持黑色?
<Window x:Class="WpfApplication4.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="TextBlock" x:Key="style">
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Tag}" Value="True">
<Setter Property="Foreground" Value="Red" />
</DataTrigger>
</Style.Triggers>
</Style>
</Window.Resources>
<StackPanel>
<TextBlock Text="Test" Tag="True" Style="{StaticResource style}" />
</StackPanel>
</Window>
更新:好了,现在我还有另外一个问题。风格对财产变化没有反应:
<Window x:Class="WpfApplication4.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="TextBlock" x:Key="style">
<Style.Triggers>
<Trigger Property="Tag" Value="True">
<Setter Property="Foreground" Value="Red" />
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
<StackPanel>
<TextBlock Text="{Binding Prop}" Tag="{Binding Prop}" Style="{StaticResource style}" x:Name="text" />
<Button Content="Test" Click="Button_Click" />
</StackPanel>
</Window>
支持代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.ComponentModel;
namespace WpfApplication4
{
public partial class MainWindow : Window
{
private MyClass a = new MyClass();
public MainWindow()
{
InitializeComponent();
DataContext = a;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
a.Prop = true;
a.OnPropertyChanged("Prop");
}
}
public class MyClass : INotifyPropertyChanged
{
public bool Prop { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
public virtual void OnPropertyChanged(string property)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
}
TextBlock的文字发生了变化,但颜色不是
答案 0 :(得分:2)
将其更改为Property Trigger
<Style TargetType="TextBlock" x:Key="style">
<Style.Triggers>
<Trigger Property="Tag" Value="True">
<Setter Property="Foreground" Value="Red" />
</Trigger>
</Style.Triggers>
</Style>
TemplatedParent在ControlTemplate中运行。您的绑定不正确。这就是为什么它不起作用。
如果由于某种原因想要使用DataTrigger,那么正确的Binding将是
<DataTrigger Binding="{Binding Tag,RelativeSource={RelativeSource Self}}" Value="True">
答案 1 :(得分:2)
只需更改装订:
Binding="{Binding RelativeSource={RelativeSource Self}, Path=Tag}"
答案 2 :(得分:0)
这主要发生,因为Tag属性是object类型而不是string。以下链接中给出的解决方案可能对您有所帮助:
http://social.msdn.microsoft.com/forums/en-US/wpf/thread/d3424267-ed1f-4b30-90a1-5cca9843bd22
关于Textblock.Tag属性: http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.tag.aspx