通过ItemsControl在画布中呈现WPF自定义控件时出现问题

本文关键字:自定义控件 问题 WPF 通过 布中呈 ItemsControl | 更新日期: 2023-09-27 18:22:17

我想在画布上呈现一堆用户控件,但每个用户控件都应该呈现为自定义内容控件的内容。

自定义内容控件被称为Window,它提供了一个边框、一些按钮等,并允许用户在画布上拖动窗口。我对画布及其子对象的定义如下:

<ItemsControl Grid.Column="2" Grid.Row="1" ItemsSource="{Binding Views}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <Canvas />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <controls:Window Title="Test" Width="300" Height="300" Content="{Binding}" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
    <ItemsControl.ItemContainerStyle>
        <Style>
            <Setter Property="Canvas.Top" Value="50"/>
            <Setter Property="Canvas.Left" Value="50"/>
        </Style>
    </ItemsControl.ItemContainerStyle>
</ItemsControl>

但是,当渲染每个项目时,它显示时没有周围的Window内容控件。事实上,它甚至没有击中Window构造函数。这告诉我,它忽略了DataTemplate,只是直接将用户控件添加到画布中,但我不确定为什么。

有什么建议吗?

通过ItemsControl在画布中呈现WPF自定义控件时出现问题

更新

在另一个堆栈线程上找到了解决方案使用绑定到列表<UserControl>我该如何处理不显示控件

基本上,正如您已经发现的那样,当您绑定到<UserControl>的列表时,您会得到错误26,并且<DataTemplate>被忽略。简单的解决方法是将<UserControl>封装在另一个类中,这样它就不会被检测为控件。然后,您可以使用包装器上的属性将<UserControl>绑定到<DataTemplate>中。

因此,为了详细说明,我创建了一个包装器类,如下所示:

public class ViewWrapper
{
    public UserControl View { get; set; }
}

然后,我将控件上的列表更改为使用ViewWrapper:

public ObservableCollection<ViewWrapper> ViewWrappers { get; set; } 

现在我可以将我的列表绑定到<ItemsControl>,而不会忽略我的<DataTemplate>。我使用包装的View属性来访问View。

        <ItemsControl ItemsSource="{Binding ViewWrappers}">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Grid>
                        <ContentControl Content="{Binding View}"/>
                        <Label Content="End of this item." />
                    </Grid>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>