wpf - 公共(public)与私有(private)附加属性

标签 wpf silverlight silverlight-4.0 attached-properties attachedbehaviors

AttachedProperties 设置为 privatepublic 有何意义? 通常它定义为(示例):

public static readonly DependencyProperty CommandProperty = 
DependencyProperty.RegisterAttached(
            "Command",
            typeof(ICommand),
            typeof(Click),
            new PropertyMetadata(OnSetCommandCallback));

但我也看到过一些例子,其中一些属性是private static readonly...

如果我现在将上述 CommandProperty 更改为 private 会有什么后果?如果我这样做,它似乎仍然可以在我的 XAML 智能感知中使用。我在这里缺少什么?

最佳答案

区别在于您无法从类外部访问DependencyProperty。如果静态 Get 和 Set 方法也是私有(private)的,那么这是有意义的,(例如,在附加行为中,您需要存储一些行为本地数据),但否则就没有意义(我不认为我曾经在公共(public) Get 和 Set 中见过这种情况。

您想要使用DependencyProperty的一个示例是DependencyPropertyDescriptor。使用公共(public)DependencyProperty,您可以执行以下操作

DependencyPropertyDescriptor de =
    DependencyPropertyDescriptor.FromProperty(Click.CommandProperty, typeof(Button));

de.AddValueChanged(button1, delegate(object sender, EventArgs e)
{
    // Some logic..
});

但是如果DependencyProperty是私有(private)的,上面的代码将不起作用。

但是,以下内容对于公共(public)和私有(private) DependencyProperty 都可以正常工作(如果静态 Get 和 Set 方法是公共(public)的),因为所有者类可以访问私有(private)依赖属性。这也适用于通过 Xaml 设置的绑定(bind)和值,其中直接调用 GetValueSetValue

Click.SetCommand(button, ApplicationCommands.Close);
ICommand command = Click.GetCommand(button);

如果您仔细查看框架,您会发现所有公共(public)附加属性都有一个公共(public) DependencyProperty,例如 Grid.RowPropertyStoryboard.TargetNameProperty 。因此,如果附加属性是公共(public)的,请使用公共(public)DependencyProperty

关于wpf - 公共(public)与私有(private)附加属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7480700/

相关文章:

c# - 如何在 Canvas 上旋转动态创建的 ListBoxItem?

c# - 如何获取 ComboBox 的值而不是文本

wpf - DataTemplate.DataType = 集合<实体>?

silverlight - 如何强制Silverlight容器扩展/收缩到其子控件的大小?

c# - "The type or namespace name ' 引用System.Xml.dll时XmlSerializer ' could not be found"错误

wpf - INotifyPropertyChanged 不会导致此代码中的屏幕更新

Silverlight 数据访问

silverlight - 如果我在 setter 中更改具有不同值的绑定(bind)数据,如何刷新绑定(bind)数据

audio - Silverlight Speex 播放速度很快

silverlight-4.0 - 由 ViewModel 中的事件触发的 View 中的 ControlStoryboardAction