0

我已将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()}
4

1 回答 1

0

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

  Text="{Binding BrowserViewModel.PageTitle, Converter={app:StringTruncator}}"
于 2013-05-21T16:25:03.983 回答