0

我想通过复选框激活转换。

在我的示例中,我有两个复选框,它们应该分别在 x 或 y 方向上交换标签中的文本。

如果没有代码,这可能吗?

到目前为止,这是我的 xaml:

<Window x:Class="WpfVideoTest.InversionTestWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="InversionTestWindow" Height="300" Width="300">
<DockPanel>
    <CheckBox DockPanel.Dock="Bottom" IsChecked="{Binding InvertX}">Invert X</CheckBox>
    <CheckBox DockPanel.Dock="Bottom" IsChecked="{Binding InvertY}">Invert Y</CheckBox>
    <Label Content="Text to invert" FontSize="40" x:Name="TextToInvert">
        <Label.RenderTransform>
            <TransformGroup>
                <!-- transformations to swap in x direction -->
                <ScaleTransform ScaleX="-1"  />
                <TranslateTransform X="{Binding ActualWidth, ElementName=TextToInvert}" />
                <!-- transformations to swap in y direction -->
                <ScaleTransform ScaleY="-1" />
                <TranslateTransform Y="{Binding ActualHeight, ElementName=TextToInvert}" />
            </TransformGroup>
        </Label.RenderTransform>
    </Label>
</DockPanel>

4

1 回答 1

1

您需要使用ConverterMultiConverter。是的,它是代码,但它是将代码添加到 WPF 中的绑定的有序方式。从概念上讲,您希望应用于转换的值依赖于其他值,而转换类本身没有该功能。

这就是转换器的外观。它需要三个值,其中第一个是布尔值。

public class TernaryConditionalMultiConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (values.Length >= 3 && values[0] is bool)
        {
            return (bool)values[0] ? values[1] : values[2];
        }
        return null;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

你会这样使用它:

<ScaleTransform>
    <ScaleTransform.ScaleX>
        <MultiBinding Converter="{StaticResource TernaryConditionalConverter}">
            <Binding Path="InvertX" />
            <Binding Source="{StaticResource PositiveOne}" />
            <Binding Source="{StaticResource NegativeOne}" />
        </MultiBinding>
    </ScaleTransform.ScaleX>
</ScaleTransform>

其中 PositiveOne 和 NegativeOne 已被定义为资源,例如:

<sys:Double x:Key="PositiveOne">1</sys:Double>
于 2013-05-02T15:13:25.313 回答