更改xaml中的绑定值

时间:2013-02-27 21:11:36

标签: c# wpf data-binding

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

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分:0)

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

以下是您提到的方案的示例,您可以绑定到窗口宽度并使用Converte r将宽度除以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;
    }
}

的Xaml:

<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>