How to I bind the Background color of a button to a class property that can change?

Confession: I'm new to WPF.

I have a class and a property (shortened for convenience)

Class UserPreference
   Property ButtonColor as String

and I have a button whose Background property should be set to the property.

What's the best way to do this with XAML? The ButtonColor property might change and the button must reflect this change.

Thanks.

AIBMassAsked:
Who is Participating?
 
lazyberezovskyCommented:
1) Add binding to button Background property
<Button x:Name="button1" Background="{Binding ButtonColor, Mode=OneWay}" Content="Ok" />
2) Implement INotifyPropertyChanged interface in your UserPreference class.
When ButtonColor property changed you should raise PropertyChanged event.
E.g.
If PropertyChanged <> Nothing Then
     PropertyChanged(Me, New PropertyChangedEventArgs("ButtonColor"))

Example: http://www.switchonthecode.com/tutorials/wpf-tutorial-binding-converters
0
 
mikebirtCommented:
Hi,

I think if you bind to the Background property you need to convert to a brush - or your binding source needs to be a brush (SolidColorBrush, LinearGradiant etc...).
However, if you have the color property - or only want to deal with colors, you can provide the brush in your Xaml and bind the color property of that;

HTH

Mike
        <Button x:Name="myBtn">
            <Button.Background>
                <SolidColorBrush Color="{Binding Path=ButtonColor}" />
            </Button.Background>
        </Button>

Open in new window

0
 
AIBMassAuthor Commented:
Very good reference provided.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.