WPF MVVM으로 Window View와 Model 분리가 되어 있을 때 OK, Cancel 버튼을 눌러 Window를 닫는 방법이다.
간단하게 Close Action을 이용해서 닫을 수도 있는데 DialogResult를 받아서 처리를 할 때는 아래와 같이 처리해서 사용을 했다.
https://learn.microsoft.com/en-us/dotnet/api/system.action-1?view=net-7.0
Action<T> Delegate (System)
Encapsulates a method that has a single parameter and does not return a value.
learn.microsoft.com
다른 방법도 많을 것이다. 아래 예제는 System에서 제공하는 delegate Action을 이용했다.
간단하게 View.xaml에 확인(OK), 취소(Cancel) 버튼을 만들었다.
<Grid Grid.Row="2">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="100"/>
</Grid.ColumnDefinitions>
<Button Grid.Column="1" Content="OK" Command="{Binding ConfirmCommand}"
Background="Green"/>
<Button Grid.Column="2" Content="Cancel" Command="{Binding CancelCommand}"
Background="Gray"/>
</Grid>
초록색 OK 버튼과 회색 Cancel 버튼을 만들고 Command를 추가했다.
아래는 Model 소스이다.
public class SampleWindowModel : INotifyPropertyChanged
{
public ICommand ConfirmCommand { get; set; }
public ICommand CancelCommand { get; set; }
public Action<bool> CloseAction { get; set; }
public SampleWindowModel()
{
ConfirmCommand = new CommandHandler(
(obj) =>
{
CloseAction(true);
});
CancelCommand = new CommandHandler(
(obj) =>
{
CloseAction(false);
});
}
}
ICommand로 확인, 취소 Commnad Handler를 만들고 DialogResult 값을 받기 위해 Action<bool>을 선언했다.
View.xaml.cs의 소스이다.
실제 Window를 닫기 위해서 이곳에 EventHandler를 통해 Close 함수를 호출하게 처리했다.
public partial class SampleWindow : Window
{
public SampleWindowModel vm = null;
public SampleWindow()
{
InitializeComponent();
vm = new SampleWindowModel();
this.DataContext = vm;
//CloseAction을 생성한다.
if (vm.CloseAction == null)
vm.CloseAction += new Action<bool>(OnCloseAction);
}
//Action이 호출되고 DialogResult값을 넣은 후 Close를 처리한다.
private void OnCloseAction(bool dialogResult)
{
this.DialogResult = dialogResult;
this.Close();
}
}
위와 같은 방식으로 간단하게 DialogResult 값을 받아 Window를 닫는다.
LIST
'WPF' 카테고리의 다른 글
WPF MVVM TextBlock Foreground Binding (0) | 2023.06.16 |
---|---|
C# UI Thread 에러 발생할 경우 (0) | 2023.02.13 |
WinForm안에 있는 WFP 창에서 owner를 지정하는 방법 (0) | 2023.02.08 |
Telerik RadRibbonView Example (리본바 메뉴 예제) (0) | 2022.01.19 |
Telerik Menu 추가 (0) | 2021.12.21 |