Public vs Private AttachedProperties
Where does it make sense to have AttachedProperties
as private
vs public
?
Usually it is define as (example):
public static readonly DependencyProperty Co开发者_运维问答mmandProperty =
DependencyProperty.RegisterAttached(
"Command",
typeof(ICommand),
typeof(Click),
new PropertyMetadata(OnSetCommandCallback));
But I have also seen examples where some properties are private static readonly...
What are the consequences if I change the above CommandProperty
to private
now? It seems to be still available in my XAML intellisense if I do that. What am I missing here?
The difference is that you won't be able to access the DependencyProperty
from outside of the class. This can make sense if the static Get and Set methods are private as well, (in an attached behavior where you need to store some behavior local data for example) but not otherwise (and I don't think I've ever seen this with public Get and Set).
An example of when you want to use the DependencyProperty
is DependencyPropertyDescriptor
. With a public DependencyProperty
you can do the following
DependencyPropertyDescriptor de =
DependencyPropertyDescriptor.FromProperty(Click.CommandProperty, typeof(Button));
de.AddValueChanged(button1, delegate(object sender, EventArgs e)
{
// Some logic..
});
But if the DependencyProperty
is private, the above code won't work.
However, the following will work fine for both a public and private DependencyProperty
(if the static Get and Set methods are public) since the owner class can access the private DependencyProperty
. This also goes for Bindings and values set through Xaml where GetValue
and SetValue
are called directly.
Click.SetCommand(button, ApplicationCommands.Close);
ICommand command = Click.GetCommand(button);
If you look through the framework you will notice that all of the public attached properties have a public DependencyProperty
, for example Grid.RowProperty
and Storyboard.TargetNameProperty
. So if the attached property is public, use a public DependencyProperty
精彩评论