【问题标题】:Build a Line UserControl建立一个线用户控件
【发布时间】:2010-11-30 18:58:25
【问题描述】:

是否可以构建一个 WPF UserControl SegmentControl,具有类似于线条形状坐标(X1,Y1)和(X2,Y2)?

我已经构建了一个自定义 Line Shape,但我需要一个 UserControl,因为我添加了一些额外的可自定义元素,例如文本和项目符号。

我编写了一些代码,但认为我需要帮助:

<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 = 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; // ??
}

【问题讨论】:

  • X1 Y1 和 X2 Y2 在这种情况下是什么意思?它们是否在您的控制范围内您的分段坐标?
  • @Nicolas Repiquet x1、y1、x2 和 y2 的含义与 Line 形状的含义相同。线的坐标(在我的画布的具体情况下)“极端”点。

标签: .net wpf user-controls


【解决方案1】:

在您需要的点的 UserControl 上创建一个自定义 DependencyProperty 并将您的 Line 位置绑定到它怎么样?

你的 UserControl 应该是这样的:

<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>

你会像这样使用它:

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

【讨论】:

  • 这段代码很酷,但是,使用 StartPosition (0,0) 行应该在容器的左上角...,但事实并非如此,因为“行”位置是相对于 UC,但 StartPosition - tot UC 父级。此外,应该有一种方法来绑定 UC Canvas.Left 等属性...)
  • 不将行的 X1:Y1 绑定到 StartPosition,而是将 UserControl 的 Canvas.TopCanvas.Left 绑定到 StartPosition,并将 X1:Y1 设置为 0:0。将 Line 的 X2:Y2 绑定到 EndPosition
猜你喜欢
  • 1970-01-01
  • 2019-04-28
  • 2015-10-04
  • 2014-04-09
  • 2015-08-03
  • 1970-01-01
  • 1970-01-01
  • 2016-01-21
  • 1970-01-01
相关资源
最近更新 更多