Phasma
Phasma

Reputation: 232

Silverlight element to element binding in generic.xaml

Is there a way to have element to element binding in Silverlight templated controls?

Example: I have two custom controls, SomeControl and CustomSlider. SomeControl has a dependency property called someValue. I want to bind the value of CustomSlider to this property, so my generic.xaml file looks like this:

<Style TargetType="local:SomeControl">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="local:SomeControl">
                <...>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
<Style TargetType="local:CustomSlider">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="local:CustomSlider">
                <Slider Value="{Binding someValue, ElementName=local:SomeControl}" />
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

and this is my dependency property:

  public int someValue, 
    {
        get { return (int)GetValue(someValueProperty); }
        set { SetValue(someValueProperty, value); }
    }
    public static readonly DependencyProperty (someValueProperty) =
        DependencyProperty.Register(someValue); typeof(int), typeof(SomeControl,
          new PropertyMetadata(0));

This throws an "BindingExpression_CannotFindElementName" exception.

Upvotes: 0

Views: 435

Answers (1)

Zabavsky
Zabavsky

Reputation: 13640

You can't use it like this. A binding through ElementName should be used to specific element instance, not style. You can create other dependency property, say SliderValue in your CustomSlidercontrol and bind to it.

<local:SomeControl x:Name="SomeControl"/>
<local:CustomSlider SliderValue="{Binding someValue, ElementName=SomeControl}"/>

And change your Slider Value from template when your SliderValue property changes;

Upvotes: 1

Related Questions