【问题标题】:ItemsControl displaying only one control when getting more controls with same key via TryFindResource通过 TryFindResource 获取具有相同键的多个控件时,ItemsControl 仅显示一个控件
【发布时间】:2012-02-23 09:47:47
【问题描述】:

首先,我的场景。我有一个带有 ObservableCollection<UserControl> 类型的公共属性 Items 的 ViewModel,其中包含我想使用 <ItemsControl ItemsSource="{Binding Items}" /> 显示的用户控件。

我使用Application.Current.TryFindResource("ControlKey") as UserControl 获取用户控件。 当每个资源都有不同的x:Key 时,一切正常。但是,当我向 Items 添加更多具有相同 x:Key 的 UserControls 时,即使所有 UserControls 都存在于 Items。

例如,我将项目添加到集合中,如下所示:

Items.Add(Application.Current.TryFindResource("Filter1") as UserControl);
Items.Add(Application.Current.TryFindResource("Filter1") as UserControl);
Items.Add(Application.Current.TryFindResource("Filter2") as UserControl);

ItemsControl 中仅显示两个控件,一个带有 x:Key“Filter1”,一个带有“Filter2”。 x:Key“Filter1”的第二个 UserControl 未显示。

我错过了什么?非常感谢。

【问题讨论】:

    标签: c# wpf itemscontrol


    【解决方案1】:

    逻辑树中的每个元素只能使用一次。您尝试使用相同的元素两次。查看以下示例:

    <Window x:Class="SO.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="MainWindow" Height="350" Width="525">
        <Window.Resources>
            <Button x:Key="btn">Hello</Button>
        </Window.Resources>
        <StackPanel>
            <ContentControl Content="{StaticResource btn}" />
            <ContentControl Content="{StaticResource btn}" />
        </StackPanel>
    </Window>
    

    如果您尝试运行此代码,则会在分配 Content 属性期间遇到异常。内部异常会告诉您该元素已放置在树中的其他位置。

    您应该为集合中的每个项目创建一个新的 UserControl 实例(提示:必须在某处使用关键字“new”)。

    编辑(回复@Jan 评论):@Jan,在使用反射时,您可以创建给定类型的对象的新实例——这不是首选设计。忘记将用户控件的实例放在应用程序字典中。只需定义类。然后代替:

    Items.Add(Application.Current.TryFindResource("Filter1") as UserControl);
    Items.Add(Application.Current.TryFindResource("Filter1") as UserControl);
    

    只是做:

    Items.Add( new Filter1() );
    Items.Add( new Filter1() );
    

    如果您将字符串 'Filter1' 作为变量 - 实现实用方法 'instantiate' - 在该函数中要么使用 switch 语句,要么使用反射:

    Items.Add( instantiate( key ) );
    
    private UserControl instantiate( string key ) {
        ...
    }
    

    【讨论】:

    • 太棒了,谢谢。当我从 ResourceDictionary 检索同一资源时,您知道如何获取同一资源的多个实例吗?
    猜你喜欢
    • 1970-01-01
    • 2013-12-24
    • 2014-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-17
    相关资源
    最近更新 更多