Controlling XAML tags from C# code
I have a WPF application , and I would like to modify the background color of the UI based on the user's selection at run time .
Now 开发者_JAVA技巧, I want to create a button that changes the color each time its clicked , so this button must change a value from the XAML tags
Please , help me doing it , I need it badly Thanks
To make a control red from code:
yourControl.Background = Brushes.Red;
Thomas has given one example of what you could do.
Another option would be to bind the background colour to some property of your data context (probably the ViewModel if you're using MVVM) and make the button click change that property - possibly indirectly via commanding.
They're just different approaches - directly setting the background colour is certainly simpler than going via binding, but it may be less easily testable.
Another option would be to bind the background colour to a property in your DataContext, and update only the property's value when you click the button. This way, you also get to keep your logic and display responsibilities separate.
To say it simply. There is no difference between XAML and C#. In the end it both produces same executable code.
To change property on GUI you should either name your control through x:Name property and then set your property in the backend code file. Or you can DataBind your property to some backing field, preferably by using MVVM pattern.
But you should first understant how WPF works (ESPECIALY DataBinding) before moving to more advanced topics like MVVM.
精彩评论