MAR
14
TextBox内でEnterキーが押下された時に、割り当てたCommandが実行されたりすると便利ですよね。ちょっと必要になったので添付ビヘイビアを利用して実装してみました。ちなみにKeyBindingも試しましたが、あれCommandプロパティが依存関係プロパティになっていないのでバインドが出来ないんですね…。不便。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using System.Windows.Controls;
using System.Windows;
namespace SharpLab.IKnow.ItemBankPane {
public class TextBoxBehavior {
#region Command
public static ICommand GetCommand(TextBox textBox) {
return (ICommand)textBox.GetValue(CommandProperty);
}
public static void SetCommand(
TextBox textBox, bool value) {
textBox.SetValue(CommandProperty, value);
}
public static readonly DependencyProperty CommandProperty =
DependencyProperty.RegisterAttached(
"Command",
typeof(ICommand),
typeof(TextBoxBehavior),
new UIPropertyMetadata(null, OnCommandPropertyChanged));
static void OnCommandPropertyChanged(DependencyObject depObj, DependencyPropertyChangedEventArgs e) {
TextBox textBox = depObj as TextBox;
if (textBox == null)
return;
if (e.NewValue is ICommand == false)
return;
ICommand command = (ICommand)e.NewValue;
textBox.KeyDown += new KeyEventHandler(OnTextBoxKeyDown);
}
static void OnTextBoxKeyDown(object sender, KeyEventArgs e) {
TextBox textBox = (TextBox)e.OriginalSource;
ICommand command = TextBoxBehavior.GetCommand(textBox);
if (e.Key == Key.Enter && command != null && command.CanExecute(TextBoxBehavior.GetCommandParameter(textBox))) {
command.Execute(TextBoxBehavior.GetCommandParameter(textBox));
}
}
#endregion
#region CommandParameter
public static object GetCommandParameter(TextBox textBox) {
return textBox.GetValue(CommandParameterProperty);
}
public static void SetCommandParameter(
TextBox textBox, object value) {
textBox.SetValue(CommandParameterProperty, value);
}
public static readonly DependencyProperty CommandParameterProperty =
DependencyProperty.RegisterAttached(
"CommandParameter",
typeof(object),
typeof(TextBoxBehavior),
new UIPropertyMetadata(null));
#endregion
}
}
利用する側はこんな感じ。スマート!
<TextBox v:TextBoxBehavior.Command="{Binding Path=StartSearchCommand}" />
Related Entries
Trackbacks : 2
- Trackback URL for this entry
- http://blog.sharplab.net/computer/cprograming/wpf/1862/trackback/
Listed below are links to weblogs that reference this entry
- ピンバック from M-V-VMパターンでsmart.fmの辞書アプリを書きなおしてみた - SharpLab. 09-04-10 12:10:16 JST
-
[...] 添付ビヘイビアでTextBoxにCommandを実装してみた – SharpLab.の添付ビヘイビアは上の検索ツールバーで、添付ビヘイビア試してみた – SharpLab.で紹介した添付ビヘイビアは検索結果を表示して [...]
- ピンバック from Expression Blend向けに、Behaviorを自作してみた。 - SharpLab. 09-04-24 21:39:39 JST
-
[...] Preview版では現在のところBehaviorはExpression Blendに付属しておらず、別途ダウンロードしてきて参照に加えることが必要ですが(Sample Silverlight 3 Behaviors(Silverlight)やMicrosoft Expression Community Gallery)、自分で書いたBehaviorを使うことももちろん可能です。 今回は試しにBehaviorを自分で書いてみました。お題は以前書いた添付ビヘイビアでTextBoxにCommandを実装してみた – SharpLab.の再実装。 [...]
添付ビヘイビア試してみた