程序化绑定控件中的算术

时间:2015-08-28 19:04:15

标签: c# wpf binding ivalueconverter

我想设置以编程方式创建的控件的绑定。这里以XAML为例,说明我正在尝试使用扩展" qc":

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

以下是我在实际代码中尝试做的一个示例:

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);

我已使用Grid进行了调查,因此我可以使用WidthHeightGridUnitType.Star设置为百分比,但我可以将其设置为{&1;}。事实上,它很可能造成更多的伤害而不是好处,所以我试图咬住子弹,看看我是否可以这样做。

1 个答案:

答案 0 :(得分:0)

“qc”语法看起来不像转换器,而是标记扩展。如果你想使用IValueConverter(看起来最好),那么你只需将它添加到绑定中。

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

转换器代码应如下所示:

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();
    }
}

(如果出于某种原因,您确实需要在XAML摘录中使用自定义“qc”绑定,那么您可能只需要在代码中设置“formula”属性,无论其名称是什么。)