下面是我用我一般CommandBase什麼從ICommand的繼承:
/// <summary>
/// Base class for all Commands.
/// </summary>
public abstract class CommandBase : ICommand
{
/// <summary>
/// Defines the method that determines whether the command can execute in its current
/// state.
/// </summary>
/// <param name="parameter">Data used by the command. If the command does not require data
/// to be passed, this object can be set to null.</param>
/// <returns>
/// true if this command can be executed; otherwise, false.
/// </returns>
public virtual bool CanExecute(object parameter)
{
return true;
}
/// <summary>
/// Defines the method to be called when the command is invoked.
/// </summary>
/// <param name="parameter">Data used by the command. If the command does not require data
/// to be passed, this object can be set to null.</param>
public abstract void Execute(object parameter);
/// <summary>
/// Occurs when changes occur that affect whether or not the command should execute.
/// </summary>
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
}
這裏是我建議的步驟如下:
- 在你的視圖模型指定的字符串屬性(MyTextProperty)處理文本框文本。
- 創建命令(MyTextChangedCommand),其從上述CommandBase即把你的視圖模型類型(YourViewModelType)的參數繼承。然後通過訪問傳遞給您的命令的ViewModel直接與您的MyTextProperty進行交互,而不是嘗試使用CommandParameters。
- 創建類型MyTextChangedCommand在您的視圖模型的屬性,並確保實例它在你的視圖模型的構造。
對於您的命令在WPF結合我會用Blend Interactivity for WPF v4.0
這裏是你將如何實現你的文本框(假設你參考Microsoft.Expression.Interactions爲「我」:
<TextBlock Text="{Binding Path=MyTextProperty">
<i:Interaction.Triggers>
<i:EventTrigger EventName="LostFocus">
<i:InvokeCommandAction
Command="{Binding Path=MyTextChangedCommand}"
CommandParameter="Whatever" />
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBlock>
爲了您的你可以使用MultiBinding參數 – XAMlMAX
如何使用CommandParamter來傳入TextBox?或者,你可以獲得MenuItem附加到的ContextMenu,並檢查它是否是PlacementTarget來獲取它附加的項目 – Rachel