C# 加载引用 XAML cs中动态加载xaml xaml中引用xaml

C# cs代码中加载 XAML

1、全局加载

csharp 复制代码
ResourceDictionary languageResDic = new ResourceDictionary();
languageResDic.Source = new Uri("View/Theme.xaml", UriKind.RelativeOrAbsolute);
this.Resources.MergedDictionaries.Add(languageResDic);

2、动态加载外部xaml文件

csharp 复制代码
using (FileStream s = new FileStream(@"C:\Users\Lin.net\Desktop\WpfApplication1\Xaml\Test.xaml", FileMode.Open))
{
    Grid grid = XamlReader.Load(s) as Grid;
    Window win = new Window1();
    win.Content = grid;
    win.ShowDialog();
}

3、动态加载内部xaml

1、动态加载

csharp 复制代码
Button btn =new  Button();
btn.SetValue(Button.StyleProperty, Application.Current.Resources["资源名称"]);



Style appButtonStyle = (Style)Application.Current.Resources["appButtonStyle"];

2、动态加载

csharp 复制代码

4、Xaml引用内部xaml资源文件

1、资源文件

csharp 复制代码
<Window.Resources>
    <Style x:Key="myBtnStyle" TargetType="{x:Type Button}">
        <Setter Property="Height" Value="72" />
        <Setter Property="Width" Value="150" />
        <Setter Property="Foreground" Value="Red" />
        <Setter Property="Background" Value="Black" />
        <Setter Property="HorizontalAlignment" Value="Left" />
        <Setter Property="VerticalAlignment" Value="Top" />
    </Style>
</Window.Resources>

2、加载

csharp 复制代码
<Button Style="{StaticResource myBtnStyle}"></Button>

5、xaml资源文件引用xaml外部资源文件

1、资源文件

csharp 复制代码
<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:System="clr-namespace:System;assembly=mscorlib">
    <Style x:Key="myBtnStyle" TargetType="Button">
    <Setter Property="Height" Value="72" />
    <Setter Property="Width" Value="150" />
    <Setter Property="Foreground" Value="White" />
    <Setter Property="Background" Value="Blue" />
    <Setter Property="HorizontalAlignment" Value="Left" />
    <Setter Property="VerticalAlignment" Value="Top" />
    </Style>
</ResourceDictionary>

2、加载

csharp 复制代码
<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="/应用名称;component/Theme/Style.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>
相关推荐
好望角雾眠1 小时前
第一阶段C#基础-10:集合(Arraylist,list,Dictionary等)
笔记·学习·c#
繁星¹⁸⁹⁵4 小时前
通过update-alternatives可以实现cuda的多版本切换
服务器
开航母的李大6 小时前
软件系统运维常见问题
运维·服务器·系统架构·运维开发
有梦想的攻城狮7 小时前
Java 11中的Collections类详解
java·windows·python·java11·collections
忒可君7 小时前
C# winform FTP功能
开发语言·windows·c#
十五年专注C++开发8 小时前
CMake进阶: CMake Modules---简化CMake配置的利器
linux·c++·windows·cmake·自动化构建
degree5208 小时前
全平台轻量浏览器推荐|支持Win/macOS/Linux,极速加载+隐私保护+扩展插件,告别广告与数据追踪!
windows·macos·电脑
时光追逐者8 小时前
C#/.NET/.NET Core技术前沿周刊 | 第 50 期(2025年8.11-8.17)
c#·.net·.netcore·.net core
一个会的不多的人9 小时前
C# NX二次开发:操作按钮控件Button和标签控件Label详解
开发语言·c#
咕白m6259 小时前
C# 实现 PDF 转图片 - 分辨率设置、图片格式选择
后端·c#