开发者

Build a Line UserControl

Is it possible to build a WPF UserControl SegmentControl, having similar to the Line shape coordinates (X1, Y1) and (X2, Y2)?

I already built a custom Line Shape, but I need an UserControl, because I add some additional customizable elements, like text and bullets to it.

I built some code, but think I need help:

<UserControl>
<!-- internal Canvas; The UsrCtrl Parent is supposed to be a Canvas too -->
    <Canvas>
        <Line x:Name="line" Stroke="Black" StrokeThickness="1"></Line>
        <Label x:Name="label" Content="Paris - Moscow"/>
    </Canvas>
</UserControl>

*.cs

public partial class SegmentControl : UserControl
{
    #region dependency properties
    public static readonly DependencyProperty X1Property;

...
static void OnXYChanged(DependencyObject source, DependencyPropertyChangedEventArgs e)
{
    SegmentControl s = source as SegmentControl;
    UpdateControlPositionAndSize(s);
}

static void UpdateControlPositionAndSize(SegmentControl sc)
{
    double left = Math.Min(sc.X1, sc.X2);
    double top = Math.Min(sc.Y1, sc.Y2);

    double width = sc.X2 - sc.X1;
    double height 开发者_JAVA技巧= sc.Y2 - sc.Y1;

    Canvas.SetLeft(sc, left);
    Canvas.SetTop(sc, top);
    sc.Width = width;
    sc.Height = height;

    sc.line.X1 = sc.X1; // ??
    sc.line.Y1 = sc.Y1; // ??
    sc.line.X2 = sc.X2; // ??       
    sc.line.Y2 = sc.Y2; // ??
}


What about just creating a custom DependencyProperty on the UserControl of the Points you need, and binding your Line position to it?

Your UserControl would be something like this:

<UserControl>
    <Canvas>
        <Line x:Name="line" Stroke="Black" StrokeThickness="1"
              X1="{Binding RelativeSource={RelativeSource AncestorType={x:Type my:SegmentControl}}, Path=StartPosition.X}"
              Y1="{Binding RelativeSource={RelativeSource AncestorType={x:Type my:SegmentControl}}, Path=StartPosition.Y}"
              X2="{Binding RelativeSource={RelativeSource AncestorType={x:Type my:SegmentControl}}, Path=EndPosition.X}"
              Y2="{Binding RelativeSource={RelativeSource AncestorType={x:Type my:SegmentControl}}, Path=EndPosition.Y}" />

        <Label x:Name="label" 
               Content="{Binding={RelativeSource RelativeSource AncestorType={x:Type my:SegmentControl}}, Path=Text}"/>
    </Canvas>
</UserControl>

You would use it something like this:

<my:SegmentControl 
    StartPosition="{Binding Path=StartPoint}"
    EndPosition="{Binding Path=EndPoint}" 
    Text="{Binding Path=SegmentText}" />
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜