[英]Add dynamically user controls
Hello stackoverflowers. 你好stackoverflowers。
I would like to display dynamically some elements on the screen. 我想在屏幕上动态显示一些元素。 I have a OverlayElement base class, and some children classes.
我有一个OverlayElement基类,还有一些子类。 The OverlayElement base class contains a FrameworkElement that correspond to a small usercontrol that defines how to draw my OverlayElement.
OverlayElement基类包含一个FrameworkElement,该FrameworkElement对应一个小的用户控件,该控件定义了如何绘制我的OverlayElement。
I have an OverlayViewModel which contain a collection of OverlayElements, binded to an Itemcontrol in the View. 我有一个OverlayViewModel,其中包含一个OverlayElements集合,绑定到View中的Itemcontrol。
Here are excerpts of OverlayElement and a child. 这是OverlayElement和一个孩子的节选。
public abstract class OverlayElement : INotifyPropertyChanged
{
public UserControl View;
}
public class ImageOverlayElement : OverlayElement
{
public ImageOverlayElement(Point start, Point end)
{
View = new ImageOverlayElementView();
}
}
Here is an exemple of ImageOverlayElementView 这是ImageOverlayElementView的一个例子
<UserControl x:Class="Client.ImageOverlayElementView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:Client"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
d:DataContext="{d:DesignInstance local:ImageOverlayElement}">
<Grid>
<Image
Source="{Binding ImageSource}"
Height="{Binding Height}"
Width="{Binding Width}"/>
</Grid>
</UserControl>
And this is how i try to use these elements. 这就是我尝试使用这些元素的方式。 My problem is that i don't know how to insert my UserControl View from OverlayElement (initialized in the child class) :
我的问题是我不知道如何从OverlayElement插入我的UserControl视图(在子类中初始化):
<ItemsControl
ItemsSource="{Binding OverlayElementsList}"
Background="Transparent">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.Resources>
<DataTemplate DataType="{x:Type elements:OverlayElement}">
<!-- Need help for here, how can I insert my UserControl View from OverlayElement ? (initialized in the child class) -->
</DataTemplate>
</ItemsControl.Resources>
</ItemsControl>
You can simply put the view in ContentControl
: 您可以简单地将视图放在
ContentControl
:
<DataTemplate DataType="{x:Type local:OverlayElement}">
<ContentControl Content="{Binding View}" />
</DataTemplate>
But make sure View
is a property, otherwise it won't work with data binding. 但是请确保
View
是一个属性,否则它将不适用于数据绑定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.