在DataTemplate中绑定ElementName

时间:2012-07-14 21:52:40

标签: c# wpf xaml data-binding

我正在尝试绑定依赖于同一DataTemplate内的控件的属性。

举例说明:

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

PercentageConverter中的属性从未设置过,我不明白为什么。这是一个命名范围问题吗?如果是这样,我认为这没关系,因为它在同一个DataTemplate 如果没有,我做错了什么?

1 个答案:

答案 0 :(得分:24)

这可能是一个名称范围问题,绑定不是框架元素,其中的任何对象都不会共享外部的名称范围,也不会在任何树中绑定,因此相对源绑定也应该失败。

您可以尝试使用x:Reference,它使用不同的机制:

{Binding SelectedItem, Source={x:Reference ComboList}}
相关问题