2013-10-02 57 views
0

我有一个WPF窗口的datacontext被实例化全光照XAML关闭窗口XAML从视图模型

<Window 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:ViewModels="clr-namespace:Contratos.ViewModels" x:Class="Contratos.Views.TipoAsociadoAcopio" 
    xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" 
    xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.WPF45" 
    xmlns:l="clr-namespace:Recursos;assembly=Recursos" 
    xmlns:controls="clr-namespace:Recursos.Controls;assembly=Recursos" 
    xmlns:resources="clr-namespace:ModelSeguridad.Resources;assembly=ModelSeguridad" 
    Title="{x:Static resources:Labels.CONTRATO_TipoContratoAcopio}" Height="Auto" Width="Auto"> 
<Window.Resources> 
    <CollectionViewSource x:Key="ListaItems" Source="{Binding ListaItems}"/> 
    <ViewModels:TipoAsociadoVM x:Key="ViewDataContext"/>  
</Window.Resources> 
<Grid> 
    <StackPanel> 
     <Button Command="{Binding _ICommandExit}" CommandParameter="{W H A T H E R E}" /> 
    </StackPanel> 
</Grid> 

我需要的时候上的退出按钮,用户点击,我的问题是如何关闭这个窗口如果使用XAML实例化,我可以将窗口引用发送给viewmodel吗?

我想维护MVVM模式,那是因为我没有任何代码在mi codebehind上。

+1

就我个人而言,我认为在后面的代码中放置按钮点击处理程序是完全可以接受的,而不是绑定到命令。关闭窗口纯粹是一个UI任务,所以你仍然保持视图逻辑解耦。 – zmb

+0

@zmb Tks,是的,你有理由。但是我喜欢为我的所有Windows自动执行此任务,并且在用户关闭窗口时必须记录一些日志。 –

+0

这不是MVVM。只需关闭用户界面中的窗口即可。 – Will

回答

0

ViewModel不应该有窗口引用,并且命令不应该在其params中发送它。如果你只是想关闭你的窗口,你可以在后面的代码中执行它,或者如果你仍然想要在命令中执行它,那么你可以在命令处理程序中找到你的窗口引用Application.Current.Windows并关闭它。

0

虽然我同意这些家伙们说可以在MVVM中使用代码,但我有一个可能的解决方案。

首先,申报您的WindowName财产。然后,你可以从任何地方像这样访问该窗口:

Window window = Application.Current.Windows.OfType<Window>().Where(w => w.Name == 
"WindowName").FirstOrDefault(); 
if (window != null) window.Close(); 

我也同意,视图模型是做到这一点的地方,但它是你的代码。 :)

+0

Tks for your hel,但是如果你有更多的同一类型的窗口, –

+0

给他们不同的名字,并确保你保存他们的记录。当你想关闭时,只需在我的示例代码中用'WindowName'替换相关'Window'的名称,它就会找到并关闭'Window'。 – Sheridan

0
<Button Command="{Binding _ICommandExit}" 
     CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=Window}}"/>