user937036
user937036

Reputation: 391

WPF C# Databind: In C# Change a Control Color when another control is Highlighted

I'm perplexed on this one.

I want to simply change the COLOR of a specific button if a specific textbox has focus. Is this possible with databinding in C# or should I use a conventional event trigger with methods?

Upvotes: 0

Views: 177

Answers (2)

user128300
user128300

Reputation:

You could use code like this to dynamically generate a button which turns red when the TextBox named "txtBox1" has keyboard focus:

Style style = new Style { TargetType = typeof(Button) };
DataTrigger trigger = new DataTrigger
    {
        Binding = new Binding("IsKeyboardFocusWithin") { ElementName = "txtBox1" },
        Value = true
    };
trigger.Setters.Add(new Setter { Property = Button.BackgroundProperty,
     Value = Brushes.Red });
style.Triggers.Add(trigger);
Button btn = new Button { Content = "Test button", Style = style };

Upvotes: 0

Jon
Jon

Reputation: 3255

This is definitely possible with data binding.

On your textbox set IsFocused="{Binding MyTextBoxFocused}" in your XAML.

Then on your button, set Background="{Binding MyButtonColor}" in your XAML.

In your ViewModel, define 2 properties bool MyTextBoxFocused and a Brush MyButtonColor. Make sure your ViewModel implements from INotifyPropertyChanged.

On the MyTextBoxFocused

set 
{ 
MyButtonColor = value ? Color.Red : Color.Blue; 
RaisePropertyChanged("MyButtonColor"); 
RaisePropertyChanged("MyTextBoxFocused"); 
}

Upvotes: 2

Related Questions