wpf canvas从资源中添加元素

时间:2014-01-14 13:27:50

标签: wpf xaml

我是wpf的新手

<Window.Resources>
        <Ellipse x:Key="connectorNode" Height="20" Width="20" Fill="Green" Stroke="Black" StrokeThickness="2" MouseMove="Ellipse_MouseMove" MouseLeftButtonDown="Ellipse_MouseLeftButtonDown" MouseLeftButtonUp="Ellipse_MouseLeftButtonUp"></Ellipse>
 </Window.Resources>

如何在画布中添加资源中的Ellipse实例,我只想指定Canvas.LeftCanvas.Right,但使用与资源相同的属性值

<Canvas>
</Canvas>

2 个答案:

答案 0 :(得分:2)

您似乎想要创建一个通用样式并将其应用于添加的每个Ellipse,这就是您可以这样做的方法:

<Window x:Class="MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <Style x:Key="EllipseStyle" TargetType="Ellipse">
            <Setter Property="Height" Value="20"/>
            <Setter Property="Width" Value="20" />
            <EventSetter Event="Control.MouseMove" Handler="Control_MouseMove" />
        </Style>
    </Window.Resources>
    <Grid>
        <Canvas>
            <Ellipse Style="{StaticResource EllipseStyle}" />
        </Canvas>
    </Grid>
</Window>

编辑:我添加了“EventSetter”,因此您可以在样式中定义事件(请参阅this post)。

答案 1 :(得分:1)

如果您真的想要使用资源中的元素并仅应用画布属性,则可以这样做:

<Window.Resources>
    <ControlTemplate x:Key="connectorNode" >
        <Ellipse 
            Height="20" 
            Width="20" 
            Fill="Green" 
            Stroke="Black" 
            StrokeThickness="2" 
            MouseMove="Ellipse_MouseMove" 
            MouseLeftButtonDown="Ellipse_MouseLeftButtonDown" 
            MouseLeftButtonUp="Ellipse_MouseLeftButtonUp" />
    </ControlTemplate>
</Window.Resources>
<Canvas>
    <ContentControl Template="{StaticResource connectorNode}"/>
    <ContentControl Canvas.Left="50" Template="{StaticResource connectorNode}"/>
</Canvas>