如何从自定义面板访问我的父属性

时间:2016-03-15 09:08:12

标签: c# xaml win-universal-app parent

我使用了本文中的自定义面板:Custom Itemspanel

ItemsPanel嵌入在这样的用户控件中:

<UserControl
    x:Class="CustomControls.LoopList"
    x:Name="LoopListControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:CustomControls"
    xmlns:ctrl="using:CustomControls.Controls"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:vm="using:CustomControls.ViewModel"
    mc:Ignorable="d"
    d:DesignHeight="300"
    d:DesignWidth="200">
    <ItemsControl ItemsSource="{Binding LoopListSource, ElementName=LoopListControl}" 
                    HorizontalAlignment="Center" VerticalAlignment="Stretch" Height="Auto" Width="{Binding ItemWidth, ElementName=LoopListControl}">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <ctrl:LoopItemsPanel x:Name="LoopControl" Loaded="LoopControl_Loaded"/>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
    </ItemsControl>
</UserControl>

我正在修改自定义面板,需要从parent-usercontrol获取名为'SelectedIndex'的依赖项属性,名称为'LoopListControl'

这是Live-Visual-Tree-Structure: Live-Visual-Tree-Structure:

到目前为止,我尝试获取SelectedIndex的是(在自定义面板中)但是Parent总是'null':

public void SetToIndex()
{
    if (this.Children == null || this.Children.Count == 0)
        return;

    var rect = this.Children[0].TransformToVisual(this).TransformBounds(new Rect(0, 0, this.Children[0].DesiredSize.Width, this.Children[0].DesiredSize.Height));
    var selectedChild = this.Children[(Parent as LoopList).SelectedIndex];

    ScrollToSelectedIndex(selectedChild, rect);
}

基于Live-Visual-Tree-Structure我也尝试了这个:

(((this.Parent as ContentControl).Parent as ItemsPresenter).Parent as ItemsControl).Parent as LoopList

并收到错误:“对象引用未设置为对象的实例。”

你知道如何获得价值吗?

1 个答案:

答案 0 :(得分:1)

有一种方法可以让您找到控件的给定类型的第一个父级。

public static T FindParent<T>(DependencyObject child) where T : DependencyObject
{
    //get parent item
    DependencyObject parentObject = VisualTreeHelper.GetParent(child);

    //we've reached the end of the tree
    if (parentObject == null) return null;

    //check if the parent matches the type we're looking for
    T parent = parentObject as T;
    if (parent != null)
        return parent;
    else
        return FindParent<T>(parentObject);
}

然后你只需要这样调用这个方法:

LoopList parentLoopList = FindParent<LoopList>(theControlInWhichYouWantToFindTheParent);
if (parentLoopList!= null)
   //Do your job

我不保证你不会得到相同的异常,但至少,如果这个方法没有返回预期的或者方法返回null,那么看看出了什么问题将是一个好的开始。