是否可以构建一个WPF UserControl SegmentControl
,类似于线形坐标(X1,Y1)和(X2,Y2)?
我已经构建了一个自定义行 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; // ??
}
答案 0 :(得分:3)
如何在您需要的点的UserControl上创建自定义DependencyProperty
,并将您的线位置绑定到它?
您的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}" />