2010-02-11 30 views
3

一直用這個問題搜索幾個小時,並且無法看到我出錯的地方。IValueCOnverter不能正常工作

我有以下轉換器,它只是返回Brushes.Red(已嘗試Colors.Red)以及但仍然沒有運氣。

public class ColorConverter : IValueConverter 
{ 
    private static ColorConverter instance = new ColorConverter(); 
    public static ColorConverter Instance 
    { 
     get 
     { 
      return instance; 
     } 
    } 

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     return Brushes.Red; 
    } 
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     throw new Exception("The method or operation is not implemented."); 
    } 
} 

現在在我的XAML我有以下代碼:

<StackPanel Orientation="Vertical"> 
    <TextBlock Text="{Binding Value}" TextAlignment="Center" Foreground="{Binding Path=color, Converter={x:Static local:ColorConverter.Instance}}" Margin="2"/> 
</StackPanel> 

我已經設置格蘭以下命名空間的頂部:

xmlns:local="clr-namespace:Dashboard" 

現在我有一個綁定下面的類到堆棧面板:

public class MyClass : INotifyPropertyChanged 
{ 
    public String Value; 
    public Color color; 

    // Declare the PropertyChanged event 
    public event PropertyChangedEventHandler PropertyChanged; 
    public void NotifyPropertyChanged(String info) 
    { 
     if (PropertyChanged != null) 
     { 
      PropertyChanged(this, new PropertyChangedEventArgs(info)); 
     } 
    } 
} 

數據綁定(值)工作得很好,但轉換器不想踢,我試圖在covnerter的Convert方法中設置一個斷點,但調試時不會觸發它,它就好像我的調試器沒有被調用。

任何人都可以對此有所瞭解嗎?

回答

2

我很驚訝,你說綁定本身的作品,因爲「價值」和「顏色」是字段和綁定到字段不應該工作。

+0

是啊,我甚至懶得去看他們的聲明,因爲它聽起來像一切,但轉換器工作。 :) – Dave 2010-02-11 14:32:43

1

嗯,這是我在項目中做到的。我修改了我的代碼,以反映您正在嘗試執行的操作。我希望它有幫助。我無法回答爲什麼你的單身方法不起作用。

類:

public class ColorConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     return Brushes.Red; 
    } 
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     throw new Exception("The method or operation is not implemented."); 
    } 
} 

在我UserControl.Resources元素:

<UserControl.Resources> 
    <local:ColorConverter x:Key="MyColorConverter" /> 
</UserControl.Resources> 

的StackPanel元素:

<StackPanel Orientation="Vertical"> 
    <TextBlock Text="{Binding Value}" TextAlignment="Center" Foreground="{Binding Path=color, Converter={StaticResource MyColorConverter}}" Margin="2"/> 
</StackPanel> 

另外,你檢查你的輸出窗口,看是否有任何錯誤?您還應該閱讀Bea Stollnitz's article on debugging databindings。她實際上有一個關於IValueConverters的特定部分,可能有一天會派上用場。

+0

謝謝!進入我的輸出窗口後發現問題。 我不知道做一個變量你必須添加一個屬性{set;得到; }來。所以我沒有在那裏和輸出抱怨,它無法找到「顏色」屬性。 真的很感謝幫助,並感謝您的鏈接。添加到收藏夾! – 2010-02-11 14:09:18

+0

啊是的,你確實使用了一個字段而不是屬性。我之前犯過這個錯誤(顯然是這樣做了)。 :) – Dave 2010-02-11 14:31:53