【问题标题】:TemplateBinding doesn't bind to effect's property?TemplateBinding 不绑定到效果的属性?
【发布时间】:2010-03-06 12:21:39
【问题描述】:

想象一个名为 Testko 的控件,如下所示:

public class Testko: Control
    {
        public static readonly DependencyProperty TestValueProperty;

        static Testko()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(Testko), new FrameworkPropertyMetadata(typeof(Testko)));
            TestValueProperty = DependencyProperty.Register("TestValue", typeof(double), typeof(Testko), new UIPropertyMetadata((double)1));
        }

        public double TestValue
        {
            get { return (double)GetValue(TestValueProperty); }
            set { SetValue(TestValueProperty, value); }
        }
    }

没什么花哨的,只是一个带有单个 double 属性的空控件,默认值设置为 (double)1。 现在,想象一个像这样的通用样式:

<Style TargetType="{x:Type local:Testko}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:Testko}">
                <Border Background="{TemplateBinding Background}"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}">
                    <StackPanel Orientation="Vertical">
                        <StackPanel.Effect>
                            <BlurEffect Radius="{TemplateBinding TestValue}" />
                        </StackPanel.Effect>
                        <Button Content="{TemplateBinding TestValue}" Margin="4" />
                    </StackPanel>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

现在,问题是 Radius 属性由于某种原因永远不会被绑定。 Wheras Button 的内容已正确绑定到 TestValue 属性。 我确定我遗漏了一些明显的东西。还是不行?

【问题讨论】:

    标签: wpf templates binding effects


    【解决方案1】:

    如果很明显,那对我来说不是 :-)

    我最喜欢的书 (WPF Unleashed) 提到有时 TemplatedBinding 不起作用(但列举的原因与您的情况不符)。

    但是 TemplatedBinding 是一个快捷方式:

    {Binding RelativeSource={RelativeSource TemplatedParent}, Path=TestValue}
    

    我复制了您的案例,即更改 TestValue 仅对按钮有影响。 用这个替换 TemplatedBinding 后,我得到了想要的效果。

    【讨论】:

    • 回答后发现stackoverflow.com/questions/1131222/…,他的回答关于Binding和TemplateBinding的区别很有意思
    • 对我来说似乎是某种错误。感谢您的解决方案:-)
    • 我在“{TemplateBinding DialogHeight}”的 XAML 编辑器中报告了“缺少依赖属性字段”错误,其中 DialogHeight 是属于从“INotifyPropertyChanged”派生的类的属性。显然在运行时也会出现一些绑定错误。按照您的建议更改绑定可以解决我的问题。谢谢。
    猜你喜欢
    • 2010-10-22
    • 1970-01-01
    • 2010-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-18
    • 1970-01-01
    相关资源
    最近更新 更多