C# 通过ItemsControl在画布中呈现WPF自定义控件时出现问题
我想在画布上呈现一组usercontrols,但是每个usercontrol都应该呈现为自定义内容控件的内容 自定义内容控件称为窗口,提供边框、一些按钮等,允许用户在画布上拖动窗口。我对画布及其子对象的定义如下:C# 通过ItemsControl在画布中呈现WPF自定义控件时出现问题,c#,wpf,canvas,itemscontrol,C#,Wpf,Canvas,Itemscontrol,我想在画布上呈现一组usercontrols,但是每个usercontrol都应该呈现为自定义内容控件的内容 自定义内容控件称为窗口,提供边框、一些按钮等,允许用户在画布上拖动窗口。我对画布及其子对象的定义如下: <ItemsControl Grid.Column="2" Grid.Row="1" ItemsSource="{Binding Views}"> <ItemsControl.ItemsPanel> <ItemsPanelTempl
<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>
但是,当渲染每个项目时,它将在没有周围窗口内容控件的情况下显示。事实上,它甚至没有击中窗口构造函数。这告诉我它忽略了DataTemplate,只是直接将usercontrol添加到画布中,但我不知道为什么
有什么建议吗?更新
在另一个堆栈线程上找到了此问题的解决方案
基本上,正如您已经发现的,当您绑定到
列表时,会出现错误26,
被忽略。简单的解决方法是将
包装到另一个类中,这样它就不会被检测为控件。然后可以使用包装器上的属性在
中绑定
为此,我创建了一个包装器类,如下所示:
public class ViewWrapper
{
public UserControl View { get; set; }
}
然后,我将控件上的列表更改为使用ViewWrapper:
public ObservableCollection<ViewWrapper> ViewWrappers { get; set; }
public observeCollection ViewWrappers{get;set;}
现在,我可以将列表绑定到
,而不必忽略我的
。我使用包装器的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!我要试一试。