WPF後台動態調用樣式檔案

來源:互聯網
上載者:User

應用場合:如果您的WPF應用程式設定WPF運行一個執行個體代碼後,App.xaml檔案中對樣式資源字典檔案的引用將失效.

解決辦法1:在App.xaml.cs檔案中用反射動態調用另外一個DLL項目中的樣式檔案即可

詳細操作介紹如下:

1、WPF設定只運行一個執行個體代碼:

App.xaml檔案代碼如下:
    <Application.Resources>         
     <ResourceDictionary>
      <ResourceDictionary.MergedDictionaries>
         <ResourceDictionary Source="ButtonStyle.xaml"/>
     </ResourceDictionary>        
    </Application.Resources>
</Application>

App.xaml.cs檔案代碼如下:

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

namespace WpfUI
{

    /// <summary>
    /// App.xaml 的互動邏輯
    /// </summary>
    public partial class App : Application
    {

        public App()
        {
        }

        /// <summary>
        /// 要設定App.xaml的檔案屬性中產生操作=無
        /// </summary>
        [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);
            //啟動登陸表單,

          MainWindow myWindow = new MainWindow();

          myWindow.Show();
      }

    }

}

2、ButtonStyle.xaml樣式檔案內容如下:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <!--按鈕樣式-->
    <Style x:Key="RedButtonStyle" TargetType="{x:Type Button}">
        <Setter Property="Foreground" Value="Red"/>
        <Setter Property="Background" Value="Silver"/>
        <Setter Property="Height" Value="23"/>
    </Style>
   
</ResourceDictionary> 

3、MainWindow.xaml檔案內容如下:

<Window x:Class="WpfUI.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Button Content="Button" Style="{StaticResource RedButtonStyle}" Height="23" HorizontalAlignment="Left" Margin="102,66,0,0" Name="button1" VerticalAlignment="Top" Width="75" />
    </Grid>
</Window>
 

4、運行程式後發現按鈕樣式RedButtonStyle總提示找不到

5、 解決辦法如下:

第一步: 建立一個Windows--類庫項目WpfThems,將ButtonStyle.xaml拷貝過去, 設定ButtonStyle.xaml檔案的屬性產生操作為 "Page",之後產生WpfThems.dll檔案

第二步:在當前項目WpfUI中添加WpfThems項目引用

第三步:修改App.xaml.cs 檔案代碼:添加一個函數LoadStyleResource並修改OnStartup函數內容。修改後的App.xaml.cs檔案內容如下:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;
//添加引用
using System.Diagnostics;
using System.IO;
using System.Reflection;

namespace WpfUI
{
    /// <summary>
    /// App.xaml 的互動邏輯
    /// </summary>
    public partial class App : Application
    {

        public App()
        {
        }

        /// <summary>
        /// 設定WpfUI項目中的App.xaml的檔案屬性中"產生操作"為"無"
        /// 設定WpfThemes項目中的ButtonStyle.xaml的檔案屬性中"產生操作"為"Page"
        /// </summary>
        [STAThread]
        public static void Main()
        {
            App myApp = new App();
            myApp.ShutdownMode = ShutdownMode.OnExplicitShutdown;
            myApp.Run();
        }

        /// <summary>
        /// 重載應用程式啟動函數
        /// </summary>
        /// <param name="e"></param>
        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);
            //動態調用樣式檔案
            LoadStyleResource();

            //啟動表單
            MainWindow myWindow = new MainWindow();
            myWindow.Show();
        }
        private void LoadStyleResource()
        {
            Assembly assembly = Assembly.LoadFrom("WpfThemes.dll");
            string packUri = @"/WpfThemes;component/ButtonStyle.xaml";
            ResourceDictionary myResourceDictionary = Application.LoadComponent(new Uri(packUri, UriKind.Relative)) as ResourceDictionary;
            this.Resources.MergedDictionaries.Add(myResourceDictionary);
        }
    }
}

 

解決辦法2:在每個表單的xaml檔案中添加對指定樣式檔案的引用

<Window.Resources>

 <ResourceDictionary>

<ResourceDictionary.MergedDictionaries>

<ResourceDictionary Source="ButtonStyle.xaml"/>

 </ResourceDictionary.MergedDictionaries>

 </ResourceDictionary>

</Window.Resources>

詳細工程項目請到我的下載資源中下載: http://download.csdn.net/detail/xqf222/5582575

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.