C# WPF文本块背景色可以';t结合变量
对不起,我是一个noob。我想点击按钮来改变textblock的背景颜色。变量的值可以更改,但背景颜色没有更改。这是我的代码。请帮助我 Visual studio 2017 WPF 文本块C# WPF文本块背景色可以';t结合变量,c#,wpf,C#,Wpf,对不起,我是一个noob。我想点击按钮来改变textblock的背景颜色。变量的值可以更改,但背景颜色没有更改。这是我的代码。请帮助我 Visual studio 2017 WPF 文本块 <TextBlock Width="75" Height="75" HorizontalAlignment="Center" Margin="205,187,626,468" FontSize="48"> <TextBlock.Style> &
<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>
我希望当testView==true时,textblock的背景颜色为绿色;当testView==false时,textblock的背景颜色为红色。
文本在文本块的中间,窗口(视图)没有被更新的原因是因为你需要通知它一个改变。要在WPF中执行此操作,必须实现INotifyPropertyChanged
接口,并相应地设置DataContext。通常,这应该使用MVVM设计模式来完成,但为了回答您的问题,以下是如何使用当前设置来完成:
<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>
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
}
@xeroxion你能接受这个答案吗=]对不起,我最近很忙,我马上就要考试了