将 AttachedProperties
设置为 private
与 public
有何意义?
通常它定义为(示例):
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)和值,其中直接调用 GetValue
和 SetValue
。
Click.SetCommand(button, ApplicationCommands.Close);
ICommand command = Click.GetCommand(button);
如果您仔细查看框架,您会发现所有公共(public)附加属性都有一个公共(public) DependencyProperty
,例如 Grid.RowProperty
和 Storyboard.TargetNameProperty
。因此,如果附加属性是公共(public)的,请使用公共(public)DependencyProperty
关于wpf - 公共(public)与私有(private)附加属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7480700/