首页 > 解决方案 > C# WPF:调整绑定到目标的源值

问题描述

rect在一个名为 UserControl的矩形中,DisplayLabel其宽度绑定到ActualWidthMainWindow 的。是否有可能使它rect.width绑定到类似的东西MainWindow.ActualWidth -50?这样矩形总是比屏幕宽度小 50 像素。

这是后面代码中的绑定。

           Rectangle rect = new Rectangle();
           rect.Fill = Brushes.Aquamarine;
           rect.Height = 20;
           Binding widthBinding = new Binding("ActualWidth");
           widthBinding.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(MainWindow), 1);
           rect.SetBinding(Rectangle.WidthProperty, widthBinding);


           UCgrid.Children.Add(rect);

这篇SO 帖子建议之后进行缩放以更改对象的大小。有没有办法ScaleTransform可以实现我的目标?

标签: c#wpfdata-binding

解决方案


您可以使用自定义 ValueConverter 甚至提供要减去的金额作为转换器参数:

public class SubtractionConverter : IValueConverter
{
    public object Convert(
        object value, Type targetType, object parameter, CultureInfo culture)
    {
        // Contrived example - make sure to type check before using 'value'
        return (float)value - (float)parameter)
    }

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

然后在您的 C#(或 XAML)中:

widthBinding.Converter = new SubtractionConverter();
widthBinding.ConverterParameter = 50f;

推荐阅读