【问题标题】:WPF Custom Control TemplateBindingWPF 自定义控件模板绑定
【发布时间】:2010-04-20 17:15:11
【问题描述】:

如何为我的自定义控件定义 TemplateBinding?

【问题讨论】:

    标签: wpf custom-controls


    【解决方案1】:

    有点像这样......(顺便说一句,这个 xaml 是 WPF,而不是 silverlight——这有点不同)

       <style TargetType="{x:Type Button}">
            <Setter Property="Background" Value="Green">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="Button">
                        <Grid Background={TemplateBinding Background}
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </style>
    

    现在,一旦将此样式应用于对象,无论何时设置该对象的背景,模板都会使用 Background 属性(这是按钮控件上的属性),并将默认为您在样式(在本例中为绿色)

    如果您想使用您的样式对象上不存在的属性,您必须派生自己的控件并将该属性添加为DependencyProperty 或使用INotifyPropertyChanged 接口。 Here 给你一个不错的解释。

    【讨论】:

    • 仅此而已吗?如果我想创建自己的,我只需使用具有唯一名称的 setter?
    • 该属性必须作为 DependencyProperty 或 INotifyPropertyChanged 属性存在于对象上。在这种情况下,背景是大多数控件的基本属性。
    【解决方案2】:

    需要更多关于您正在尝试做什么的信息。可以使用以下 XAML 设置 TemplateBinding

    {TemplateBinding YourProperty}

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

    【讨论】:

    • 我在哪里创建这个绑定的来源和默认值?
    猜你喜欢
    • 1970-01-01
    • 2010-12-28
    • 1970-01-01
    • 2015-09-07
    • 2011-07-03
    • 1970-01-01
    • 2015-06-03
    • 2013-03-15
    • 2012-08-18
    相关资源
    最近更新 更多