WPFのTextBoxは、デフォルトでフォーカスが失われたときにBindingに反映されます。
Enterキーの押下で反映させたいときってありますよね!
今回はBehaviorを使って、その動作を実装したいと思います。
Behaviorクラスを作成する
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Interactivity;
using System.Windows.Controls;
using System.Windows.Data;
namespace BannerCreator.Behaviors
{
/**
* Enterキー押下でTextBoxのBindingをUpdateするBehavior
**/
class TextBox_BindingUpdate_OnEnterKeyDownBehavior : Behavior
XAMLでTextBoxにBehaviorを紐づける
Behaviorクラスができたら、あとはTextBoxに紐づけるだけです。
…(省略)…
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:behaviors="clr-namespace:Jp.Artm.Behaviors"
…(省略)…
<TextBox Text="{Binding Value">
<i:Interaction.Behaviors>
<behaviors:TextBox_BindingUpdate_OnEnterKeyDownBehavior />
</i:Interaction.Behaviors>
</TextBox>
…(省略)…
これで、エンターキー押下時に変更が反映されるようになりました!