21

I am trying to bind a property that is dependent on a control within the same DataTemplate.

To illustrate:

<DataTemplate>
    <StackPanel Orientation="Horizontal">
        <ComboBox x:Name="ComboList"
                  ItemsSource="{Binding StatTypes}"
                  SelectedItem="{Binding SelectedStatType, Mode=TwoWay, FallbackValue='Select a type'}">
            <ComboBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Text}"/>
                </DataTemplate>
            </ComboBox.ItemTemplate>
        </ComboBox>

        <TextBox Grid.Column="1" MinWidth="40" Margin="5">
            <TextBox.Text>
                <Binding Path="StatValue">
                    <Binding.Converter>
                        <converter:PercentageConverter SelectedStatType="{Binding ElementName=ComboList, Path=SelectedItem}" />
                    </Binding.Converter>
                </Binding>
            </TextBox.Text>
        </TextBox>
    </StackPanel>
</DataTemplate>

But the property in the PercentageConverter is never set through this and I don't see why. Is this a naming scope issue? If so, I thought this would not matter since it is in the same DataTemplate If not, what am I doing wrong?

g t
  • 7,287
  • 7
  • 50
  • 85
Perry
  • 2,250
  • 2
  • 19
  • 24

1 Answers1

33

This is probably a namescope issue, the binding is not a framework element, any objects inside it will not share the outside namescope, nor is the binding in any tree, so relative source bindings should fail as well.

You can try using x:Reference instead, it uses a different mechanism:

{Binding SelectedItem, Source={x:Reference ComboList}}
H.B.
  • 166,899
  • 29
  • 327
  • 400
  • Doh My bad, I forgot I had a wrapper around the items in the ComboBox list. It works fine. Thanks! – Perry Jul 14 '12 at 22:26
  • 3
    I think it's good to add that `x:Reference` is only available from .NET 4.0 and above. – XAMlMAX Sep 01 '14 at 14:48
  • This is the only solution that worked for me as referencing `ElementName` from inside a `DataTemplate` doesn't always work depending upon the control type is seems. – Tronald Apr 21 '20 at 18:59