将封闭控件绑定到DataTemplate中的依赖对象的DP

时间:2014-07-22 23:34:24

标签: c# wpf data-binding datatemplate attached-properties

被封锁多天搜索我放弃了,想要求你提供建议。

我有以下DataTemplate:

<TextBox x:Name="FilterValueTextBox"
                 Grid.Column="1"
                 BorderThickness="1"
                 BorderBrush="{Binding TextBoxBorderBrush}"
                 VerticalAlignment="Stretch"
                 IsEnabled="{Binding FilterTypeValid}"
                 Background="{Binding TextBoxBackgroundBrush}"
                 VerticalContentAlignment="Stretch"
                 Text="{Binding RawText}"
                 SnapsToDevicePixels="True">
    <controls:OnScreenKeyboardControl.KeyboardDescriptor>
                    <controls:KeyboardDescriptor TextBoxRef="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorLevel=1, AncestorType={x:Type TextBox}}}" />
    </controls:OnScreenKeyboardControl.KeyboardDescriptor>
</TextBox>

KeyboardDescriptor是一个DependencyObject,包含"TextBoxRef"类型的依赖属性TextBox

这个机制在我的应用程序中无处不在除了这个特殊情况,其中绑定应该在datatemplate中发生。

我阅读了数十篇文章,声明所有内容都不是Visual Tree或Logical Tree的一部分,因此,ELementName和RelativeSource Binding应该失败。

显然,我设法可靠地证实了这一点。 有了上面的内容,我得到模板实例化的例外,“双向绑定(在本例中是默认的)需要路径或x路径”...... 如果没有上述绑定尝试,异常就会消失,但当然没有建立链接。

我现在的问题是:我可以以某种方式将封闭的TextBox作为参考传递给附加属性的DP的键盘描述符吗?

1 个答案:

答案 0 :(得分:0)

由我自己解决。将上面的xaml更改为:

<TextBox x:Name="FilterValueTextBox"
                 Grid.Column="1"
                 BorderThickness="1"
                 BorderBrush="{Binding TextBoxBorderBrush}"
                 VerticalAlignment="Stretch"
                 IsEnabled="{Binding FilterTypeValid}"
                 Background="{Binding TextBoxBackgroundBrush}"
                 VerticalContentAlignment="Stretch"
                 Text="{Binding RawText}"
                 SnapsToDevicePixels="True">
    <controls:OnScreenKeyboardControl.KeyboardDescriptor>
                    <controls:KeyboardDescriptor TextBoxRef="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type TextBox}}, Path=.}" />
    </controls:OnScreenKeyboardControl.KeyboardDescriptor>
</TextBox>

尽管如此,非常感谢!希望有一天能帮助别人。