WPF 后台动态调用样式文件,就像CSS样式表文件一样

阅读更多
应用场合:如果您的WPF应用程序设置WPF运行一个实例代码后,App.xaml文件中对样式资源字典文件的引用将失效.

解决办法1:在App.xaml.cs文件中用反射动态调用另外一个DLL项目中的样式文件即可

解决办法2:在每个窗体的xaml文件中添加对指定样式文件的引用(本文不做介绍)

详细操作介绍如下:

1、WPF设置只运行一个实例代码:

App.xaml文件代码如下:
             
    
     
        
    
        
   



App.xaml.cs文件代码如下:

//添加引用
using System.Diagnostics;
using System.IO;
using System.Reflection;

namespace WpfUI
{

    ///
    /// App.xaml 的交互逻辑
    ///

    public partial class App : Application
    {

        public App()
        {
        }

        ///
        /// 要设置App.xaml的文件属性中生成操作=无
        ///

        [STAThread]       
        public static void Main()
        {
            App myApp = new App();                         
            myApp.ShutdownMode = ShutdownMode.OnExplicitShutdown;
            myApp.Run();
        }

        private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            if (e.Exception is InvalidOperationException)
                e.Handled = true;
        }

        protected override void OnStartup(StartupEventArgs e)
        {
            //获取当前运行WPF程序的进程实例
            Process process = Process.GetCurrentProcess();
            //遍历WPF程序的同名进程组
            foreach (Process p in Process.GetProcessesByName(process.ProcessName))
            {
                if (p.Id != process.Id && (p.StartTime - process.StartTime).TotalMilliseconds <= 0)
                {
                    p.Kill();//关闭进程
                    return;
                }
            }
            base.OnStartup(e);
            //启动登陆窗体,

          TestWindow myWindow = new TestWindow();

          myWindow.Show();
      }

    }

}

2、ButtonStyle.xaml样式文件内容如下:

    xmlns=" http://schemas.microsoft.com/winfx/2006/xaml/presentation "
    xmlns:x=" http://schemas.microsoft.com/winfx/2006/xaml "
    xmlns:ed=" http://schemas.microsoft.com/expression/2010/drawing ">

   
   


3、TestWindow.xaml文件内容如下:



你可能感兴趣的:(wpf)