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>
相关推荐
山川绿水4 分钟前
Ubuntu22.04更新Openssh至9.9p2无法正常连接,报错解决
服务器·web安全·网络安全
古希腊数通小白(ip在学)16 分钟前
HCIA实现不同vlan间的通信
linux·服务器·网络
每日出拳老爷子27 分钟前
[C#] 使用TextBox换行失败的原因与解决方案:换用RichTextBox的实战经验
开发语言·c#
星辰离彬29 分钟前
Java 与 MySQL 性能优化:MySQL连接池参数优化与性能提升
java·服务器·数据库·后端·mysql·性能优化
小苹果13572 小时前
阿里云mysql数据丢失,如何通过服务器备份在其他服务器上恢复数据,并获取mysql丢失数据,完成mysql数据恢复
服务器·mysql·阿里云
许白掰2 小时前
Linux入门篇学习——Linux 工具之 make 工具和 makefile 文件
linux·运维·服务器·前端·学习·编辑器
hrrrrb3 小时前
【TCP/IP】12. 文件传输协议
服务器·网络·tcp/ip
安全系统学习6 小时前
网络安全之RCE分析与利用详情
服务器·网络·安全·web安全·系统安全
longze_76 小时前
Ubuntu连接不上网络问题(Network is unreachable)
linux·服务器·ubuntu