【问题标题】:Problems rendering a WPF custom control within a Canvas via an ItemsControl通过 ItemsControl 在 Canvas 中呈现 WPF 自定义控件时出现问题
【发布时间】:2014-12-24 08:13:26
【问题描述】:

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

自定义内容控件称为 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 并直接将用户控件添加到画布,但我不知道为什么。

有什么建议吗?

【问题讨论】:

    标签: c# wpf canvas itemscontrol


    【解决方案1】:

    更新

    在另一个 Stack 线程 Using binding to a List &lt;UserControl&gt; how can I do for not showing the controls 上找到了解决方案

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

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

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

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

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

    现在我可以将我的列表绑定到&lt;ItemsControl&gt;,而不会忽略我的&lt;DataTemplate&gt;。我使用包装器的 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>
    

    【讨论】:

    • 感谢 Jynx!我试试看。
    猜你喜欢
    • 2011-01-17
    • 1970-01-01
    • 2012-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-24
    • 1970-01-01
    相关资源
    最近更新 更多