OneWayToSource binding resetting target value

做~自己de王妃 提交于 2020-01-04 04:13:05

问题


Why is the OneWayToSource binding resetting my target value? Here is the binding code:

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

I set the "Color" dependency property in xaml. But it gets overwritten by the binding. After that the binding works ok. So, essentially my problem is: I can't give a starting value to the "Color" property because it gets overwritten by the binding.

EDIT:

I made a workaround that solves the problem, but still don't understand why OneWayToSource behaves like that:

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

EDIT 2:

Found a possible solution: I have to set:

binding.FallbackValue = this.Color;

回答1:


You could use the BindingOperations class to set the binding:

BindingOperations.SetBinding(
    brush, SolidColorBrush.ColorProperty, new Binding("Color") { Source = this });


来源:https://stackoverflow.com/questions/13772749/onewaytosource-binding-resetting-target-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!