2010-10-20 48 views
4

我正在嘗試維護其他人的代碼,該人員是WPF專家。另一方面,我不是。 :)WPF IValueConverter - 將多個值轉換爲單個值

該代碼使用IValueConverter將狀態枚舉轉換爲布爾值,該布爾值控制是否在屏幕上顯示UserControl。

我發現了一個缺點,即在這種情況下單個枚舉是不夠的,實際上還有另一個布爾值需要考慮。是否還有另一個對象可以用來作爲參數來進行轉換? (「轉換器」參數已被使用。)

一個快速示例如下。

現有代碼的邏輯說...

If it's sunny, go to work. 
If it's raining, don't go to work. 

我需要別的東西考慮進去,這將使其如下。

If it's sunny and you're wearing pants, go to work. 
If it's sunny and you're not wearing pants, don't go to work. 
If it's raining and you're wearing pants, don't go to work. 
If it's raining and you're not wearing pants, don't go to work. 

的IValueConverter,這將執行轉換隻允許我採取一個「東西」的轉換。

任何幫助表示讚賞。謝謝,

MJ

回答

14

使用IMultiValueConverter

public class MyMultiValueConverter: IMultiValueConverter 
{ 
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) 
    { 
     // Do something with the values array. It will contain your parameters 
    } 

    public object[] ConvertBack(object values, Type[] targetType, object parameter, CultureInfo culture) 
    { 
     throw new NotImplementedException(); 
    } 
} 

您還需要在XAML使用MultiBinding而不是常規的結合

<MultiBinding Converter="{StaticResource MyMultiValueConverterKey}"> 
    <Binding Path="Value1" /> 
    <Binding Path="Value2" /> 
</MultiBinding> 
+0

謝謝!我正在嘗試。 mj – 2010-10-20 16:47:25

+0

我有一個問題。如何根據頁面上兩個文本框的非空值啓用/禁用按鈕?我可以使用樣式,IMultivalueConvertor但如果文本框的數量不斷變化/增加。有沒有辦法動態監視檢查按鈕的行爲?你想讓我爲此提出一個單獨的問題嗎? – Vikram 2016-12-16 11:24:51

+1

@Vikram一個單獨的問題將是最好的。很可能你想要設置你的CanExecuteCommand,以便它檢查所有綁定字段的值,並且只有在它們都有值時才返回true。 – Rachel 2016-12-16 21:42:55