我主要基于C#代码编写WPF类库,而我目前正在尝试仅为样式化UI元素加载XAML文件。
这是XAML"风格"代码与" BuildAction:内容" :
<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设置为&#34;相对&#34;我收到此错误消息:
A relative URI cannot be created because the 'uriString' parameter represents an absolute URI.
但是如果Urikind被设置为&#34; Absolute&#34;然后我得到了这个:
Cannot use absolute URI.
因此,无论如何,未加载XAML文件且未应用样式。
编辑:
我试过这个URI:
pack://application:,,,/WpfApplication1;component/Styles/LabelStyle.xaml
并得到同样的错误。
答案 0 :(得分:0)
更正位于本地程序集项目文件夹
子文件夹中的资源文件的格式pack://application:,,,/Subfolder/ResourceFile.xaml
在单独引用的程序集中引用资源文件的正确格式为
pack://application:,,,/ReferencedAssembly;component/Subfolder/ResourceFile.xaml
将你的uri改为
pack://application:,,,/WpfApplication1;component/Styles/LabelStyle.xaml
应解决问题