Hi,
I'm trying to write a simple WPF app that has two ellipses, joined by a line, like you might see in a network graph. When the ellipses are animated, I just want the joining line to automagically 'stick' to the canvas locations of the two ellipses that the line joins. The XAML is just a canvas:
<Window x:Class="UIDataBindingDemo.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="400" Width="400">
<Grid>
<Canvas x:Name="cnvExample" />
</Grid>
...and I'm just doing some really simple stuff in the constructor here:
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
namespace UIDataBindingDemo
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
// create 2 ellipses, one next to the other, and add them to the canvas
Ellipse el1 = new Ellipse();
Canvas.SetTop(el1, 100);
Canvas.SetLeft(el1, 100);
el1.Width = 20;
el1.Height = 20;
el1.Fill = Brushes.Red;
el1.Stroke = Brushes.Black;
Ellipse el2 = new Ellipse();
Canvas.SetTop(el2, 100);
Canvas.SetLeft(el2, 200);
el2.Width = 20;
el2.Height = 20;
el2.Fill = Brushes.Blue;
el2.Stroke = Brushes.Black;
cnvExample.Children.Add(el1);
cnvExample.Children.Add(el2);
// create a line that connects the 2 ellipses. Bind the two points that define this line to the
// locations of our ellipses, so the line always connects them, through animations, drag and drop
// operations, whatever.
Line line = new Line();
line.StrokeThickness = 3;
line.Stroke = Brushes.Black;
line.SetBinding(Line.X1Property, new Binding("(Canvas.Left)") { Source = el1 });
line.SetBinding(Line.X1Property, new Binding("(Canvas.Top)") { Source = el1 });
line.SetBinding(Line.X1Property, new Binding("(Canvas.Left)") { Source = el2 });
line.SetBinding(Line.X1Property, new Binding("(Canvas.Top)") { Source = el2 });
cnvExample.Children.Add(line);
// animate the second ellipse, so it moves down and to the right, nice and slow
var moveTheBlueOne = new DoubleAnimation(300, TimeSpan.FromSeconds(10));
el2.BeginAnimation(Canvas.LeftProperty, moveTheBlueOne);
el2.BeginAnimation(Canvas.TopProperty, moveTheBlueOne);
}
}
I'm pretty new to WPF, and I'm sure I'm missing something simple. Why am I not seeing the line?