Yellow
Yellow

Reputation: 3957

Why are the following Binding expressions not the same?

I am trying to set the text of a TextBox inside a custom user control. The following works fine:

<Style TargetType="{x:Type MyCustomControl}"  >
    <Setter Property="Template" >
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type MyCustomControl}">

                <Canvas>
                    <TextBox Text="{Binding CustomControlText, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type MyCustomControl}}}">
                </Canvas>

            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

I tried to separate out the Text property of TextBox explicitly, initially to add a MultiBinding. When this didn't work, I noticed that also with a single Binding it didn't work. I mean the following:

<Canvas>
     <TextBox>
         <TextBox.Text>
             <Binding Path="CustomControlText" Source="{RelativeSource FindAncestor, AncestorType={x:Type MyCustomControl}}"/>
         </TextBox.Text>
     </TextBox>
</Canvas>

I thought this should be exactly equivalent to the former case, but this doesn't actually work. Though it compiles fine, this Binding never finds any value. Why are the two different, and how can the latter be fixed into a functioning expression?

Upvotes: 0

Views: 49

Answers (1)

Mike Fuchs
Mike Fuchs

Reputation: 12319

Use RelativeSource instead of Source in your Binding.

<Binding Path="CustomControlText" RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type MyCustomControl}}"/>

Upvotes: 3

Related Questions