【发布时间】:2021-11-29 00:24:01
【问题描述】:
我有两个 WPF 窗口,一个带有列表,另一个用于更改该列表的内容。我怎么能这样做?
非常感谢您的宝贵时间。
【问题讨论】:
-
如果其中一个窗口是对话框,您可以将主窗口的数据上下文传递给对话框并在关闭后更新。如果两个窗口同时打开。我个人喜欢使用静态类,或者更全局的中心对象来充当中介。如果这成为一种常见的模式,我可能会尝试以更好的方式解决它,但如果它是一次性的,我会使用中心的东西。
我有两个 WPF 窗口,一个带有列表,另一个用于更改该列表的内容。我怎么能这样做?
非常感谢您的宝贵时间。
【问题讨论】:
最简单的例子
型号:
using System;
using System.Collections.ObjectModel;
namespace WpfApp1
{
internal class Model
{
public Model()
{
AddStuff = new RelayCommand(() => Collection.Add(DateTime.Now.ToString()));
}
public RelayCommand AddStuff { get; }
public ObservableCollection<string> Collection { get; } = new();
}
}
命令:
#nullable enable
using System;
using System.Windows.Input;
namespace WpfApp1
{
public class RelayCommand : ICommand
{
private readonly Func<bool> _canExecute;
private readonly Action _execute;
public RelayCommand(Action execute) : this(execute, () => true)
{
}
public RelayCommand(Action execute, Func<bool> canExecute)
{
_execute = execute;
_canExecute = canExecute;
}
public bool CanExecute(object? parameter)
{
return _canExecute();
}
public void Execute(object? parameter)
{
_execute();
}
public event EventHandler? CanExecuteChanged;
}
}
App.xaml:模型是共享的
<Application x:Class="WpfApp1.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApp1"
StartupUri="Window1.xaml">
<Application.Resources>
<local:Model x:Key="Model" />
</Application.Resources>
</Application>
窗口 1:
<Window
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"
x:Class="WpfApp1.Window1"
mc:Ignorable="d"
Title="Window1" Height="450" Width="800" DataContext="{StaticResource Model}">
<Grid>
<ListBox ItemsSource="{Binding Collection}" />
</Grid>
</Window>
窗口 1:
using System.Windows;
namespace WpfApp1
{
public partial class Window1
{
public Window1()
{
InitializeComponent();
Loaded += OnLoaded;
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
new Window2().Show();
}
}
}
窗口 2:
<Window x:Class="WpfApp1.Window2"
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"
mc:Ignorable="d"
Title="Window2" Height="450" Width="800" DataContext="{StaticResource Model}">
<Grid>
<Button Content="Whatever" Command="{Binding AddStuff}" />
</Grid>
</Window>
窗口 2:
namespace WpfApp1
{
public partial class Window2
{
public Window2()
{
InitializeComponent();
}
}
}
【讨论】:
例如,通过保留对要从另一个窗口更新的窗口的引用,或使用 Application.Current.Windows 属性获取对该窗口的引用:
var listBoxInWindow1 = Application.Current.Windows.OfType<Window1>()?
.FirstOrDefault()?.listBox1;
Window1.xaml:
<ListBox x:Name="listBox1" .... />
【讨论】: