3

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;
kovacs lorand
  • 741
  • 7
  • 23
  • Couldn't you just bind the other way round? Something like `brush.SetBinding(SolidColorBrush.ColorProperty, new Binding("Color") { Source = this });` – Clemens Dec 08 '12 at 08:48
  • @Clemens: SolidColorBrush does not have SetBinding, that is why I have to go with OneWayToSource. – kovacs lorand Dec 08 '12 at 10:34
  • 1
    You might also want to read [this question](http://stackoverflow.com/q/4875751/1136211). – Clemens Dec 08 '12 at 14:00

1 Answers1

1

You could use the BindingOperations class to set the binding:

BindingOperations.SetBinding(
    brush, SolidColorBrush.ColorProperty, new Binding("Color") { Source = this });
Clemens
  • 123,504
  • 12
  • 155
  • 268
  • Yeah. Thanks. That's the best way to do without OneWayToSource. But I cant mark this as the answer because I want to figure out OneWayToSource. – kovacs lorand Dec 08 '12 at 13:29