【问题标题】:wpf control background 2-way binding only working one waywpf 控制背景 2-way 绑定只工作一种方式
【发布时间】:2016-04-05 22:16:16
【问题描述】:

我有这个按钮,在背景画笔上有一个双向绑定,我已经设置了一个依赖属性,我也在使用 INotifyPropertyChanged 接口。但是我仍然遇到两种方式绑定的问题。

如果我更新绑定到按钮的属性,按钮背景会改变,就像我期望的那样,但是如果我直接更新按钮背景(“button.Background = Brushes.Blue”),则属性不会更新。

这是按钮的 xaml:

<Button Background="{Binding ElementName=MainWindow,Path=TitleBrush,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>

属性:

public Brush TitleBrush 
{
    get 
    {
        return (Brush)GetValue(TitleBrushProperty);
    }
    set 
    {
        if (!_graph.TitleBrush.Equals(value)) 
        {
            _graph.TitleBrush = value;
            SetValue(TitleBrushProperty, value);
            NotifyPropertyChanged(nameof(TitleBrush));
        }
    }
}

public static readonly DependencyProperty TitleBrushProperty =
        DependencyProperty.Register(nameof(TitleBrush), typeof(Brush), typeof(MainWindow));

我改变背景颜色的两种方式:

TitleBrush = Brushes.Red; // This works great
button.Background = Brushes.Red; // This changes the background but doesn't update the property

感谢任何帮助。

【问题讨论】:

    标签: c# wpf data-binding


    【解决方案1】:

    TwoWay 用于将值设置为绑定属性并接受返回值。在您的情况下,您为这两种情况设置了一种方式 - 控制。控件没有发回属性值。 TwoWay 真正用于输入字段。如果您使用的是代码隐藏,则应使用绑定属性。

    正如BindingMode Enumeration documentation 所说:

    导致对源属性或目标属性的更改自动更新另一个。这种类型的绑定适用于可编辑的表单或其他完全交互的 UI 场景。

    【讨论】:

    • 好的,谢谢,我希望不是这样。但无论如何,我想我会想出别的办法。
    • 不客气。这就是 WPF 设计的工作方式。如果您需要以编程方式设置控件的颜色,您可能需要创建一个单独的 ViewModel,将属性放在那里,将一个实例设置为 DataContext,然后以这种方式使用它。直接访问/调用控件应该是最后的手段。
    猜你喜欢
    • 1970-01-01
    • 2011-03-22
    • 1970-01-01
    • 1970-01-01
    • 2016-10-07
    • 2015-10-12
    • 1970-01-01
    • 1970-01-01
    • 2021-04-16
    相关资源
    最近更新 更多