本節使用MVVM模式進行演示
MyCommand為自定義的命令類,程式碼如下:
public class MyComand : ICommand { private readonly Action<object> _action; private readonly Func<object,bool>? _func; public MyComand(Action<object> action, Func<object, bool> func) { _action = action; _func = func; } /// <summary> /// 事件處理器 /// </summary> public event EventHandler? CanExecuteChanged; /// <summary> /// 能否執行 true/false /// </summary> /// <param name="parameter"></param> /// <returns></returns> /// <exception cref="NotImplementedException"></exception> public bool CanExecute(object? parameter) { return _func(parameter); } /// <summary> /// 執行命令 /// </summary> /// <param name="parameter"></param> /// <exception cref="NotImplementedException"></exception> public void Execute(object? parameter) { _action(parameter); } }
按照MVVM模式在專案下定義兩個資料夾,Views、ViewModels。在Views中建立一個wpf窗體Demo1,在ViewModels中新增一個類Demo1ViewModel
在Demo1的頁面中注意新增,prism的相關引用,以及設定Command命令
<Window x:Class="WpfProject_Study.Views.Demo1" 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:local="clr-namespace:WpfProject_Study.Views" xmlns:prism="http://prismlibrary.com/" prism:ViewModelLocator.AutoWireViewModel="True" mc:Ignorable="d" Title="Demo1" Height="450" Width="800"> <Grid> <Button Content="點選按鈕出現提示" Width="100" Height="30" Command="{Binding ShowDialogCommand}"></Button> </Grid> </Window>
在DemoViewModel類中,實現自定義命令ShowDialogCommand。注意Command命令必須是public型別,且必須是屬性而不是欄位
public class Demo1ViewModel : BindableBase { public MyComand ShowDialogCommand { get; set; } public Demo1ViewModel() { ShowDialogCommand = new MyComand(ShowDialog, myCanExec); } private void ShowDialog(object pramparameter) { MessageBox.Show("使用命令開啟彈窗"); } private bool isCanExec = true; private bool myCanExec(object pramparameter) { return isCanExec; } }
重新生成專案,點選按鈕,即可實現效果。