用户控件的子抚养对象绑定不工作 [英] Bindings on child dependency object of usercontrol not working
问题描述
我想获得一个绑定的用户控件的子对象上工作。 XAML中看起来是这样的:
I'm trying to get a binding to work on a child object of a user control. The Xaml looks like this:
<MyGrid>
<MyColumn ExtendedColumnData="{Binding ColumnToolTipDescriptions}"/>
</MyGrid>
下面是这些类是如何定义的:
Here is how the classes are defined:
[ContentProperty("Columns")]
public class MyGrid : UserControl
{
private MyColumnCollection _columns;
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content), Category("Data")]
public MyColumnCollection Columns
{
get
{
if (_columns == null)
_columns = new MyColumnCollection();
return _columns;
}
}
}
public class MyColumnCollection : ObservableCollection<MyGridColumn>
{
}
public class MyGridColumn : DependencyObject
{
public object ExtendedColumnData
{
get { return (object)GetValue(ExtendedColumnDataProperty); }
set { SetValue(ExtendedColumnDataProperty, value); }
}
public static readonly DependencyProperty ExtendedColumnDataProperty =
DependencyProperty.Register("ExtendedColumnData", typeof(object), typeof(MyGridColumn), new UIPropertyMetadata(null));
}
从我所知道的,结合甚至没有试图获取的数据,因为我已经试图把一个转换器对绑定,并在转换方法断点从来没有被击中。
From what I can tell, the binding is not even attempting to get the data as I've tried putting a converter against the binding, and the breakpoint on the Convert method never gets hit.
我使用的MVVM模式,使窗口的的DataContext
属性设置为视图模型。
I'm using the MVVM pattern so the window's DataContext
property is set to a view model.
我读过关于这里的一些其他问题,并尝试了各种排列的结合,例如:
I've read some other questions on here and tried various permutations of the binding such as:
<MyColumn ExtendedColumnData="{Binding DataContext.ColumnToolTipDescriptions, ElementName=MyViewName}" />
<MyColumn ExtendedColumnData="{Binding DataContext.ColumnToolTipDescriptions, RelativeSource={RelativeSource AncestorType={x:Type local:MyView}}" />
但仍然没有运气,结合不火!恼人的是,这似乎工作正常(如果我的属性添加到网格):
But still no luck, the binding doesn't fire! The annoying thing is, this seems to work fine (if I add the property to the grid):
<MyGrid ExtendedColumnData="{Binding ColumnToolTipDescriptions}">
<MyColumn />
</MyGrid>
我不与WPF经历,所以我敢肯定,我失去了一些东西?
I'm not that experienced with WPF so I'm sure I'm missing something?
推荐答案
的问题是, MyColumnCollection
不继承数据上下文(控制的常用属性都没有的一部分继承上下文)。如果你没有一个数据上下文绑定将无法工作。
The problem is that MyColumnCollection
is not inheriting data context (usual properties of a control are not part of inheritance context). If you don't have a data context bindings will not work.
要解决这个问题,尝试继承 MyColumnCollection
从的ObservableCollection
,而是来自的FreezableCollection
(可冻结属性继承上下文的一部分)。
To fix that, try inheriting MyColumnCollection
not from ObservableCollection
, but from FreezableCollection
(freezable properties are part of inheritance context).
这篇关于用户控件的子抚养对象绑定不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!