user3489057 user3489057 - 1 month ago 14
C# Question

WPF: Bind Canvas.Top and Panel.ZIndex programmatically

How can I bind the Canvas.Top and Panel.ZIndex property of an object only via code in C#? The effect I want to obtain si the most the object is down on the canvas (higher top value) the higher is its Z property. I'm kind new to WPF so I can't figure out well how to do

Answer

You could create a Binding as shown below. The parantheses in the Path string are necessary because the source property is an attached property.

element.SetBinding(Panel.ZIndexProperty,
    new Binding
    {
        RelativeSource = RelativeSource.Self,
        Path = new PropertyPath("(Canvas.Top)")
    });

You could also directly pass the source DependencyProperty to the PropertyPath constructor like this:

element.SetBinding(Panel.ZIndexProperty,
    new Binding
    {
        RelativeSource = RelativeSource.Self,
        Path = new PropertyPath(Canvas.TopProperty)
    });

Conversion from double to int is done implicitly by the framework. However, if you need some "scaling" factor, you would also have to add a Binding Converter.