不好意思,我是菜鸟。我想单击按钮来更改文本块的背景颜色。变量的值可以更改,但是背景的颜色没有更改。有我的代码。请帮帮我。
Visual Studio 2017
WPF
TextBlock
<TextBlock Width="75" Height="75" HorizontalAlignment="Center" Margin="205,187,626,468" FontSize="48">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Setter Property="Text" Value="1" />
<Setter Property="Background" Value="Red" />
<Style.Triggers>
<DataTrigger Binding="{Binding Path=TestView,Mode=TwoWay}" Value="True">
<Setter Property="Text" Value="1" />
<Setter Property="Background" Value="Green" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
和按钮
<Button Margin="202,596,564,0" VerticalAlignment="Top" Width="134" Click="buttonClick">
</Button>
Xaml.cs
private bool testView = true;
public bool TestView
{
get { return testView; }
set { testView = value; }
}
private void buttonClick(object sender, RoutedEventArgs e)
{
TestView = false;
}
我希望当testView == true时,textblock的背景颜色为绿色;当testView == false时,textblock的背景颜色为Red。 并且文本在TextBlock的中间
答案 0 :(得分:1)
窗口(视图)未更新的原因是,您需要将更改通知给它。要在WPF中执行此操作,必须实现INotifyPropertyChanged
接口,并相应地设置DataContext。通常,应使用MVVM设计模式完成此操作,但是为了回答您的问题,以下是使用当前设置进行操作的方法:
public partial class Window1 : Window, INotifyPropertyChanged
{
private bool testView = true;
public bool TestView
{
get { return testView; }
set
{
if (testView != value)
{
testView = value;
OnPropertyChanged("TestView");
}
}
}
public Window1()
{
InitializeComponent();
DataContext = this;
}
private void buttonClick(object sender, RoutedEventArgs e)
{
TestView = false;
}
#region INotify
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion INotify
}