在xaml中绑定的属性不能被绑定吗?

时间:2014-12-11 14:17:43

标签: wpf xaml properties operator-precedence

以下控件定义正常:

<local:TextBoxEx Text="{Binding Title, UpdateSourceTrigger=PropertyChanged, Delay=900}"
                 Foreground="{Binding Selection.Error, Converter={StaticResource BoolToErrorBrush}}"/>

当我使用样式更改它时:

<Style x:Key="TextBoxTitle" TargetType="local:TextBoxEx">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate>
                <local:TextBoxEx Text="{Binding Text, RelativeSource={RelativeSource TemplatedParent}, UpdateSourceTrigger=PropertyChanged}"
                                 Foreground="Blue"/>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

<local:TextBoxEx Text="{Binding Title, UpdateSourceTrigger=PropertyChanged, Delay=900}" 
                 Style="{StaticResource TextBoxTitle}" 
                 Foreground="Pink"/>

对Title的绑定优先于绑定到Text的样式并起作用 设置前景色无效,仍为蓝色。 当我在controltemplate样式中使用Foreground="{TemplateBinding Foreground}"时,它可以工作。

我无法理解这种行为,你呢? 在第一种情况下,本地定义是领先的,在第二种情况下,它不是。

2 个答案:

答案 0 :(得分:1)

我不知道这里有什么问题。 TemplatedParent的RelativeSource将在运行时查找原始组件中的Text属性,该属性绑定到Title。它本质上等同于TemplateBinding to Text(但它是slower)。

关于Foreground,它总是蓝色,除非你使用TemplateBinding,在这种情况下它会采用你在TemplatedParent中定义的颜色。

我不明白你的问题。

答案 1 :(得分:0)

在控件模板中,您需要将数据绑定到控件属性,即TextBoxEx,当您使用控件并将其绑定到DataContext时,您将前景设置为蓝色时,通过控件将数据传递给控件模板在控制模板中,您可以制动管道,无论您做什么,控制颜色都将为蓝色 DataContext - &gt;控制 - &gt;控件模板
当您在控制模板中设置蓝色时,您剪切第二个箭头
DataContext - &gt;控制XXXXX ControlTemplate
所以无论你在做什么,蓝色都是蓝色的 有关详细信息,请参阅MSDN ControlTemplate