简体   繁体   中英

Binding ElementName inside a DataTemplate

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?

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}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM