【问题标题】:Property set in a style cannot be overruled with binding in xaml?样式中设置的属性不能被 xaml 中的绑定否决?
【发布时间】:2014-12-11 14:17:42
【问题描述】:

以下控件定义可以正常工作:

<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}" 时,它可以工作。

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

【问题讨论】:

    标签: wpf xaml properties operator-precedence


    【解决方案1】:

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

    关于前景,它将始终为蓝色,除非您使用 TemplateBinding,在这种情况下,它将采用您在 TemplatedParent 中定义的颜色。

    我不明白你的问题。

    【讨论】:

    • 我的问题是我没有理解 TemplatedParent 和 ControlTemplate 之间的区别。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-23
      • 1970-01-01
      • 2013-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多