2013-03-25 213 views
1

我目前正在設計一個系統(我的第一個WPF),我正在尋找將我的自定義控件的屬性綁定到控件樣式中設置的元素。WPF與自定義控件綁定

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

我期待將Line(X1/2 Y1/2)的元素綁定到我的Connection Control中的屬性。然而,只要我添加一個連接元素(在代碼中,即使沒有綁定),我得到一個類型初始化錯誤。我的連接類如下:

public class Connection : Control 
{ 
    public Connector StartElement { get; set; } 
    public Connector EndElement { get; set; } 

    #region Properties 


    #endregion 

} 

而且我的初始化如下:Connection con = new Connection(); (然後我將它添加到畫布)。

如何將座標綁定到連接器中的點? (ex StartElement.GetXPosition());

親切的問候 湯姆

+0

這聽起來像我在[這個例子]中做的事情(http://stackoverflow.com/questions/15579069/graph-nodes-coordinates-evaluation/15580293#15580293) – 2013-03-25 16:28:42

+0

什麼是確切的錯誤你得到什麼位置在你的代碼中導致錯誤?如果你包含你的初始化代碼,它會有所幫助。 – Rachel 2013-03-25 16:50:48

回答

1

你確定你正確地創建元素?

這個工作對我來說:

Connection.cs文件

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> 

UserControl後臺代碼:

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); 
} 

運行這個,我看到一條紅色的對角線。