简体   繁体   English

WPF:以编程方式绑定Canvas.Top和Panel.ZIndex

[英]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#? 如何仅通过C#中的代码绑定对象的Canvas.Top和Panel.ZIndex属性? 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. 我想获得的效果是,si尽可能多地位于画布上(最高值越高),其Z属性越高。 I'm kind new to WPF so I can't figure out well how to do 我是WPF的新手,所以我不知道该怎么做

You could try this: 您可以尝试以下方法:

    <Canvas>
        <Border Panel.ZIndex="{Binding Location, Converter={StaticResource DoubleToIntConverter}}" Canvas.Top="{Binding Location}"/>
    </Canvas>

DoubleToIntConverter is a converter that takes a Double and returns an int. DoubleToIntConverter是一个接受Double并返回int的转换器。 Location is a Double stored in your ViewModel. Location是存储在ViewModel中的Double。

You could create a Binding as shown below. 您可以如下所示创建一个绑定。 The parantheses in the Path string are necessary because the source property is an attached property. 因为source属性是附加属性,所以Path字符串中的括号是必需的。

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: 您还可以像这样直接将源DependencyProperty传递给PropertyPath构造函数:

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. doubleint转换是由框架隐式完成的。 However, if you need some "scaling" factor, you would also have to add a Binding Converter. 但是,如果需要一些“缩放”因子,则还必须添加一个绑定转换器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM