У меня есть два приложения WPF (Приложение1 и Приложение2), и Приложение1 добавляет пользователя в файл Users.xml , а Приложение2 отображает все имена из Users.xml в метке.Чтобы обновить метку в Application2, я должен нажать кнопку «Обновить» в моей текущей реализации.Я хочу создать механизм, чтобы при добавлении пользователя с помощью Application1 приложение 2 автоматически обновляло метку.Один из способов добиться этого - всякий раз, когда Application1 добавляет пользователя, он устанавливает какой-либо флаг в XML-файле (например, IsSync = false ), и Application2 постоянно отслеживает этот флаг, и всякий раз, когда он видит IsSync = false, он обновляетМетка и устанавливает IsSync = true.Но я хотел бы знать, существуют ли какие-либо другие лучшие способы (возможно, для издателя / подписчика путем обработки кнопки «Обновить» приложения 2 из приложения 1) для достижения этой цели.Не могли бы вы помочь мне достичь этого?Я приложил оба XAML / код ниже:

Application1
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();
}
}
}