3

为什么 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 中设置了“颜色”依赖属性。但它会被绑定覆盖。之后绑定工作正常。所以,基本上我的问题是:我不能给“颜色”属性一个起始值,因为它被绑定覆盖了。

编辑:

我做了一个解决问题的解决方法,但仍然不明白为什么 OneWayToSource 会这样:

System.Windows.Media.Color CurrentColor = this.Color;
                this.SetBinding(ColorPicker.ColorProperty, binding);
                this.Color = CurrentColor;

编辑2:

找到了一个可能的解决方案:我必须设置:

binding.FallbackValue = this.Color;
4

1 回答 1

1

您可以使用BindingOperations类来设置绑定:

BindingOperations.SetBinding(
    brush, SolidColorBrush.ColorProperty, new Binding("Color") { Source = this });
于 2012-12-08T12:49:41.820 回答