我的问题很简单我在WPF中有一个文本框,你可以输入一个数字。当我按下特定键时,我想要三件事:
我已经制作了3个附加属性,但它仅适用于键输入。
<TextBox Margin="5,0" hlp:TextboxBehaviors.KeyToValid="Enter" hlp:Decrease.KeyToDecrease="Down" hlp:Increase.KeyToIncrease="Up" Text="{Binding Target, Mode=TwoWay, UpdateSourceTrigger=Explicit, Converter={StaticResource kiloConverter}, ValidatesOnNotifyDataErrors=True, ValidatesOnExceptions=True}" />
班级代码:
public static class Decrease
{
private static Key TriggeredKey = Key.Down;
public static Key GetKeyToDecrease(DependencyObject obj)
{
return (Key)obj.GetValue(KeyToDecreaseProperty);
}
/// <summary>
/// Sert uniquement à s'attacher à la TextBox (une seule fois à l'init de l'interface)
/// </summary>
public static void SetKeyToDecrease(DependencyObject obj, Key value)
{
var tb = obj as TextBox;
if (tb != null)
tb.KeyDown += OnKeyDown;
}
/// <summary>
/// Evenement classique
/// </summary>
private static void OnKeyDown(object sender, KeyEventArgs e)
{
var tbCurrent = sender as TextBox;
int selectedpos;
if (tbCurrent != null && e.Key == TriggeredKey)
{
if (tbCurrent.SelectionStart > 0)
{
if (!tbCurrent.Text.Contains("."))
{
int exp = tbCurrent.Text.Length - tbCurrent.SelectionStart;
tbCurrent.Text = (Convert.ToDouble(tbCurrent.Text) - Math.Pow(10, exp)).ToString();
selectedpos = tbCurrent.Text.Length - exp;
}
else
{
int exp;
if (tbCurrent.SelectionStart > tbCurrent.Text.IndexOf('.') + 1)
{
exp = tbCurrent.Text.IndexOf('.') - tbCurrent.SelectionStart + 1;
}
else if (tbCurrent.SelectionStart < tbCurrent.Text.IndexOf('.') + 1)
{
exp = tbCurrent.Text.IndexOf('.') - tbCurrent.SelectionStart;
}
else
{
return;
}
tbCurrent.Text = (Convert.ToDouble(tbCurrent.Text) - Math.Pow(10, exp)).ToString("0.00");
if (exp < 0)
{
selectedpos = tbCurrent.Text.IndexOf('.') - exp + 1;
}
else
{
if (tbCurrent.Text.IndexOf('.') - exp < 0)
{
selectedpos = 0;
}
else
{
selectedpos = tbCurrent.Text.IndexOf('.') - exp;
}
}
}
BindingExpression binding = tbCurrent.GetBindingExpression(TextBox.TextProperty);
if (binding != null)
{
binding.UpdateSource();
}
tbCurrent.SelectionLength = 0;
if (selectedpos >= 0)
{
tbCurrent.SelectionStart = selectedpos;
}
else
{
tbCurrent.SelectionStart = 0;
}
}
}
}
// Using a DependencyProperty as the backing store for KeyToValid. This enables animation, styling, binding, etc...
public static readonly DependencyProperty KeyToDecreaseProperty =
DependencyProperty.RegisterAttached("KeyToDecrease", typeof(Key), typeof(TextBox), new PropertyMetadata(TriggeredKey));
}
这是减少附加行为的代码,另外两个是以相同的方式设计的。
减少和增加不会触发事件!输入确实......
答案 0 :(得分:0)
减少和增加不会触发事件!输入确实......
处理预览 KeyDown事件:
public static void SetKeyToDecrease(DependencyObject obj, Key value)
{
var tb = obj as TextBox;
if (tb != null)
tb.PreviewKeyDown += OnKeyDown;
}
TextBox
控件处理和&#34;吞下&#34;某些按键本身。这就是KeyDown
事件未在您的行为中被解雇的原因。