Как закрыть окно (XAML) из ViewModelHelper в C #? - PullRequest
0 голосов
/ 21 сентября 2019

Я хочу выполнить метод метода onCloseCommand (отправитель объекта) в методе onTimeOutCommand (), но я не знаю, как передать обязательный параметр, передаваемый этим методом?

Пожалуйста, обратитесь к следующему фрагменту кода.

Код XAML:

x:name = "Recorder" // window name define in the begining


//below command is used for closing this window when user clicks on close button

Command = "{Binding CloseCommand}" CommandParameter="{Binding ElementName=Recorder}"

Код ViewModel:

CloseCommand = new DelegateCommand<object>(helper.onCloseCommand);

Код ViewModelHelper:

Note: onCloseCommand() methodis working as per expectation
onCloseCommand(object sender) // This method is used for closing the window on clicking on close button of this window
{
    if(sender != null && send is window)
    {
         (sender as window).close();
    }
}

onTimeOutCommand() // this method is used for closing the window (the window which is passed in onCloseCommand() method) automaticlly after time out of the recording
{
      how to perform onCloseCommand() from this method?
}

1 Ответ

0 голосов
/ 21 сентября 2019

как выполнить onCloseCommand () из этого метода?

У вас есть несколько опций, например, создать прикрепленное поведение, которое закрывает окно после определенного времени ожидания, и эффективно использовать его из xamlоставляя модель представления вне уравнения.

Я предлагаю вам отреагировать на событие Loaded окна в модели представления и сохранить окно и использовать его позже, когда вы захотите закрыть его.

<Window x:Class="MyWindow"
        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:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
        mc:Ignorable="d">
     <i:Interaction.Triggers>
         <i:EventTrigger EventName="Loaded">
             <i:InvokeCommandAction Command="{Binding WindowLoadedCommand}" CommandParameter="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}}"/>
         </i:EventTrigger>
     </i:Interaction.Triggers>

     <!--- the rest of the window here --->
</Window>

Но позвольте мне отослать вас к этому ответу для более удобного для mvvm и, что более важно, тестируемого способа закрытия окна из модели представления:

Makeокно реализует интерфейс и сохраняет и использует его (не полный Window)!

Таким образом, WindowLoadedCommand имеет тип DelegateCommand<IClosable> и сохраняет IClosable в поле.Когда истечет время ожидания, извлеките IClosable из поля и позвоните Close.

...