WPF 的應用程式如何自動更新呢?照目前微軟的建議,會使用ClickOnce 的方式來部署。之後,程式就可以照ClickOnce的方式來更新了。
以下是簡單的範例。
範例
xaml
<Window x:Class="AutoUpdate.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> <StackPanel Name="panel"> <TextBlock Text="V1" /> </StackPanel> </Grid> </Window>
code
using System.Deployment.Application; using System.Windows; using System.Windows.Controls; namespace AutoUpdate { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); AutoUpdateIt(); } private void AutoUpdateIt() { if (ApplicationDeployment.IsNetworkDeployed) { var ad = ApplicationDeployment.CurrentDeployment; var info = ad.CheckForDetailedUpdate(); if (info.UpdateAvailable) { UpdateApp(); DisplayRestartMessage(); } } } private void UpdateApp() { ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment; ad.Update(); } private void DisplayRestartMessage() { var newText = new TextBlock { Text = "程式已經更新。請重新啟動程式" }; panel.Children.Add(newText); var button = new Button() { Content = "Restart" }; button.Click += (sender, e) => Restart(sender, null); panel.Children.Add(button); } private void Restart(object sender, RoutedEventArgs e) { System.Windows.Forms.Application.Restart(); Application.Current.Shutdown(); } } }
程式非常簡單。當程式運作時,發現了有新的版本,就自動下載並更新。更新完後,顯示訊息並讓使用者按「Restart」鍵重新啟動程式。
範例程式下載