Xaml 将控件用作静态资源会导致异常
对于我的Windows Phone 8.1应用程序,我试图通过将图标放入我的XAML页面的Xaml 将控件用作静态资源会导致异常,xaml,windows-phone-8,windows-phone,Xaml,Windows Phone 8,Windows Phone,对于我的Windows Phone 8.1应用程序,我试图通过将图标放入我的XAML页面的ResourceDictionary,将其作为静态资源提供: <phone:PhoneApplicationPage.Resources> <ResourceDictionary> <Path x:Name="MyIcon" Width="38" Height="31.6667" Fill="{StaticResource PhoneForegroundBrush}
ResourceDictionary
,将其作为静态资源提供:
<phone:PhoneApplicationPage.Resources>
<ResourceDictionary>
<Path x:Name="MyIcon" Width="38" Height="31.6667" Fill="{StaticResource PhoneForegroundBrush}" Data="..."/>
</ResourceDictionary>
</phone:PhoneApplicationPage.Resources>
…在此行抛出一个ArgumentException
:值不在预期范围内。
在XAML中直接引用MyIcon
时,它会正确显示在可视化编辑器中,但会在加载页面时导致XAMLParseException
我是做错了什么,还是不可能将控件对象用作静态资源?在可视化/逻辑树的少数位置不能使用UIElement的一个实例。因此,您的路径当前在树中,无法使用。 我在上一个项目中遇到了同样的问题,我的解决方案是通过值转换器创建路径
public class PathConv
: IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var data = value as string;
if (data == null)
{
return value;
}
return CreatePath(data);
}
private Path CreatePath(string pathString)
{
var xaml = string.Format("<Path xmlns='{0}'><Path.Data>{1}</Path.Data></Path>",
"http://schemas.microsoft.com/winfx/2006/xaml/presentation",
pathString);
return XamlReader.Load(xaml) as Path;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
请看我之前的答案,它仍然适用于wp,您只需将其转换为contentcontrol。这可能是一个解决方法,但并不能真正回答我的失败原因,但无论如何,谢谢。我会说,因为您没有将其称为静态资源,并期望它神奇地找到MyIcon,但是对不起,朋友,我是一个xaml/前端的家伙,所以我的无知背后的代码对你没有多大帮助。希望有人能教我们两个新东西。@ChrisW我不希望它神奇地出现。由于上面的代码片段位于页面的代码隐藏类中,因此实际上可以通过这种方式访问它,即所有带有
x:Name
的UIElement都可以通过这种方式寻址。如果不是,我可能会在编译时出错。哈哈,这正是我现在使用的解决方法,只是我正在硬编码整个路径,因为我需要显式的高度和。:)您可以将路径存储为字符串而不是路径数据,并由XamlReaderYeah构造它,但是为每个路径存储三个字符串对我来说似乎是一种过度使用。
public class PathConv
: IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var data = value as string;
if (data == null)
{
return value;
}
return CreatePath(data);
}
private Path CreatePath(string pathString)
{
var xaml = string.Format("<Path xmlns='{0}'><Path.Data>{1}</Path.Data></Path>",
"http://schemas.microsoft.com/winfx/2006/xaml/presentation",
pathString);
return XamlReader.Load(xaml) as Path;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
<phone:PhoneApplicationPage.Resources>
<ResourceDictionary>
<PathConv x:Name="conv" />
<String x:Key="PathData">...</String>
</ResourceDictionary>
</phone:PhoneApplicationPage.Resources>
Button buyButton = new Button { Content = conv.Convert(Resources["PathData"], null, null, null) };