在應用 Command 模式中,需要在View上點擊 一個按鈕,需要將當前窗體作為參數傳遞為 command
兩種方式傳遞當前窗體
1、通過窗體名稱(假設窗體名稱為 ThisWindow)
<ButtonCommand="CancelCommand
"CommandParameter="{Binding ElementName=ThisWindow}"/>
2、綁定到 RelativeSource
<ButtonCommand="
CancelCommand
"CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}}"/>
-------------------------------------------------------------------------------------------------------------------
以下是ViewModel中的 Command 代碼
private DelegateCommand<Window> _cancelCommand = null;
public DelegateCommand<Window> CancelCommand
{
get
{
if (_cancelCommand == null)
{
_cancelCommand = new DelegateCommand<Window>(Cancel);
}
return _cancelCommand;
}
}
void Cancel(Window window)
{
if (window != null)
{
window.DialogResult = false;
window.Close();
}
}
參考網址:http://stackoverflow.com/questions/3504332/passing-the-current-window-as-a-commandparameter