1

ある要素のプロパティを別の要素のプロパティにバインドするが、その間のデータを変更する方法があるかどうか疑問に思っています。たとえば、テキストブロックのFontSizeをウィンドウのwidth / 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;
    }
}

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>
于 2013-02-27T21:24:43.283 に答える