2013-05-02 68 views
0

我想通過複選框激活轉換。是否可以通過綁定在xaml中打開和關閉轉換?

在我的示例中,我有兩個複選框,它們應該分別在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> 

回答

1

你需要使用ConverterMultiConverter。是的,它是代碼,但是它是將代碼添加到WPF綁定中的有序方式。從概念上講,您有一種情況,您希望應用於變換的值依賴於某個其他值,而變換類本身不具備該功能。

這是轉換器的外觀。它期望三個值,其中第一個是bool。

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

我得到「System.Windows.Data錯誤:5:由BindingExpression生成的值對於目標屬性無效; Value ='1'MultiBindingExpression:目標元素爲'ScaleTransform'(HashCode = 43184669);目標屬性爲'ScaleX'(類型'Double')「 。 1.0也不起作用。那麼我怎麼能給這個轉換器一個正確的double值和第三個綁定? – MTR 2013-05-06 15:19:27

+0

沒關係,我找到了。只需使用StaticResource進行雙重幫助。無論如何,由於其他原因(綁定更新不正確),我最終得到了一個轉換器,它根據InvertX和InvertY給出了完整的轉換。 – MTR 2013-05-06 15:45:40

+0

是的,我會編輯響應以獲得一些數字的靜態資源。感謝您指出了這一點。 – dtm 2013-05-06 18:58:09

相關問題