【发布时间】:2018-05-28 12:16:57
【问题描述】:
使用附加属性,我想在点击 Key.Up 或 Key.Down 时将文本框的值减小/增加该值。
我定义了以下属性:
public static readonly DependencyProperty SmallFloatIncrementProperty = DependencyProperty.RegisterAttached(
"SmallFloatIncrement",
typeof(double),
typeof(InputService),
new UIPropertyMetadata(0.1));
public static double GetSmallFloatIncrement(DependencyObject d)
{
return (double)d.GetValue(SmallFloatIncrementProperty);
}
public static void SetSmallFloatIncrement(DependencyObject d, double value)
{
d.SetValue(SmallFloatIncrementProperty, value);
}
我还在我的 TextBox 上注册了 PreviewKeyDown 并像这样处理它:
if(e.Key == Key.Up)
{
IncrementOrDecrementValue((DependencyObject)sender, true);
}
else if (e.Key == Key.Down)
{
IncrementOrDecrementValue((DependencyObject)sender, false);
}
...
private static void IncrementOrDecrementValue(DependencyObject sender, bool doIncrement)
{
if (sender is TextBox)
{
TextBox tb = (TextBox)sender;
var increment = GetSmallFloatIncrement((DependencyObject)sender);
var text = tb.Text;
double textBoxValue = 0.0;
if (!string.IsNullOrEmpty(text))
{
try{
textBoxValue = Convert.ToDouble(text, FormatProvider);
}
catch (FormatException) { }
}
tb.Text = Convert.ToString((doIncrement) ? textBoxValue + increment : textBoxValue - increment, FormatProvider);
ValidateResult(sender);
}
}
我在检索文本框的值时遇到了问题。例如,如果绑定属性为 1.234,但绑定中定义了 StringFormat = N1,则调用 tb.Text 提供 1.2 而不是整个值。但是我需要将原始值增加指定的数量(该值必须是增量的倍数)。有没有办法检索文本框的完整绑定值?
感谢您的帮助!
【问题讨论】:
标签: c# binding textbox attached-properties