问题描述
我正试图绑定一个依赖于控件的属性在同一个 DataTemplate
中。
I am trying to bind a property that is dependent on a control within the same 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
如果没有,我做错了什么?
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?
推荐答案
这可能是一个namescope问题,绑定不是一个框架元素,它内部的任何对象都不会共享外部名称镜像,也不会在任何树中绑定,所以相关的源绑定也应该失败。
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}}
这篇关于在DataTemplate中绑定ElementName的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!