WPF 通過 CommandParameter 傳遞當前窗體到 ViewModel


在應用 Command 模式中,需要在View上點擊 一個按鈕,需要將當前窗體作為參數傳遞為 command


兩種方式傳遞當前窗體
1、通過窗體名稱(假設窗體名稱為 ThisWindow)

   <Button
Command="
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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM