C# WPF-Tips-CommandをTextBoxのトリガーに
TextBoxのCommand実行はButtonとは少し違います。
一筋縄では行かないです・・・
ちなみにButtonのCommandは下記です。
dasuma20.hatenablog.com
BaseICommand.csの作成
namespace InputName.ViewModel { public class BaseICommand : ICommand { public delegate void DelegateAction(); private DelegateAction _delegateAction; public event EventHandler CanExecuteChanged; public BaseICommand(Action action) { _delegateAction = new DelegateAction(action); } public bool CanExecute(object parameter) { return true; } public void Execute(object parameter) { _delegateAction(); } } }
ICommandをそのまま使うと使いにくいので、
ICommandを継承した基底クラスを作成しましょう。
ViewModelにCommandを追加
public ICommand SetNameCommand { get { return new BaseICommand(SetNameCallBack); } } private void SetNameCallBack() { Name.SetName(); }
ICommandを引数にして先程作成した"BaseICommand"クラスを作成して
引数にCallBackメソッドを渡します。
そこで、実行したい処理を記載します。
XAMLの修正
1.behaviorsを読み込み
xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
上の部分に書くと下で使えます。
csファイルで言うと"using"みたいなものです。
2.Interactionに追加
<TextBox Text="{Binding Name.FirstName}" Width="100"> <i:Interaction.Triggers> <i:EventTrigger EventName="LostFocus"> <i:InvokeCommandAction Command="{Binding SetNameCommand}"/> </i:EventTrigger> </i:Interaction.Triggers> </TextBox>
LostFocusはフォーカスが外れた時にCommandが発動されます。
他にも色々あります。
値が変わったらなど。