OneWayToSource绑定重置目标值
为什么OneWayToSource绑定重置我的目标值? 这是绑定代码:
SolidColorBrush brush = GetTemplateChild("PART_PreviewBrush") as SolidColorBrush; if (brush != null) { Binding binding = new Binding("Color"); binding.Source = brush; binding.Mode = BindingMode.OneWayToSource; this.SetBinding(ColorPicker.ColorProperty, binding); }
我在xaml中设置了“Color”依赖项属性。 但它会被绑定覆盖。 之后,绑定工作正常。 所以,基本上我的问题是:我不能给“Color”属性一个起始值,因为它被绑定覆盖了。
编辑:
我做了一个解决问题的解决方法,但仍然不明白为什么OneWayToSource的行为如下:
System.Windows.Media.Color CurrentColor = this.Color; this.SetBinding(ColorPicker.ColorProperty, binding); this.Color = CurrentColor;
编辑2:
找到了一个可能的解决方案:我必须设置:
binding.FallbackValue = this.Color;
您可以使用BindingOperations类来设置绑定:
BindingOperations.SetBinding( brush, SolidColorBrush.ColorProperty, new Binding("Color") { Source = this });