我使用WPF和MVVM模式。我想从viewmodel关闭一个窗口。我尝试使用以前的一些问题的解决方案,但它没有用。
这是我的代码:
视图模型:
//Defining commands
public RelayCommand SaveAddBankCommand { get; private set; }
//Constructor
public AddBankVM()
{
//Initializing Commands
SaveAddBankCommand = new RelayCommand(SaveAddBank);
}
//Commands methods
public void SaveAddBank(object parameter)
{
new Banks().AddBank(this.BankName, _Status, System.Convert.ToDouble(Credit), this.Notes);
new Done("Bank has been added successfully.");
//here i want to close the window.
}
查看课程:
public partial class AddBankView : Window
{
public AddBankView()
{
InitializeComponent();
var addBankVM = new AddBankVM();
this.DataContext = addBankVM;
}
}
答案 0 :(得分:0)
确定。这是一种方法:
在视图模型中......
//Commands methods
public void SaveAddBank()
{
new Banks().AddBank(this.BankName, _Status, System.Convert.ToDouble(Credit), this.Notes);
new Done("Bank has been added successfully.");
//here i want to close the window.
CloseWindowEvent?.Invoke(this, EventArgs.Empty);
}
public event EventHandler CloseWindowEvent;
在初始化后面的代码中......
InitializeComponent();
DataContext = new AddBankVM();
(DataContext as AddBankVM).CloseWindowEvent += CommandBench_CloseWindowEvent;
最后代码中的事件处理程序......
private void CommandBench_CloseWindowEvent(object sender, EventArgs e)
{
Close();
}
概念上发生的事情是视图模型正在向窗口发送事件以关闭自身。
我怀疑MVVM风格的警察会遇到这种方法的一些问题。让我们看看我们是否收到他们的消息。
答案 1 :(得分:0)
最简单的方法是引入界面:
public interface IClosable
{
void Close();
}
然后,在代码隐藏中需要更改的唯一事情是指定窗口实现IClosable
:
public partial class MainWindow : Window, IClosable
{
public MainWindow()
{
InitializeComponent();
}
}
XAML:
<Button Width="50"
Height="20"
Command="{Binding CloseCommand}"
CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type Window}}}"
Content="Close" />
ViewModel:
#region Commands
public DelegateCommand<IClosable> CloseCommand => new DelegateCommand<IClosable>(Close, CanClose);
private bool CanClose(IClosable parameter)
{
return true;
}
private void Close(IClosable parameter)
{
var closable = parameter as IClosable;
if (closable != null)
{
closable.Close();
}
}
或者,您可以使用EventTigger,行为或附加行为,但它不那么简单,恕我直言。
答案 2 :(得分:0)
在此链接中,您将找到一个从viewmodel打开和关闭对话框的绝佳机制。 https://www.youtube.com/watch?v=OqKaV4d4PXg