在DataTemplate中绑定ElementName

Per*_*rry 18 c# data-binding wpf xaml

我试图绑定一个依赖于同一控件的属性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>
Run Code Online (Sandbox Code Playgroud)

但是这里的财产PercentageConverter从来没有通过这个,我不明白为什么.这是一个命名范围问题吗?如果是这样的话,我认为这不重要,因为它是相同的DataTemplate 如果不是,我做错了什么?

H.B*_*.B. 25

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

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

{Binding SelectedItem, Source={x:Reference ComboList}}
Run Code Online (Sandbox Code Playgroud)

  • 我认为添加`x:Reference`仅适用于.NET 4.0及更高版本是件好事. (2认同)