C# ItemsControl通过TryFindResource获取具有相同键的多个控件时,仅显示一个控件
首先,我的设想。我有一个ViewModel,其公共属性项的类型为C# ItemsControl通过TryFindResource获取具有相同键的多个控件时,仅显示一个控件,c#,wpf,itemscontrol,C#,Wpf,Itemscontrol,首先,我的设想。我有一个ViewModel,其公共属性项的类型为ObservableCollection,其中包含要使用显示的用户控件 我使用Application.Current.TryFindResource(“ControlKey”)作为UserControl获取UserControls。 当每个资源都有不同的x:Key时,一切正常。但是,当我向具有相同x:Key的项添加更多UserControls时,ItemsControl仅显示具有相同x:Key的UserControls中的一个,即使
ObservableCollection
,其中包含要使用
显示的用户控件
我使用Application.Current.TryFindResource(“ControlKey”)作为UserControl
获取UserControls。
当每个资源都有不同的x:Key
时,一切正常。但是,当我向具有相同x:Key
的项添加更多UserControls时,ItemsControl仅显示具有相同x:Key
的UserControls中的一个,即使所有UserControls都存在于项中
在示例中,我将项目添加到集合中,如下所示:
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
我错过了什么?非常感谢。逻辑树中的每个元素只能使用一次。您尝试使用同一元素两次。请查看以下示例:
<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>
只要做:
Items.Add( new Filter1() );
Items.Add( new Filter1() );
如果将字符串“Filter1”作为变量-实现实用程序方法“实例化”-在该函数中,可以使用switch语句,也可以使用反射:
Items.Add( instantiate( key ) );
private UserControl instantiate( string key ) {
...
}
太棒了,谢谢。当我从ResourceDictionary检索同一资源时,您知道如何获取同一资源的多个实例吗?
Items.Add( instantiate( key ) );
private UserControl instantiate( string key ) {
...
}