我有类似的问题。最后我把它从代码隐藏中分类出来。有些事情是XAML不擅长的。
我需要将我的DataTemplate的根UserControl的Top属性绑定到包含它的ContentPresenter的Canvas.Top附加属性。在我的情况下,ContentPresenter由正在将DataTemplate应用于基础数据对象集合的ItemsControl生成。 ContentPresenter的Content属性指向底层数据对象,而不是我需要引用的Visual对象。虽然这不是你所面对的问题,但我认为它的关键是相同的 - 试图找到对ContentPresenter的Visual内容的引用。
在最内层的UserControl后面的代码中,我通过覆盖EndInit方法来连接绑定。我只是打算在一种情况下使用该控件,所以这对我来说是可以接受的,但是代码可以在适用于您的情况的其他地方移动。
/// <summary>
/// Indicates that the initialization process for the element is complete
/// </summary>
public override void EndInit()
{
this.BindToParentContentPresenter();
base.EndInit();
}
/// <summary>
/// Binds the Canvas.Top attached property of the content presenter to the top property of this object
/// </summary>
private void BindToParentContentPresenter()
{
ContentPresenter cp = this.VisualParent as ContentPresenter;
if (cp != null)
{
Binding b = new Binding();
b.Source = this;
b.Path = new PropertyPath(TopProperty);
cp.SetBinding(SelectableUniformCanvas.TopProperty, b);
}
}
你不应该那样做...... –