我有两个WPF应用程序(Application1和Application2),Application1将用户添加到 Users.xml 文件中,Application2将所有从Users.xml的名称显示到标签。要刷新Application2中的Label,我必须在当前实现中按Refresh按钮。我想建立一种机制,以便每当我向Application1添加用户时,Application2都会自动更新Label。我可以实现此目的的一种方法是,每当Application1添加用户,在XML文件中设置一些标志(例如 IsSync = false )并且Application2不断监视该标志并且每当看到IsSync = false时,它都会更新标签并设置IsSync = true。但是我想知道是否还有其他最佳方法(也许是通过处理Application1中Application2的Refresh按钮的发布者/订阅者方法)来实现的。你能帮我实现这个目标吗?我在下面附加了两个XAML /代码:
应用程序1
XAML
<Window x:Class="Application1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Application1"
mc:Ignorable="d"
Title="Application1" Height="500" Width="500">
<Grid>
<Label Name="lblUserName" Content="Name" HorizontalAlignment="Left" Margin="42,60,0,0" VerticalAlignment="Top"/>
<TextBox Name="txtUserName" HorizontalAlignment="Left" Height="23" Margin="91,60,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="300"/>
<Button Name="btnAdd" Content="Add" HorizontalAlignment="Left" Margin="310,110,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>
</Grid>
</Window>
隐藏代码
using System.IO;
using System.Windows;
using System.Xml;
using System.Xml.Linq;
namespace Application1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private static string fullPath = "C:\\Files\\Users.xml";
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
if (!string.IsNullOrWhiteSpace(txtUserName.Text))
{
if (!File.Exists(fullPath))
{
// If Users.xml is not exists, create a file and add Textbox Name to the file
CreateUsersXMLAndAddUser();
txtUserName.Text = "";
}
else
{
// Add Textbox name to the Users.xml
AddUser();
txtUserName.Text = "";
}
}
else
{
MessageBox.Show(this, "Name can not be empty", "Required", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
private void AddUser()
{
XElement xEle = XElement.Load(fullPath);
xEle.Add(new XElement("User", new XAttribute("Name", txtUserName.Text.Trim())));
xEle.Save(fullPath);
}
private void CreateUsersXMLAndAddUser()
{
XDocument xDoc = new XDocument(
new XDeclaration("1.0", "UTF-8", null),
new XElement("Users",
new XElement("User",
new XAttribute("Name", txtUserName.Text.Trim())
)));
StringWriter sw = new StringWriter();
XmlWriter xWrite = XmlWriter.Create(sw);
xDoc.Save(xWrite);
xWrite.Close();
xDoc.Save(fullPath);
}
}
}
应用程序2
XAML
<Window x:Class="Application2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Application2"
mc:Ignorable="d"
Title="Application2" Height="500" Width="600">
<Grid>
<Label Name="lblUsers" FontSize="20" FontWeight="UltraBold" HorizontalAlignment="Left" Margin="20,20,0,0" VerticalAlignment="Top"/>
<Button Name="btnRefreshUsers" Content="Refresh" FontSize="20" FontWeight="UltraBold" HorizontalAlignment="Left" Margin="450,39,0,0" VerticalAlignment="Top" Height="100" Width="100" Click="btnRefreshUsers_Click"/>
</Grid>
</Window>
隐藏代码
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows;
using System.Xml.Linq;
namespace Application2
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private static string fullPath = "C:\\Files\\Users.xml";
StringBuilder userList;
public MainWindow()
{
InitializeComponent();
userList = new StringBuilder();
lblUsers.Content = string.Empty;
lblUsers.Content = LoadUsers();
}
private StringBuilder LoadUsers()
{
userList.AppendLine(" Users ");
userList.AppendLine("---------");
if (File.Exists(fullPath))
{
XElement xelement = XElement.Load(fullPath);
IEnumerable<XElement> users = xelement.Elements();
foreach (var user in users)
{
userList.AppendLine(user.Attribute("Name").Value);
}
}
else
{
userList.AppendLine("Nothing to show ...");
}
return userList;
}
private void btnRefreshUsers_Click(object sender, RoutedEventArgs e)
{
userList.Clear();
lblUsers.Content = string.Empty;
lblUsers.Content = LoadUsers();
}
}
}
答案 0 :(得分:1)
有几种方法可以在进程之间进行通信:
从理论上讲,在通信水平较低的情况下,大多数此类技术都将套接字用作主要部分。因此Socket编程是一种底层通信,您拥有更多的控制权,还需要做更多的工作才能使它正常工作。
我已经阅读了一个很好的答案:
答案 1 :(得分:0)
我已经实现FileSystemWatcher来实现我的目标。此处更改了Application2中的完整代码,以侦听Users.xml中的更改。
应用程序2
背后的代码
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows;
using System.Xml.Linq;
namespace Application2
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private static string fullPath = "C:\\Files\\Users.xml";
StringBuilder userList;
public MainWindow()
{
InitializeComponent();
userList = new StringBuilder();
lblUsers.Content = string.Empty;
lblUsers.Content = LoadUsers();
CreateFileWatcher(@"C:\\Files");
}
private StringBuilder LoadUsers()
{
userList.AppendLine(" Users ");
userList.AppendLine("---------");
if (File.Exists(fullPath))
{
XElement xelement = XElement.Load(fullPath);
IEnumerable<XElement> users = xelement.Elements();
foreach (var user in users)
{
userList.AppendLine(user.Attribute("Name").Value);
}
}
else
{
userList.AppendLine("Nothing to show ...");
}
return userList;
}
private void btnRefreshUsers_Click(object sender, RoutedEventArgs e)
{
userList.Clear();
lblUsers.Content = string.Empty;
lblUsers.Content = LoadUsers();
}
private void CreateFileWatcher(string path)
{
// Create a new FileSystemWatcher and set its properties.
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = path;
/* Watch for changes in LastAccess and LastWrite times, and the renaming of files or directories. */
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName;
// Only watch text files.
watcher.Filter = "Users.xml";
// Add event handlers.
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnChanged);
// Begin watching.
watcher.EnableRaisingEvents = true;
}
// Define the event handlers.
private void OnChanged(object source, FileSystemEventArgs e)
{
// Specify what is done when a file is changed, created, or deleted.
lblUsers.Dispatcher.Invoke(new Action(delegate ()
{
userList.Clear();
lblUsers.Content = string.Empty;
lblUsers.Content = LoadUsers();
}), System.Windows.Threading.DispatcherPriority.Normal);
}
}
}