命令可以不通過數據綁定進行配置。在某些情況下,可能希望直接在代碼隱藏文件中處理命令邏輯,而不是通過數據綁定。以下是一個完整的例子,展示了如何在不使用數據綁定的情況下實現命令。
### 1. 定義命令
首先,我們定義一個簡單的命令類,類似于之前的 `RelayCommand`。
using System;
using System.Windows.Input;public class RelayCommand : ICommand
{
? ? private readonly Action<object> _execute;
? ? private readonly Predicate<object> _canExecute;? ? public RelayCommand(Action<object> execute, Predicate<object> canExecute = null)
? ? {
? ? ? ? _execute = execute ?? throw new ArgumentNullException(nameof(execute));
? ? ? ? _canExecute = canExecute;
? ? }? ? public bool CanExecute(object parameter)
? ? {
? ? ? ? return _canExecute == null || _canExecute(parameter);
? ? }? ? public void Execute(object parameter)
? ? {
? ? ? ? _execute(parameter);
? ? }? ? public event EventHandler CanExecuteChanged
? ? {
? ? ? ? add { CommandManager.RequerySuggested += value; }
? ? ? ? remove { CommandManager.RequerySuggested -= value; }
? ? }
}
?
### 2. 創建視圖模型
接下來,我們創建一個視圖模型,其中包含一個命令屬性。
using System.Windows.Input;
using System.Windows.Controls;public class MainViewModel
{
? ? public ICommand ClearTextCommand { get; }? ? public MainViewModel()
? ? {
? ? ? ? ClearTextCommand = new RelayCommand(ClearText);
? ? }? ? private void ClearText(object parameter)
? ? {
? ? ? ? if (parameter is TextBox textBox)
? ? ? ? {
? ? ? ? ? ? textBox.Clear();
? ? ? ? }
? ? }
}
?
### 3. 配置 XAML
在 XAML 中,我們不使用數據綁定,而是直接在代碼隱藏文件中處理命令。
<Window x:Class="WpfApp.MainWindow"
? ? ? ? xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
? ? ? ? xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
? ? ? ? Title="MainWindow" Height="200" Width="300">
? ? <StackPanel>
? ? ? ? <TextBox Name="tbox" Margin="10" />
? ? ? ? <Button Name="clearButton" Content="Clear" Margin="10" />
? ? </StackPanel>
</Window>
?
### 4. 代碼隱藏文件
在代碼隱藏文件中,我們將命令直接附加到按鈕上。
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;namespace WpfApp
{
? ? public partial class MainWindow : Window
? ? {
? ? ? ? private readonly ICommand _clearTextCommand;? ? ? ? public MainWindow()
? ? ? ? {
? ? ? ? ? ? InitializeComponent();? ? ? ? ? ? // 創建視圖模型實例
? ? ? ? ? ? var viewModel = new MainViewModel();? ? ? ? ? ? // 獲取命令
? ? ? ? ? ? _clearTextCommand = viewModel.ClearTextCommand;? ? ? ? ? ? // 將命令附加到按鈕
? ? ? ? ? ? clearButton.Command = _clearTextCommand;
? ? ? ? ? ? clearButton.CommandParameter = tbox;
? ? ? ? }
? ? }
}
?
### 解釋
1. **RelayCommand**:這是一個簡單的命令實現,實現了 `ICommand` 接口。它包含兩個主要方法:`CanExecute` 和 `Execute`。
2. **MainViewModel**:這是視圖模型類,包含一個 `ClearTextCommand` 屬性,該屬性是一個 `RelayCommand` 實例。`ClearText` 方法用于清空文本框的內容。
3. **XAML**:在 XAML 中,我們沒有使用數據綁定,而是直接在代碼隱藏文件中處理命令。
4. **代碼隱藏文件**:在代碼隱藏文件中,我們創建了視圖模型實例,獲取了命令,并將命令附加到按鈕上。
通過這種方式,我們實現了在不使用數據綁定的情況下處理命令邏輯。