在WPF中创建任意位置控件的集合

本文关键字:控件 集合 位置 任意 WPF 创建 | 更新日期: 2023-09-27 18:22:33

我有一个简单的BorderGrid,它们位于WPF中的Canvas容器中。控件的位置在运行时会发生变化,因此它会驻留在画布中。

控件的XAML如下所示:

<Border Name="PopupArea"
        Width="130"
        Height="150"
        BorderBrush="Black"
        BorderThickness="2"
        CornerRadius="5">
    <Border.Background>
        <SolidColorBrush Opacity="0.5" Color="Black" />
    </Border.Background>
    <Grid>
        <StackPanel>
            <Border HorizontalAlignment="Center">
                <Border.Effect>
                    <DropShadowEffect />
                </Border.Effect>
                <TextBlock FontWeight="Bold" Style="{StaticResource SmallWhiteFont}">HELLO WORLD</TextBlock>
            </Border>
        </StackPanel>
    </Grid>
</Border>

然而,我现在需要能够创建上面控件的Collection,我在运行时根据需要在代码中创建并销毁它。

我的问题是:

A。编写XAML以通过代码创建上述控件的多个实例的最佳方法是什么?我只是在资源中声明一个ContentControl吗?

B。假设我是正确的,并且需要一个资源模板。如何实际使用它在代码中创建控件的多个实例?

在WPF中创建任意位置控件的集合

在XAML中,我将使用ItemTemplate。然后,我会将ItemsSource绑定到我的视图模型上的某个可观察集合。

下面是一个来自MSDN的示例:

<ListBox Width="400" Margin="10"
         ItemsSource="{Binding Source={StaticResource myTodoList}}">
   <ListBox.ItemTemplate>
     <DataTemplate>
       <StackPanel>
         <TextBlock Text="{Binding Path=TaskName}" />
         <TextBlock Text="{Binding Path=Description}"/>
         <TextBlock Text="{Binding Path=Priority}"/>
       </StackPanel>
     </DataTemplate>
   </ListBox.ItemTemplate>
 </ListBox>

注:

更常见的做法是在resources部分定义DataTemplate,使其成为可重用对象。

<ListBox Width="400" Margin="10"
         ItemsSource="{Binding Source={StaticResource myTodoList}}"
         ItemTemplate="{StaticResource myTaskTemplate}"/>