簡體   English   中英

如何在 WPF 后面的代碼中綁定屬性

[英]How Do I Bind Properties in Code Behind WPF

我對 WPF 很陌生......所以我需要用橢圓 canvas.left 和 canvas.top 屬性綁定線 X1 和 Y1 屬性......

在 XAML 它工作正常......

XAML 代碼

<Ellipse x:Name="tst" Width="40" Height="40" Canvas.Left="150" Canvas.Top="150" Stroke="Blue" StrokeThickness="2" MouseMove="adjustRoute"/>
<Line X1="{Binding ElementName=tst, Path=(Canvas.Left)}" Y1="{Binding ElementName=tst, Path=(Canvas.Top)}" X2="300" Y2="200" Stroke="Blue" StrokeThickness="2"/>

但我需要在代碼后面使用 C#

所以我做了這個

temp = new Line();
tempe = new Ellipse();
tempe.Fill = Brushes.Transparent;
tempe.Stroke = Brushes.Blue;
tempe.StrokeThickness = 1;
tempe.Width = 20;
tempe.Height = 20;
Canvas.SetLeft(tempe, currentPoint.X-10);
Canvas.SetTop(tempe, currentPoint.Y-10);
tempe.MouseMove += adjustRoute;
Binding binding = new Binding { Source = tempe, Path = new PropertyPath(Canvas.LeftProperty), UpdateSourceTrigger=UpdateSourceTrigger.PropertyChanged };
temp.SetBinding(Line.X1Property, binding);
Binding binding2 = new Binding { Source = tempe, Path = new PropertyPath(Canvas.TopProperty), UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged };
temp.SetBinding(Line.Y1Property, binding2);
temp.Stroke = Brushes.Blue;
temp.StrokeThickness = 2;
temp.X1 = currentPoint.X;
temp.Y1 = currentPoint.Y;
temp.X2 = currentPoint.X + 200;
temp.Y2 = currentPoint.Y + 200;
testcanv.Children.Add(temp);
testcanv.Children.Add(tempe);

但是當我移動橢圓時它不會更新 position 行(在 XAML 中它會更新)....

這里currentPoint是我在運行時單擊鼠標捕獲的點以繪制形狀,而 adjustRoute 是 function 以在拖動時移動它們

我在這里做錯了什么?

謝謝

確保只創建一次 Line 和 Ellipse 元素,並且只分配一次綁定。 將 MouseMove 處理程序分配給 Canvas 而不是 Ellipse:

private Line line;
private Ellipse ellipse;

public MainWindow()
{
    InitializeComponent();

    line = new Line
    {
        Stroke = Brushes.Blue,
        StrokeThickness = 2
    };

    ellipse = new Ellipse
    {
        Stroke = Brushes.Blue,
        StrokeThickness = 1,
        Width = 20,
        Height = 20,
        Margin = new Thickness(-10)
    };

    Binding xBinding = new Binding
    {
        Source = ellipse,
        Path = new PropertyPath(Canvas.LeftProperty)
    };
    line.SetBinding(Line.X1Property, xBinding);

    Binding yBinding = new Binding
    {
        Source = ellipse,
        Path = new PropertyPath(Canvas.TopProperty)
    };
    line.SetBinding(Line.Y1Property, yBinding);

    testcanv.Children.Add(line);
    testcanv.Children.Add(ellipse);

    testcanv.Background = Brushes.Transparent;
    testcanv.MouseMove += adjustRoute;
}

private void adjustRoute(object sender, MouseEventArgs e)
{
    var p = e.GetPosition(testcanv);
    Canvas.SetLeft(ellipse, p.X);
    Canvas.SetTop(ellipse, p.Y);
}

暫無
暫無

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

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