【问题标题】:C# WPF: Adjust Source Values Being Bound to TargetC# WPF:调整绑定到目标的源值
【发布时间】:2021-09-29 21:31:06
【问题描述】:

我在名为DisplayLabel 的用户控件中有一个矩形rect,其宽度绑定到主窗口的ActualWidth。是否有可能使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);

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

【问题讨论】:

    标签: c# wpf data-binding


    【解决方案1】:

    您可以使用自定义 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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-18
      • 1970-01-01
      • 2014-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多