wpf控制背景双向绑定只能单向工作

时间:2016-04-05 22:16:16

标签: c# wpf data-binding

我有一个在背景画笔上有双向绑定的按钮,我已经设置了一个依赖属性,我也使用了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

感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

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

正如BindingMode Enumeration documentation所述:

  

导致对source属性或target属性的更改以自动更新另一个属性。此类绑定适用于可编辑表单或其他完全交互式UI方案。