WPF类库,加载带有绝对URI或相对URI的XAML都不起作用
本文关键字:URI 相对 XAML 不起作用 类库 加载 WPF | 更新日期: 2023-09-27 18:14:41
我正在编写一个主要基于c#代码的WPF类库,我目前正在尝试加载XAML文件,仅用于样式UI元素。
下面是带有"BuildAction: Content":
的XAML "style"代码<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1">
<Style x:Key="LabelStyle" TargetType="{x:Type Label}">
<Setter Property="Height" Value="53" />
<Setter Property="Width" Value="130" />
<Setter Property="HorizontalAlignment" Value="Left" />
<Setter Property="Margin" Value="99,71,0,0" />
<Setter Property="VerticalAlignment" Value= "Top" />
<Setter Property="Foreground" Value="#FFE75959" />
<Setter Property="FontFamily" Value="Calibri" />
<Setter Property="FontSize" Value="40" />
</Style>
下面是我的标签代码:
private void CreateElement(int i)
{
UIElementOut[i] = new Label();
var uiElement = (Label)UIElementOut[i];
uiElement.HorizontalAlignment = HorizontalAlignment.Center;
uiElement.VerticalAlignment = VerticalAlignment.Center;
uiElement.FontFamily = new FontFamily(FFontInput[i]);
uiElement.FontSize = Convert.ToDouble(FontSizeIn[i]);
uiElement.Content = TextIn[i];
Brush BgBrushColor = new SolidColorBrush(RGBAToMediaColor(FBgCol[i]));
Brush FgBrushColor = new SolidColorBrush(RGBAToMediaColor(FFgCol[i]));
uiElement.Background = BgBrushColor;
uiElement.Foreground = FgBrushColor;
Uri uri = new Uri("pack://application:,,,/WpfApplication1;component/WpfApplication1/Styles/LabelStyle.xaml", UriKind.Relative);
StreamResourceInfo info = Application.GetContentStream(uri);
System.Windows.Markup.XamlReader reader = new System.Windows.Markup.XamlReader();
ResourceDictionary myResourceDictionary = Application.LoadComponent(uri) as ResourceDictionary;
Application.Current.Resources.MergedDictionaries.Add(myResourceDictionary);
Style myLabelStyle = myResourceDictionary["LabelStyle"] as Style;
uiElement.Style = myLabelStyle;
}
如果UriKind被设置为"相对",我得到这个错误信息:
A relative URI cannot be created because the 'uriString' parameter represents an absolute URI.
但是如果Urikind被设置为"绝对",那么我得到这个:
Cannot use absolute URI.
所以在这两种情况下,XAML文件都没有加载,样式也没有应用。
编辑:I tried this URI:
pack://application:,,,/WpfApplication1;component/Styles/LabelStyle.xaml
并得到相同的错误
引用位于本地程序集的项目文件夹子文件夹中的资源文件的正确格式
pack://application:,,,/Subfolder/ResourceFile.xaml
在单独引用的程序集中引用资源文件的正确格式是
pack://application:,,,/ReferencedAssembly;component/Subfolder/ResourceFile.xaml
将uri更改为
pack://application:,,,/WpfApplication1;component/Styles/LabelStyle.xaml
应该解决这个问题