Reputation: 858
I've created user control, the code for property which I want to bind is:
public Color Value
{
get
{
return (Color)this.GetValue(this.ValueProperty);
}
set
{
this.SetValue(this.ValueProperty, value);
}
}
public readonly DependencyProperty ValueProperty =
DependencyProperty.Register("Value", typeof(Color),
typeof(ColorSlider), new PropertyMetadata(Colors.Red))
I have two instances of this control in my page:
<local:ColorSlider x:Name="ColorsSlider1" />
<!--...-->
<local:ColorSlider x:Name="ColorsSlider3" />
And controls with values, that I want to bind to (from ColorSlider
to Canvas
and TextBlock
):
<Canvas x:Name="TileCanvas" Grid.Column="0" Margin="30" Width="173" Height="173"
Background="{Binding Value, ElementName=ColorsSlider1, Converter={StaticResource ColorToSolidBrushConverter}}">
<TextBlock x:Name="TileText" Text="dsdfsdfsf"
Foreground="{Binding Value, ElementName=ColorsSlider3, Converter={StaticResource ColorToSolidBrushConverter}}"/>
</Canvas>
So here's the problem. Binding to the Canvas
works, but binding to the TextBlock
doesn't! It is interesting that if I remove ColorSlider3
a binding to the TextBlock
will work! Also the binding will update the TextBlock
background if I set the binding to ColorSlider3
.
So it seems that I can bind values only from the latest instance of one UserControl
. Why is this the case and how can I fix it?
Upvotes: 0
Views: 179
Reputation: 2516
Your Dependency Property is not correctly defined... lacks the static part, and don't need the "this":
public Color Value
{
get
{
return (Color)this.GetValue(ValueProperty);
}
set
{
this.SetValue(ValueProperty, value);
}
}
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register("Value", typeof(Color),
typeof(ColorSlider), new PropertyMetadata(Colors.Red));
EDIT -----------------
Good to know it works for you. However, the real reason MS decided it to be static... never though about it, but according to MSDN:
"Custom Dependency Properties.
If you want properties on your custom types to support value expressions, property invalidation, per-type default values, inheritance, data binding, animation, or styling, you should back these CLR properties with a dependency property following these guidelines and procedures:
Upvotes: 2