我不想使用容器使我的项目可见,我只想获取 Children 控件并将其放入 List 或 Collection
如果它们不是视觉元素,您可以在用户控件上创建列表
示例:(仅使用FrameworkElement
列表)
用户控制:
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
public ObservableCollection<FrameworkElement> FirstCollection
{
get { return (ObservableCollection<FrameworkElement>)GetValue(FirstCollectionProperty); }
set { SetValue(FirstCollectionProperty, value); }
}
// Using a DependencyProperty as the backing store for FirstCollection. This enables animation, styling, binding, etc...
public static readonly DependencyProperty FirstCollectionProperty =
DependencyProperty.Register("FirstCollection", typeof(ObservableCollection<FrameworkElement>), typeof(UserControl1), new PropertyMetadata(new ObservableCollection<FrameworkElement>()));
public ObservableCollection<FrameworkElement> SecondCollection
{
get { return (ObservableCollection<FrameworkElement>)GetValue(SecondCollectionProperty); }
set { SetValue(SecondCollectionProperty, value); }
}
// Using a DependencyProperty as the backing store for SecondCollection. This enables animation, styling, binding, etc...
public static readonly DependencyProperty SecondCollectionProperty =
DependencyProperty.Register("SecondCollection", typeof(ObservableCollection<FrameworkElement>), typeof(UserControl1), new PropertyMetadata(new ObservableCollection<FrameworkElement>()));
public ObservableCollection<FrameworkElement> LastCollection
{
get { return (ObservableCollection<FrameworkElement>)GetValue(LastCollectionProperty); }
set { SetValue(LastCollectionProperty, value); }
}
// Using a DependencyProperty as the backing store for LastCollection. This enables animation, styling, binding, etc...
public static readonly DependencyProperty LastCollectionProperty =
DependencyProperty.Register("LastCollection", typeof(ObservableCollection<FrameworkElement>), typeof(UserControl1), new PropertyMetadata(new ObservableCollection<FrameworkElement>()));
}
用法:
<Window x:Class="WpfApplication8.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication8"
Title="MainWindow" Height="350" Width="525" Name="UI">
<Grid>
<local:UserControl1 >
<local:UserControl1.FirstCollection>
<Label />
</local:UserControl1.FirstCollection>
<local:UserControl1.SecondCollection>
<Label />
</local:UserControl1.SecondCollection>
<local:UserControl1.LastCollection>
<Label />
</local:UserControl1.LastCollection>
</local:UserControl1>
</Grid>
</Window>