如何从 custom-panel 到达我的 parent-property

How do I reach my parent-property from custom-panel

我使用本文中的自定义面板: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>

我正在修改 custom-panel,需要从名称为 'LoopListControl' 的 parent-usercontrol 中获取名称为 'SelectedIndex' 的 dependency-property

这是 Live-Visual-Tree-Structure:

到目前为止我为获得 SelectedIndex 所做的尝试是这样的(在 custom-panel 内)但是 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

并收到错误:"Object reference not set to an instance of an object."

你知道如何获取这个值吗?

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

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

我不保证你不会得到相同的异常,但至少,如果此方法不 return 预期的结果或方法 return null,它将是一个好的开始看看出了什么问题。