簡體   English   中英

從項目模板WPF中獲取列表項目控件

[英]Get Back List Item Control From Item Template WPF

我將列表視圖與用戶控件綁定如下,

<ListView Grid.Row="2" Name="lvItems">
       <ListView.ItemTemplate>
                <DataTemplate>
                    <my1:ucItem Name="li"/>
                </DataTemplate>
            </ListView.ItemTemplate>
</ListView>

該用戶控件具有用戶將在運行時輸入的本地存儲值。 我不想雙向綁定,因為在運行時,該用戶控件會添加除用戶控件之外的其他值。 我設置了一些get方法來獲取存儲在用戶控件中的值。 我如何找回該用戶控件lvItems.Items只是返回綁定到它的對象列表,而不是我的用戶控件。 有沒有辦法找回生成的用戶控制列表。

例如,我想像這樣讀回ListView項目,

foreach(UserControl uc in lvItems.Items){//Do Something}

@Amit在注釋中正確,您應該真正使用MVVM和數據綁定方法。 就是說,如果您確定要采用其他方式,則此擴展方法應該會有所幫助:

public static class ItemsControlExtensions
{
    public static IEnumerable<TElement> GetElementsOfType<TElement>(
        this ItemsControl itemsControl, string named)
        where TElement : FrameworkElement
    {
        ItemContainerGenerator generator = itemsControl.ItemContainerGenerator;

        return
            from object item in itemsControl.Items
            let container = generator.ContainerFromItem(item)
            let element = GetDescendantByName(container as FrameworkElement, named)
            where element != null
            select (TElement) element;
    }

    static FrameworkElement GetDescendantByName(FrameworkElement element,
        string elementName)
    {
        if (element == null)
        {
            return null;
        }

        if (element.Name == elementName)
        {
            return element;
        }

        element.ApplyTemplate();

        FrameworkElement match = null;
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(element); i++)
        {
            var child = VisualTreeHelper.GetChild(element, i) as FrameworkElement;
            match = GetDescendantByName(child, elementName);

            if (match != null)
            {
                break;
            }
        }

        return match;
    }
}

用法如下:

foreach (UserControl uc in lvItems.GetElementsOfType<UserControl>(named: "li"))
{
    // do something with 'uc'
}

GetDescendantByName方法基於WPF博士從此博客文章中獲得的方法: ItemsControl:'G'用於Generator 實際上,關於ItemsControl如何工作的整個博客文章系列非常值得一讀: WPF博士:ItemsControl:從A到Z。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM