【问题标题】:Converter not found? XamlParseException: Cannot find a Resource with the Name/Key StringTruncator找不到转换器? XamlParseException:找不到具有名称/键 StringTruncator 的资源
【发布时间】:2013-05-16 11:51:58
【问题描述】:

我已将StringTruncator 转换器包含在我的App.Resources

xmlns:app="clr-namespace:Tabbed_Browser">

<!--Application Resources-->
<Application.Resources>

    <ResourceDictionary>
        <app:StringTruncator x:Key="StringTruncator" />
        <app:StringTruncatorFav x:Key="StringTruncatorFav" />        
        <app:AppInfo x:Key="AppInfo" />
        <app:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" /       
    </ResourceDictionary>

</Application.Resources>

然后在 UserControl XML 中我通过此代码引用它

<Grid x:Name="LayoutRoot" Background="{StaticResource PhoneChromeBrush}">
    <TextBlock TextWrapping="NoWrap" x:Name="txtPageTitle" 
            Text="{Binding BrowserViewModel.PageTitle, Converter={StaticResource StringTruncator}}" 
            FontSize="{StaticResource PhoneFontSizeSmall}"    
            VerticalAlignment="Top"/>

StringTruncator 是一个简单的转换器,如果字符串超过一定长度,则附加 ...

namespace Tabbed_Browser
{
public class StringTruncator : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null)
            return ""; 

        string str = value.ToString();
        int maxChars = 44;
        return str.Length <= maxChars ? str : str.Substring(0, maxChars) + "...";
    }

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

}

但随后我运行该项目,我得到以下信息。删除代码中的StringTruncator 转换器可消除错误,但我需要使用转换器。我错过了什么?

{System.Windows.Markup.XamlParseException:
 Cannot find a Resource with the Name/Key StringTruncator [Line: 15 Position: 22]
  at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
  at Tabbed_Browser.User_Controls.UCAddressBar.InitializeComponent()
  at Tabbed_Browser.User_Controls.UCAddressBar..ctor()}

【问题讨论】:

    标签: c# xaml windows-phone-8 converter


    【解决方案1】:

    您应该改用 DynamicResource,这样它将在运行时应用。或者,您可以将资源添加到 Usercontrol.Resources 本身。或者您也可以这样做,但您还必须将命名空间添加到 UserControl:

      Text="{Binding BrowserViewModel.PageTitle, Converter={app:StringTruncator}}"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-05
      • 2012-10-31
      • 1970-01-01
      • 1970-01-01
      • 2012-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多