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>
相关推荐
运维行者_3 小时前
Applications Manager中的Redis监控
大数据·服务器·数据库·人工智能·网络协议
xingyuzhisuan6 小时前
网络 Token 常见故障原理,基础排查科普
运维·服务器·网络·php
m0_535817556 小时前
从0到1上手Claude Code:Windows安装+88api配置全流程
windows·gpt·node.js·claude·claudecode·88api
z落落7 小时前
C#String字符串
开发语言·c#·php
wljy17 小时前
二、进制状态转换
linux·运维·服务器·c语言·c++
浮生若城8 小时前
Linux——Ext系列文件系统
linux·运维·服务器
ITyunwei09878 小时前
主流 SaaS 工单系统对比
运维·服务器·人工智能
阿昭L9 小时前
Windows用户态hook技术总结
windows·逆向·hook
影寂ldy10 小时前
C#数组的属性和方法(Clear / Copy / IndexOf )
开发语言·javascript·c#
无情的西瓜皮12 小时前
MCP协议实战:从零搭建一个AI Agent工具服务器
运维·服务器·python