简体   繁体   English

程序绑定控件中的算术

[英]Arithmetic in Programmatically Bound Controls

I want to set the binding of programmatically created control with arithmetic involved. 我想设置以编程方式创建的控件与所涉及的算术的绑定。 Here as example of the XAML of what I am trying to do using the extension "qc": 这是我使用扩展名“ qc”尝试执行的XAML的示例:

<ColumnDefinition x:Name="MidColumn" 
      Width="{qc:Binding '$P * .727', P={Binding ActualHeight, ElementName=PaperCanvas}}" />

Here's an example of what I'm trying to do in the actual code: 这是我要在实际代码中尝试执行的示例:

Binding binding = new Binding();
//Below is pseudo code for what i'm trying to do
binding.Path = new PropertyPath(Canvas.ActualWidthProperty * 0.7);
binding.Source = TrueCanvas;
binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
BindingOperations.SetBinding(((Rectangle)CurrentControl), Rectangle.WidthProperty, binding);

I've looked into using a Grid so I can set the Width and Height as a percentage using GridUnitType.Star , but with where I'm at as it is, it would more than likely cause more harm than good, so I'm trying to just bite the bullet and see if I can get it done this way. 我已经研究过使用Grid因此可以使用GridUnitType.StarWidthHeight设置为百分比,但是按我所处的位置,它很可能造成弊大于利,所以我试着咬住子弹,看看我能不能这样做。

That "qc" syntax does not look like a converter, but rather a markup extension. 该“ qc”语法看起来不像转换器,而是标记扩展。 If you want to use an IValueConverter (which does seem best), then you simply add it to the binding. 如果要使用IValueConverter(看起来最好),则只需将其添加到绑定中即可。

binding.Path = new PropertyPath(Canvas.ActualWidthProperty);
binding.Converter = new WidthConverter();

The converter code should look something like this: 转换器代码应如下所示:

public class WidthConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        var x = (double)value;
        return x * 0.7;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

(If for some reason you did actually need to use that custom "qc" Binding as in your XAML excerpt, then you would probably just need to set that "formula" property, whatever its name is, in the code.) (如果由于某种原因您确实确实需要像在XAML摘录中那样使用自定义的“ qc”绑定,那么您可能只需要在代码中设置该“ formula”属性,无论其名称是什么。)

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

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