【问题标题】:Binding ElementName inside a DataTemplate在 DataTemplate 中绑定 ElementName
【发布时间】:2012-07-14 07:36:58
【问题描述】:

我正在尝试绑定依赖于同一 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 如果没有,我做错了什么?

【问题讨论】:

  • 你应该在visual studio的输出窗口中看到相关的绑定错误。

标签: c# wpf xaml data-binding


【解决方案1】:

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

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

{Binding SelectedItem, Source={x:Reference ComboList}}

【讨论】:

  • 糟糕,我忘了我在 ComboBox 列表中的项目周围有一个包装器。它工作正常。谢谢!
  • 我认为最好补充一下 x:Reference 仅适用于 .NET 4.0 及更高版本。
  • 这是唯一对我有用的解决方案,因为从 DataTemplate 内部引用 ElementName 并不总是有效,具体取决于控件类型。
猜你喜欢
  • 2011-12-23
  • 1970-01-01
  • 2012-02-25
  • 2012-10-12
  • 1970-01-01
  • 1970-01-01
  • 2010-11-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多