简体   繁体   English

如何在事件上动态更改TextBlock背景

[英]How to Change TextBlock Background Dynamically On An Event

Currently, I have a binding from a textblock in XAML to a Brush variable in the code. 目前,我已经从XAML中的文本块绑定到代码中的Brush变量。 If I set this variable statically, before I run the code, it will change it correctly. 如果我静态设置此变量,则在运行代码之前,它将正确更改它。 However, if I change the variable during runtime, on a click for example, the textblock doesn't update. 但是,如果我在运行时更改变量,例如单击一次,则文本块不会更新。 Is there some function that needs to be used to update the window or something like that? 是否需要一些功能来更新窗口或类似的东西?

You need to use a Binding by the sound of it, rather than setting the TextBlock.Background ? 您需要根据其声音使用Binding,而不是设置TextBlock.Background property to your variable: 变量的属性:

Binding myBinding = new Binding("MyPropertyName");
myBinding.Source = ViewModel.MyPropertyName;
myBinding.Mode = BindingMode.OneWay;
BindingOperations.SetBinding(textBlock, TextBlock.BackgroundProperty, myBinding);

You will also need to implement INotifyPropertyChanged in your ViewModel to fire the PropertyChanged event and notify the UI that the property has changed. 您还需要在ViewModel中实现INotifyPropertyChanged来触发PropertyChanged事件并通知UI属性已更改。

My guess is that you change to color without notifying. 我的猜测是您在不通知的情况下更改了颜色。 The binding cannot know the color changed. 绑定无法知道颜色已更改。

What you need to do is implement the INotifyPropertyChanged interface and raise the propertyChanged event in the Color property' setter. 您需要执行的是实现INotifyPropertyChanged接口,并在Color属性的设置器中引发propertyChanged事件。 This way, your binding will work as expected. 这样,您的绑定将按预期工作。 (look at this : https://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged(v=vs.110).aspx ) (看这个: https : //msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged ( v=vs.110 ) .aspx

Another way is to implement Color as a dependency property. 另一种方法是将Color实现为依赖项属性。 That way, you won't have to implement the INotifyPropertyChanged interface./ 这样,您就不必实现INotifyPropertyChanged接口。

Have a look at this : 看看这个:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM