2

AttachedPropertiesprivate vs public哪里有意义? 通常它定义为(例如):Public vs Private AttachedProperties

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

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

什么后果,如果我现在改变上述CommandPropertyprivate?如果我这样做,似乎仍然可以在我的XAML intellisense中使用。我在这里错过了什么?

回答

4

区别在于您将无法从课外访问DependencyProperty。如果静态的Get和Set方法是私有的,这也是有意义的,(在你需要存储一些行为本地数据的附加行为中)但是不是(否则我不认为我见过这与公共获取和设置)。

当您想要使用DependencyProperty的示例是DependencyPropertyDescriptor。与公共DependencyProperty你可以做以下

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

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

但如果DependencyProperty是私有的,上面的代码将无法正常工作。

但是,下面的工作罚款既是公共和私人DependencyProperty(如果静态get和set方法是公开的)因为主人类可以访问私有DependencyProperty。这也适用于通过Xaml设置的Bindings和值,其中GetValueSetValue被直接调用。

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

如果你看看通过框架你会发现,所有的公共附加属性有一个公共DependencyProperty,例如Grid.RowPropertyStoryboard.TargetNameProperty。因此,如果附属财产是公开的,请使用公开的DependencyProperty

+0

如果附加行为是xaml中的数据绑定,并且被定义为私有? xaml是否会调用静态的Get和Set方法? – VoodooChild

+0

通过Binding或Xaml设置的值将直接调用'GetValue'和'SetValue',这样它们对于私有'DependencyProperty'仍然可以正常工作。公共的getter和setter仍然需要能够找到它 –

相关问题