簡體   English   中英

具有自定義控件的WPF綁定

[英]WPF binding with custom control

我目前正在設計一個系統(我在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中的屬性。 但是,一旦我添加了一個連接元素(即使在沒有綁定的情況下,在代碼中),我也會收到類型初始化錯誤。 我的Connection類如下:

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

   #region Properties


    #endregion

}

然后初始化如下:Connection con = new Connection(); (然后我將其添加到畫布)。

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

親切的問候湯姆

確定要正確創建元素嗎?

這對我有用:

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

運行此命令,我看到一條紅色對角線。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM