1

我想知道是否有办法将一个元素的属性绑定到另一个元素的属性,但修改其间的数据。例如,我可以将文本块的 FontSize 绑定到窗口的宽度/20 或类似的东西吗?我已经遇到过几次这很有用的领域,但总是找到解决方法(通常涉及向我的 viewModel 添加字段)。优选完全xaml溶液。

4

2 回答 2

1

是的,通过实施IValueConverter

对于转换器,您的方案看起来像这样:

[ValueConversion(typeof(double), typeof(double))]
public class DivideBy20Converter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var f = (double) value;
        return f/20.0;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var f = (double)value;
        return f * 20.0;
    }
}

...以及 XAML 中的类似内容:

<Window x:Class="WpfApplication3.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
        xmlns:wpfApplication3="clr-namespace:WpfApplication3"
        Title="MainWindow" Height="350" Width="525"
        x:Name="Window">
    <Window.Resources>
        <wpfApplication3:DivideBy20Converter x:Key="converter"></wpfApplication3:DivideBy20Converter>        
    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition />
            <RowDefinition />
        </Grid.RowDefinitions>
        <TextBox FontSize="{Binding ElementName=Window, Path=Width, Converter={StaticResource converter}}"></TextBox>
    </Grid>
</Window>
于 2013-02-27T21:23:08.970 回答
0

你可以IValueConverters用来处理这样的逻辑。

这是您提到的场景的示例,您可以绑定到窗口宽度并使用Converter 将宽度除以中提供的值ConverterParameter

public class MyConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value != null && parameter != null)
        {
            double divisor = 0.0;
            double _val = 0.0;
            if (double.TryParse(value.ToString(), out _val) && double.TryParse(parameter.ToString(), out divisor))
            {
                return _val / divisor;
            }
        }
        return value;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return null;
    }
}

xml:

<Window x:Class="WpfApplication7.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:converters="clr-namespace:WpfApplication7"
        Title="MainWindow" Height="124" Width="464" Name="YourWindow" >

    <Window.Resources>
        <converters:MyConverter x:Key="MyConverter" />
    </Window.Resources>

    <StackPanel>
        <TextBlock FontSize="{Binding ElementName=YourWindow, Path=ActualWidth, Converter={StaticResource MyConverter}, ConverterParameter=20}" />
    </StackPanel>
</Window>
于 2013-02-27T21:24:43.283 回答