MVVMを使用しているので(バリューコンバーターを介してこれを行うことができます)、ほとんど好奇心からこれを実行しました-これは非常にうまく機能しているようですが、インスタンスを使用しているため、現在、コントロールごとにコンバーターのインスタンスが必要です最後の既知の適切な16進値をキャッシュする変数-検証と組み合わせて使用して改善できると確信しています。
更新
さて、これはうまくいくようです(ish)-1-9とAFのみを許可します、奇妙な結果を引き起こしていたのでテキストボックスの選択を無効にする必要がありました-カーソルを制御するために添付の動作を使用しました、より良い方法があるかもしれませんこれを行うが、私は確かに方法がわからない...
削除動作は、要求どおりに機能します(ペアの最後で削除しても、何も実行されません)。
遊びましょう:)
アップデート2
テキスト選択で機能するようにいくつかの変更を加えました。
意見
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.Resources>
<local:HexStringConverter x:Key="HexConverter"></local:HexStringConverter>
</Grid.Resources>
<StackPanel>
<TextBox local:TextBoxBehaviour.KeepCursorPosition="true" VerticalAlignment="Center" Width="200" HorizontalAlignment="Center" Text="{Binding HexValue,Mode=TwoWay,Converter={StaticResource HexConverter},UpdateSourceTrigger=PropertyChanged}"></TextBox>
</StackPanel>
</Grid>
背後にあるコードを表示
public partial class MainWindow : Window
{
public MainWindow()
{
this.DataContext = new MyViewModel();
InitializeComponent();
}
ViewModel
public class MyViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
private string hexValue;
public string HexValue
{
get
{
return hexValue;
}
set
{
hexValue = value;
OnPropertyChanged("HexValue");
}
}
}
16進コンバーター
public class HexStringConverter : IValueConverter
{
private string lastValidValue;
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string ret = null;
if (value != null && value is string)
{
var valueAsString = (string)value;
var parts = valueAsString.ToCharArray();
var formatted = parts.Select((p,i)=>(++i)%2==0 ? String.Concat(p.ToString()," ") : p.ToString());
ret = String.Join(String.Empty,formatted).Trim();
}
return ret;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
object ret = null;
if (value != null && value is string)
{
var valueAsString = ((string)value).Replace(" ",String.Empty).ToUpper();
ret = lastValidValue = IsHex(valueAsString) ? valueAsString : lastValidValue;
}
return ret;
}
private bool IsHex(string text)
{
var reg = new System.Text.RegularExpressions.Regex("^[0-9A-Fa-f]*$");
return reg.IsMatch(text);
}
}
テキストボックスの動作
public static class TextBoxBehaviour
{
public static bool GetKeepCursorPosition(DependencyObject obj)
{
return (bool)obj.GetValue(KeepCursorPositionProperty);
}
public static void SetKeepCursorPosition(DependencyObject obj, bool value)
{
obj.SetValue(KeepCursorPositionProperty, value);
}
// Using a DependencyProperty as the backing store for KeepCursorPosition. This enables animation, styling, binding, etc...
public static readonly DependencyProperty KeepCursorPositionProperty =
DependencyProperty.RegisterAttached("KeepCursorPosition", typeof(bool), typeof(TextBoxBehaviour), new UIPropertyMetadata(false, KeepCursorPosition));
public static int GetPreviousCaretIndex(DependencyObject obj)
{
return (int)obj.GetValue(PreviousCaretIndexProperty);
}
public static void SetPreviousCaretIndex(DependencyObject obj, int value)
{
obj.SetValue(PreviousCaretIndexProperty, value);
}
// Using a DependencyProperty as the backing store for PreviousCaretIndex. This enables animation, styling, binding, etc...
public static readonly DependencyProperty PreviousCaretIndexProperty =
DependencyProperty.RegisterAttached("PreviousCaretIndex", typeof(int), typeof(TextBoxBehaviour), new UIPropertyMetadata(0));
public static string GetPreviousTextValue(DependencyObject obj)
{
return (string)obj.GetValue(PreviousTextValueProperty);
}
public static void SetPreviousTextValue(DependencyObject obj, string value)
{
obj.SetValue(PreviousTextValueProperty, value);
}
// Using a DependencyProperty as the backing store for PreviousTextValue. This enables animation, styling, binding, etc...
public static readonly DependencyProperty PreviousTextValueProperty =
DependencyProperty.RegisterAttached("PreviousTextValue", typeof(string), typeof(TextBoxBehaviour), new UIPropertyMetadata(null));
private static void KeepCursorPosition(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
var textBox = sender as TextBox;
if (textBox != null)
{
textBox.PreviewKeyDown += new System.Windows.Input.KeyEventHandler(textBox_PreviewKeyDown);
textBox.TextChanged += new TextChangedEventHandler(textBox_TextChanged);
textBox.Unloaded += new RoutedEventHandler(textBox_Unloaded);
}
else
{
throw new ArgumentException("KeepCursorPosition only available for textboxes");
}
}
static void textBox_Unloaded(object sender, RoutedEventArgs e)
{
var textBox = sender as TextBox;
textBox.PreviewKeyDown -= new System.Windows.Input.KeyEventHandler(textBox_PreviewKeyDown);
textBox.TextChanged -= new TextChangedEventHandler(textBox_TextChanged);
textBox.Unloaded -= new RoutedEventHandler(textBox_Unloaded);
}
static void textBox_TextChanged(object sender, TextChangedEventArgs e)
{
//For some reason our e.Changes only ever contains 1 change of 1 character even if our
//converter converts it to 2 chars with the additional space - hmmm?
var textBox = sender as TextBox;
var previousIndex = GetPreviousCaretIndex(textBox);
var previousText = GetPreviousTextValue(textBox);
var previousLen = !String.IsNullOrEmpty(previousText) ? previousText.Length : 0;
var currentLen = textBox.Text.Length;
var change = (currentLen - previousLen);
var newCharIndex = Math.Max(1, (previousIndex + change));
Debug.WriteLine("Text Changed Previous Caret Pos : {0}", previousIndex);
Debug.WriteLine("Text Changed Change : {0}", change);
Debug.WriteLine("Text Changed New Caret Pos : {0}", newCharIndex);
textBox.CaretIndex = Math.Max(newCharIndex, previousIndex);
SetPreviousCaretIndex(textBox, textBox.CaretIndex);
SetPreviousTextValue(textBox, textBox.Text);
}
static void textBox_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
var textBox = sender as TextBox;
Debug.WriteLine("Key Preview Caret Pos : {0}", textBox.CaretIndex);
Debug.WriteLine("------------------------");
SetPreviousCaretIndex(textBox, textBox.CaretIndex);
SetPreviousTextValue(textBox, textBox.Text);
}
}