依赖属性 - 有 2 个所有者有什么意义?
如果您查看 Selector
和 TabItem
类,它们显然都拥有 IsSelectedProperty
。
static Selector()
{
...
IsSelectedProperty = DependencyProperty.RegisterAttached("IsSelected", typeof(bool), typeof(Selector), ...);
...
}
static TabItem()
{
IsSelectedProperty = Selector.IsSelectedProperty.AddOwner(typeof(TabItem), ...);
...
}
所以我想我的问题是...既然 Tabitem 包含实际的 propertychanged 逻辑,那么 IsSelectedProperty 甚至驻留在 Selector 类中的意义是什么?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在这种特定情况下,
Selector
具有IsSelected
DP,因为有许多从它派生的控件,其项目可以选择(ComboBox
、ListBox
、ListView
、TabControl
、DataGrid
)。它们都需要能够使用IsSelected
标记项目,因此 DP 是在它们的公共基类中声明的。就像蒂姆说的,干。TabItem
将自身添加为所有者的另一个原因是,在Selector
类中,IsSelected
是一个附加属性,因为您几乎可以将任何内容设置为选择器
中的一项。这样,附加属性就非常容易移动。但是,
TabItem
将自身添加为所有者,这样它就不是TabItem
上的附加属性。它还注册了一个在值更改时调用的回调方法,以便在选择或取消选择时可以执行一些操作。是的,在 Intellisense 中输入 并查看
IsSelected
比“但是我到底如何选择一个选项呢?”更容易。并且必须四处寻找并发现您需要使用其他类的附加属性。In this specific case,
Selector
has theIsSelected
DP because there are a number of controls that derive from it whose items can be selected (ComboBox
,ListBox
,ListView
,TabControl
,DataGrid
). They all need an ability to mark an item withIsSelected
, therefore that DP is declared in their common base class. Like Tim said, DRY.Another reason that
TabItem
adds itself as an owner is that in theSelector
class,IsSelected
is an attached property because you can have just about anything as an item in aSelector
. Attached properties are pretty mobile that way.However,
TabItem
adds itself as an owner such that it is not an attached property onTabItem
. It also registers a callback method to be called when the value changes so that it can do a few things when selected or unselected.And yes, it is easier to type
<TabItem
and seeIsSelected
in Intellisense rather than going, "But how the heck do I make one selected?" and have to hunt around and find that you need to use an attached property from some other class.它基本上只是 DRY(不要重复自己)的一个实例。以下是来自 MSDN 论坛的有关该主题的主题:
DependencyProperty.AddOwner - 重点是什么
It's basically just an instance of DRY (Don't Repeat Yourself). Here's a thread from MSDN forums on the topic:
DependencyProperty.AddOwner - What's the Point