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>
相关推荐
Kelvin_Ngan40 分钟前
C#从XmlDocument提取完整字符串
c#
lingllllove2 小时前
使用 HTTP::Server::Simple 实现轻量级 HTTP 服务器
服务器·网络协议·http
Linux运维老纪2 小时前
K8s之Service详解(Detailed Explanation of K8s Service)
服务器·网络·云原生·容器·kubernetes·云计算·运维开发
iqay2 小时前
【C语言】填空题/程序填空题1
c语言·开发语言·数据结构·c++·算法·c#
神秘剑客_CN3 小时前
使用windows笔记本让服务器上网
运维·服务器·windows
star010-4 小时前
【视频+图文详解】HTML基础4-html标签的基本使用
前端·windows·经验分享·网络安全·html·html5
黑牛先生5 小时前
【Linux】动静态库
linux·运维·服务器
明 庭9 小时前
通过 Docker 部署 pSQL 服务器的教程
服务器·docker·容器
神秘剑客_CN9 小时前
使用vhd虚拟磁盘安装两个win10系统
windows
中游鱼10 小时前
C# 数组和列表的基本知识及 LINQ 查询
c#·linq·数组·数据处理·list数列