【问题标题】:How to add a DependencyProperty to a Button?如何将 DependencyProperty 添加到按钮?
【发布时间】:2011-01-15 20:55:36
【问题描述】:

我基本上只是想向按钮添加几个属性来存储一些额外的信息以供以后使用。我选择这样做而不是基于按钮创建 UserControl 仅仅是因为它看起来像更少的代码。

我按照我在 Microsoft 网站上看到的示例进行操作,但收到错误消息“无法在 'Button' 类型的 'SetSortIndicatorVisibility' 属性上设置 'Binding'。'Binding' 只能是在 DependencyObject 的 DependencyProperty 上设置。”这没有任何意义,因为 Button 是一个 DependencyObject,而我正在添加一个 DependencyProperty。我最初是从一个 AttachedProperty 开始的,但后来我已经解决了这个问题。我什至已经将与此相关的所有代码放入测试项目中,但我仍然收到此错误。所有这些测试代码如下:

DependencyProperty 定义:

public static readonly DependencyProperty SortIndicatorVisibilityProperty = DependencyProperty.Register( "SortIndicatorVisibility", typeof( Visibility ), typeof( Button ), new FrameworkPropertyMetadata( Visibility.Visible, FrameworkPropertyMetadataOptions.AffectsRender ) );

    public static void SetSortIndicatorVisibility( Button button, Visibility value )
    {
        button.SetValue( SortIndicatorVisibilityProperty, value );
    }
    public static Visibility GetSortIndicatorVisibility( Button button )
    {
        return ( Visibility ) button.GetValue( SortIndicatorVisibilityProperty );
    }

包含具有新属性和绑定的按钮的窗口 XAML:

<Window x:Class="Testing.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:ext="clr-namespace:Testing"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <Button Content="Test"
            Command="{Binding TestCommand}"
            ext:Class1.SortIndicatorVisibility="{Binding SortIndicatorVisibilitySiteName}" />
</Grid>

最后,DependencyProperty 绑定的属性:

public Visibility SortIndicatorVisibilitySiteName
    {
        get
        {
            return Visibility.Visible;
        }
    }

【问题讨论】:

    标签: wpf binding dependency-properties


    【解决方案1】:

    您不能将“普通”依赖属性添加到任意类,它必须是附加属性。另外,所有者类型不应该是Button,应该是声明属性的类

    【讨论】:

    • 出于某种原因,我假设声明这些 DependencyProperties 与扩展相同。为了让它工作,我所要做的就是让 Class1 从 Button 继承并将父类型从 typeof( Button ) 更改为 typeof( Class1) 并且它起作用了!感谢您为我指明正确的方向。
    【解决方案2】:

    我认为您第一次尝试使用 attached Dependency property 是正确的,因为您的 getter 和 setter 现在不一致。

    您的属性实际上注册为依赖属性,而不是 attached 依赖属性(使用“RegisterAttached”而不是“Register”)。

    【讨论】:

    • 根据这个 Microsoft 自定义依赖属性页面 - msdn.microsoft.com/en-us/library/ms753358.aspx (对不起,不知道使这个可链接的代码),它说为了使自定义属性可绑定,它必须是依赖属性而不是附加属性,这就是我进行更改的原因。
    • “而不是附加属性”?你在哪里看到的?如您所见,我的回答是正确的,正如 Thomas Levesque 的回答......
    猜你喜欢
    • 1970-01-01
    • 2014-05-13
    • 2018-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多