【发布时间】:2018-05-08 08:08:21
【问题描述】:
我想通过收集DependencyObjects 的集合类型附加属性来扩展FrameworkElement 类的Button 类元素。
困难在于集合项的绑定不起作用:没有显示调试或运行时错误,但从未调用绑定的源。
我注意到集合类型附加属性不是从类DependencyObject 继承的。
我猜DataContext 属性将被任何子DependencyObject 对象继承(只要父对象也是DependencyObject 对象)。由于集合类型附加属性不继承自DependencyObject,因此不会发生DataContext 属性继承。
- 我想知道为什么
DependencyObject的实例可以继承DataContext属性,因为DataContext是FrameworkElement中定义的属性?DependencyObject如何管理DataContext查找? - 为什么用
ElementName=PageName指定绑定源不能正常工作(例如{Binding MyProperty="{Binding DataContext.PropertySource1, ElementName=PageName})?如果DependencyObject也负责ElementName查找,它是如何做到的? - 是否有继承
DependencyObject的 UWP 集合? (在 WPF 中有FreezableCollection<T>类,但我在 UWP 环境中找不到挂件。)
下面的 XAML 标记显示了一个示例扩展,其中 Binding 不起作用。
<Button Name="Button">
<ext:MyExtension.MyCollection>
<ext:MyDependencyObject MyProperty="{Binding PropertySource1}"/>
<ext:MyDependencyObject MyProperty="{Binding PropertySource1}"/>
</ext:MyExtension.MyCollection>
</Button>
如果我对非集合类型的附加属性进行以下扩展,则可以正确解析绑定。
<Button Name="Button">
<ext:MyExtension.MyProperty>
<ext:MyDependencyObject MyProperty="{Binding PropertySource1}"/>
</ext:MyExtension.MyProperty>
</Button>
下面的代码显示了一个示例集合类型的附加属性实现。考虑附加属性类还包含一个非集合类型附加属性的定义(它可以与绑定一起正常工作)。
public class MyDependencyObject: DependencyObject
{
public object MyProperty
{
get { return (object)GetValue(MyPropertyProperty ); }
set { SetValue(MyPropertyProperty , value); }
}
public static readonly DependencyProperty MyPropertyProperty =
DependencyProperty.Register("MyProperty", typeof(object), typeof(MyProperty), null);
}
public class MyPropertyCollection : ObservableCollection<MyDependencyObject> { }
public static class MyExtension
{
// Collection-type AttachedProperty with DependencyObject items
public static MyPropertyCollection GetMyPropertyCollection(DependencyObject obj)
{
MyPropertyCollection collection = (MyPropertyCollection )obj.GetValue(MyCollectionProperty );
if (collection == null)
{
collection = new MyPropertyCollection();
collection.CollectionChanged +=
(sender, e) =>
{
//intiailization of elements possible
};
obj.SetValue(MappingsProperty, collection);
}
return collection;
}
public static void SetMyPropertyCollection(DependencyObject obj, MyPropertyCollection value)
{
obj.SetValue(MyCollectionProperty , value);
}
public static readonly DependencyProperty MyCollectionProperty =
DependencyProperty.RegisterAttached("MyCollection", typeof(MyPropertyCollection), typeof(MyExtension), null);
// DependencyObject-type AttachedProperty
public static MyProperty GetMapping(DependencyObject obj)
{
return (MyProperty )obj.GetValue(MyPropertyProperty );
}
public static void SetMapping(DependencyObject obj, MyProperty value)
{
obj.SetValue(MyPropertyProperty , value);
}
public static readonly DependencyProperty MyPropertyProperty =
DependencyProperty.RegisterAttached("MyProperty", typeof(MyDependencyObject), typeof(MyExtension), null);
}
【问题讨论】:
标签: c# binding uwp dependency-properties attached-properties