当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - wpf control background 2-way binding only working one way

问题描述:

I have this button that has a two way binding on the background brush, I've set up a dependency property, I'm also making use of the INotifyPropertyChanged interface. But I'm still having problems with two way bindings.

If I update the property that's bound to the button, the buttons background changes, like i would expect however if I update the buttons background directly ("button.Background = Brushes.Blue") the property doesn't get updated.

Here is the xaml for the button:

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

The property:

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

The two ways I change the background color:

TitleBrush = Brushes.Red; // This works great

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

Any help is appreciated.

网友答案:

TwoWay is for setting values to a bound property and accepting a value back. In your case, you are setting it one way for both cases -- to the control. The control isn't sending a property value back. TwoWay is really meant for input fields. If you are using code-behind, you should use the bound property.

As the BindingMode Enumeration documentation states:

Causes changes to either the source property or the target property to automatically update the other. This type of binding is appropriate for editable forms or other fully-interactive UI scenarios.

分享给朋友:
您可能感兴趣的文章:
随机阅读: