c# - C# WPF:调整绑定到目标的源值
问题描述
我rect
在一个名为 UserControl的矩形中,DisplayLabel
其宽度绑定到ActualWidth
MainWindow 的。是否有可能使它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
可以实现我的目标?
解决方案
您可以使用自定义 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;
推荐阅读
- google-cloud-platform - 计算实例的 GCP gcloud API 过滤标签
- r - 想要根据列名改变平均列的列,但还要从计算中排除某些列?
- python - 查找磁盘何时未连接?
- mongodb - 如何在数组中找到数组的最大值?
- mysql - 计算一个字符串表示的json对象的值的总和
- c++ - 对一个数组进行排序并在第二个数组交换 C++ 中具有相应的值
- google-cloud-platform - Google Cloud Run 服务上的 DNS_PROBE_FINISHED_NXDOMAIN 错误
- ruby - 将 ruby 应用程序部署到云代工厂,rubygems 失败
- python - Python——如何在不同命名的函数下添加输入函数
- c# - 我想知道C#中函数和方法的区别