繁体   English   中英

WPF C#Databind:在C#中,突出显示另一个控件时更改控件颜色

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

我对此感到困惑。

如果特定的文本框具有焦点,我只想简单地更改特定按钮的颜色。 使用C#进行数据绑定是否有可能,还是应该将常规事件触发器与方法一起使用?

使用数据绑定绝对可以做到这一点。

在您的文本框中,在XAML中设置IsFocused="{Binding MyTextBoxFocused}"

然后在您的按钮上,在XAML中设置Background="{Binding MyButtonColor}"

在您的ViewModel中,定义2个属性bool MyTextBoxFocused和Brush MyButtonColor。 确保您的ViewModel从INotifyPropertyChanged实现。

在MyTextBoxFocused

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

您可以使用如下代码来动态生成一个按钮,当名为“ txtBox1”的TextBox具有键盘焦点时,该按钮将变为红色:

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 };

暂无
暂无

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

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