0

我知道您可以轻松地将孩子的身高与父母的身高绑定:

windowSelector.SetBinding(HeightProperty, 
    new Binding(nameof(mainWindow.ActualHeight)) { Source = mainWindow });

但是,我正在努力弄清楚如何绑定到该值的修改版本,即mainWindow.ActualHeight- 30 甚至一个的高度 - 另一个的高度?

4

1 回答 1

0

评论中的链接导致 a 的实现过于复杂Converter,但最终 aConverter是我需要的,这里是更简单的实现。

添加一个实现IValueConverter

public class ValueConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        try
        {
            return System.Convert.ToInt32(value.ToString()) + 
                   System.Convert.ToInt32(parameter.ToString());
        }
        catch
        {
            return 0;
        }
    }
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        try
        {
            return System.Convert.ToInt32(value.ToString()) + 
                   System.Convert.ToInt32(parameter.ToString());
        }
        catch
        {
            return 0;
        }
    }
}

您需要Resource在窗口中使用它XAML

<Window x:Class=...>
    <Window.Resources>
        <local:ValueConverter x:Key="valueConverter"/>
    </Window.Resources>

然后绑定Converter

Height="{ Binding ActualHeight, ElementName=mainWindow, Converter={ StaticResource valueConverter }, ConverterParameter=-100 }"
于 2021-05-08T19:28:50.597 回答