Back to Devexpress

How to: Bind Items Position to a Source Object

windowsforms-403718-controls-and-libraries-diagrams-examples-how-to-bind-items-position-to-a-source-object.md

latest3.0 KB
Original Source

How to: Bind Items Position to a Source Object

  • Jan 19, 2022
  • 2 minutes to read

This example demonstrates how to bind the Position property of diagram items to the view model in two-way mode.

Define the CustomLayoutItems event:

csharp
public Form1() {
    InitializeComponent();
    diagramDataBindingController1.CustomLayoutItems += DiagramDataBindingController1_CustomLayoutItems;
    //...
}

private void DiagramDataBindingController1_CustomLayoutItems(object sender, DiagramCustomLayoutItemsEventArgs e) {
    e.Handled = true;
}
vb
Public Sub New()
            InitializeComponent()
            AddHandler diagramDataBindingController1.CustomLayoutItems, AddressOf Me.DiagramDataBindingController1_CustomLayoutItems
            '...
        End Sub

        Private Sub DiagramDataBindingController1_CustomLayoutItems(ByVal sender As Object, ByVal e As DiagramCustomLayoutItemsEventArgs)
            e.Handled = True
        End Sub

Add a Position property of the PointFloat type to the data source:

csharp
public class Item : BindableBase {
    public int Id { get; set; }
    public string Name { get; set; }
    public PointFloat Position { get => GetProperty(() => Position); set => SetProperty(() => Position, value); }
}
vb
Public Class Item
    Inherits BindableBase

    Public Property Id As Integer

    Public Property Name As String

    Public Property Position As PointFloat
        Get
            Return GetProperty(Function() Me.Position)
        End Get

        Set(ByVal value As Point)
            SetProperty(Function() Position, value)
        End Set
    End Property
End Class

Specify a DiagramBinding for the Position property:

csharp
private void DiagramDataBindingController1_GenerateItem(object sender, DiagramGenerateItemEventArgs e) {
    var item = new DiagramShape {
        X = 27,
        Width = 75,
        Height = 50,
        Shape = BasicShapes.Rectangle
    };
    item.Bindings.Add(new DiagramBinding("Position", "Position", DiagramBindingMode.TwoWay));
    e.Item = item;
}
vb
Private Sub DiagramDataBindingController1_GenerateItem(ByVal sender As Object, ByVal e As DiagramGenerateItemEventArgs)
    Dim item = New DiagramShape With {.X = 27, .Width = 75, .Height = 50, .Shape = BasicShapes.Rectangle}
    item.Bindings.Add(New DiagramBinding("Position", "Position", DiagramBindingMode.TwoWay))
    e.Item = item
End Sub

View Example