I am currently designing a system, (my first in WPF) and i am looking to bind properties of my custom control to elements set within the control-style.
<Style TargetType="{x:Type c:Connection}">
<Setter Property="SnapsToDevicePixels" Value="true"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type c:Connection}">
<Grid DataContext="{Binding RelativeSource={RelativeSource TemplatedParent}}">
<Line Stroke="Red" X1="90" X2="90" Y1="90" Y2="5"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
I am looking to bind the elements of the Line (X1/2 Y1/2) to properties within my Connection Control. However, as soon as i add a connection element (in code, even without binding), i get a Type Initialization Error. My Connection class is as follows:
public class Connection : Control
{
public Connector StartElement { get; set; }
public Connector EndElement { get; set; }
#region Properties
#endregion
}
And I Initialize as follows: Connection con = new Connection(); (and then i add it to the canvas).
How can i bind the coordinates to a the Points that are in Connector? (ex StartElement.GetXPosition());
Kind Regards Tom
Are you sure your creating your elements correctly?
This works for me:
In Connection.cs
file
using System.Windows.Controls;
public class Connector {
public int X { get; set; }
public int Y { get; set; }
}
public class Connection : Control {
public Connector StartElement { get; set; }
public Connector EndElement { get; set; }
}
Xaml
:
<UserControl x:Class="WpfApplication1.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1">
<UserControl.Resources>
<Style TargetType="{x:Type local:Connection}">
<Setter Property="SnapsToDevicePixels"
Value="true" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:Connection}">
<Grid DataContext="{Binding RelativeSource={RelativeSource TemplatedParent}}">
<Line Stroke="Red"
X1="{Binding StartElement.X}"
X2="{Binding EndElement.X}"
Y1="{Binding StartElement.Y}"
Y2="{Binding EndElement.Y}" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</UserControl.Resources>
<Canvas x:Name="canvasElement"
Background="White" />
</UserControl>
and UserControl
code-behind:
public UserControl1() {
InitializeComponent();
Connection connectionVariable = new Connection {
StartElement = new Connector { X = 0, Y = 0 },
EndElement = new Connector { X = 300, Y = 300 }
};
canvasElement.Children.Add(connectionVariable);
Canvas.SetLeft(connectionVariable, 0);
Canvas.SetTop(connectionVariable, 0);
}
Running this, I see a Red diagonal line.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.