2011-04-07 52 views
12

我想根據綁定值將TextBlock設置爲可見/摺疊模式。它不起作用,當我想調試我的應用程序時,我收到以下消息:WPF:無法設置轉換器 - 啓動應用程序時出錯

Set property'System.Windows.Data.Binding.Converter'throw a exception。

綁定的值的類型爲Uri。有一個內部InvalidCastException這樣說:

無法將'System.String'類型的對象轉換爲鍵入'System.Windows.Data.IValueConverter'。

這裏是我的轉換器:

public class VisibilityConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, 
     object parameter, CultureInfo culture) 
    { 
     if (value is string && string.IsNullOrEmpty(value as string)) 
     { 
      return Visibility.Collapsed; 
     } 
     else if (value == null) 
     { 
      return Visibility.Collapsed; 
     } 
     else 
     { 
      return Visibility.Visible; 
     } 
    } 

    public object ConvertBack(object value, Type targetType, 
     object parameter, CultureInfo culture) 
    { 
     throw new NotSupportedException(); 
    } 
} 

而這裏的拋出異常的XAML:

... 
<Page.Resources> 
    <converters:VisibilityConverter x:Key="visibilityConverter" /> 
</Page.Resources> 
... 
<TextBlock Visibility="{Path=UrlAddress, Converter=visibilityConverter}"> 
    This never works! 
</TextBlock> 
... 

幫助,請!

回答

43

嘗試引用您的轉換器作爲靜態資源

<TextBlock Visibility="{Path=UrlAddress, Converter={StaticResource visibilityConverter}}"> 
+0

恭喜第一個答案;) – Boris 2011-04-07 12:02:07

+0

非常感謝:) – 2013-07-18 19:14:14

1

應該

<TextBlock Visibility="{Path=UrlAddress, Converter={StaticResource visibilityConverter}}">` 
1

忘了提綁定標記擴展與可能的ElementName屬性?

<TextBlock Visibility="{Binding ElementName=XXX, Path=UrlAddress, Converter={StaticResource visibilityConverter}}"> ` 
相關問題