简体   繁体   中英

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. 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 ? 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.

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. 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 )

Another way is to implement Color as a dependency property. That way, you won't have to implement the INotifyPropertyChanged interface./

Have a look at this :

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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