我遇到的问题有点难以描述,所以请听一听。
我只是打开另一个窗口,然后尝试关闭第二个窗口。如果我使用第二个的InputBindings的命令,第二个关闭罚款。如果我直接调用关闭它会关闭第一个和第二个窗口。我希望代码能帮到这种情况。
WPF:Window1View(关键部分)
<Grid>
<Button Content="Button" Command="{Binding RptKeyDownCommand}" />
</Grid>
Window1ViewModel :(缩短列表)
using GalaSoft.MvvmLight.Command;
var _runCommand = new RelayCommand(() => Run(), () => CanRun());
public void Run()
{
var v = new Window2();
var vm = new Window2ViewModel();
vm.RequestClose += v.Close;
v.DataContext = vm;
v.ShowDialog();
}
public event Action RequestClose;
var _closeCommand = new RelayCommand(() => Close(), () => CanClose());
public void Close()
{
if (RequestClose != null)
RequestClose();
}
WPF:Window2View
<Window.InputBindings>
<KeyBinding Key="Escape" Command="{Binding CloseCommand}" />
</Window.InputBindings>
<TextBox Text="Hello">
<i:Interaction.Triggers>
<i:EventTrigger EventName="PreviewKeyDown">
<cmd:EventToCommand
Command="{Binding Close2Command, Mode=OneWay}"
PassEventArgsToCommand="True" />
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBox>
Window2ViewModel :(具有相同的Close Command加上EventToCommand结束点)
var _close2Command = new RelayCommand<KeyEventArgs>(p => Close2(p), p => CanClose2(p));
public void Close2(KeyEventArgs e)
{
if (e.Key == Key.Escape)
Close(); <- Here closes both Window1View and Window2View?
}
答案 0 :(得分:0)
从Window2ViewModel,您应该调用RequestClose not Close。
以下是Window2ViewModel的代码
RelayCommand _close2Command;
public ICommand Close2Command
{
get
{
if (_close2Command == null)
{
_close2Command = new RelayCommand(param => CloseEx(), param => CanClose());
}
return _close2Command;
}
}
public virtual void CloseEx()
{
Close();
}
public event Action RequestClose;
public virtual void Close()
{
if (RequestClose != null)
{
*RequestClose();*
}
}
public virtual bool CanClose()
{
return true;
}
Window1ViewModel的代码应为:
using GalaSoft.MvvmLight.Command;
var _runCommand = new RelayCommand(() => Run(), () => CanRun());
var vm;
public void Run()
{
var v = new Window2();
vm = new Window2ViewModel();
vm.RequestClose += CloseV2;
v.DataContext = vm;
v.ShowDialog();
}
public event Action RequestClose;
var _closeCommand = new RelayCommand(() => Close(), () => CanClose());
public void CloseV2()
{
vm.Close();
}
public void Close()
{
if (RequestClose != null)
RequestClose();
}
尝试了解您的代码。 请注意,在您的代码中,您将V1.RequestClose与V2.RequestClose绑定到同一方法Close。在我的情况下,我将它们分开,V2.RequestClose将始终调用vm.Close。
希望这会有所帮助。
答案 1 :(得分:0)
请参阅其他主题中的this answer以获取解决方案。