kovacs lorand
kovacs lorand

Reputation: 906

OneWayToSource binding resetting target value

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;

Upvotes: 3

Views: 582

Answers (1)

Clemens
Clemens

Reputation: 128061

You could use the BindingOperations class to set the binding:

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

Upvotes: 1

Related Questions