我在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()}
答案 0 :(得分:0)
您应该使用 DynamicResource ,这样它将在运行时应用。或者您可以向Usercontrol.Resources本身添加资源。或者您也可以这样做,但您还必须将命名空间添加到UserControl:
Text="{Binding BrowserViewModel.PageTitle, Converter={app:StringTruncator}}"