gpt4 book ai didi

c# - 我可以绑定(bind)到实用程序类吗?

转载 作者:太空狗 更新时间:2023-10-30 01:34:48 24 4
gpt4 key购买 nike

我有一个通用类,其中填充了通用函数,如下所示,用于解析文本框:

public static void DoubleParse_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Decimal)
{
var textBox = sender as TextBox;
if (textBox != null)
textBox.Text += Convert.ToChar(CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator);
}
else
{
e.Handled = (e.Key >= Key.D0 && e.Key <= Key.D9) ||
(e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) ||
e.Key == Key.Back || e.Key == Key.Delete ||
e.Key == Key.Left || e.Key == Key.Right || e.Key == Key.Unknown;
}
}

我想我可以在我的页面的任何地方使用它作为 TextBox 按键事件的单一来源。 WP8 中 MVVM 实现的新手,好奇是否有实现此目的的方法?

本着 MVVM 的精神(虽然我不是纯粹主义者),我知道它不需要专门在 View 模型中,但我仍然希望它集中。

快速说明:

  • 该类不是静态的,我知道我不能直接在 xaml 中使用它。
  • 我想使该类成为某种 StaticResource 并引用 xaml 中的函数。但这似乎不起作用。
  • 我目前只是在代码隐藏中使用传递函数,并将发送者传递给静态函数。

最佳答案

你想要一个附加行为。

public static class TextBoxBehavior
{
public static bool GetAllowOnlyDecimalInput(TextBox texbox)
{
return (bool)texbox.GetValue(AllowOnlyDecimalInputProperty);
}

public static void SetAllowOnlyDecimalInput(
TextBox texbox, bool value)
{
texbox.SetValue(AllowOnlyDecimalInputProperty, value);
}

public static readonly DependencyProperty AllowOnlyDecimalInputProperty =
DependencyProperty.RegisterAttached(
"AllowOnlyDecimalInput",
typeof(bool),
typeof(TextBox),
new PropertyMetadata(false, OnAllowOnlyDecimalInputChanged));

static void OnAllowOnlyDecimalInputChanged(
DependencyObject depObj, DependencyPropertyChangedEventArgs e)
{
TextBox item = depObj as TextBox;
if (item == null)
return;

if (e.NewValue is bool == false)
return;

if ((bool)e.NewValue)
item.KeyDown += OnTextBoxDoubleParse_KeyDown;
else
item.KeyDown -= OnTextBoxDoubleParse_KeyDown;
}

static void OnTextBoxDoubleParse_KeyDown(object sender, KeyEventArgs e)
{
if (!Object.ReferenceEquals(sender, e.OriginalSource))
return;

TextBox item = e.OriginalSource as TextBox;
if (item != null) {
if (e.Key == Key.Decimal)
{
var textBox = sender as TextBox;
if (textBox != null)
textBox.Text += Convert.ToChar(CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator);
}
else
{
e.Handled = (e.Key >= Key.D0 && e.Key <= Key.D9) ||
(e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) ||
e.Key == Key.Back || e.Key == Key.Delete ||
e.Key == Key.Left || e.Key == Key.Right || e.Key == Key.Unknown;
}
}
}

#endregion // AllowOnlyDecimalInput
}

在 XAML 中使用它

<TextBox my:TextBoxBehavior.AllowOnlyDecimalInput="True" />

您还可以在 WPF 样式中设置它,并让它在所有或许多控件中重复使用,而不是每次都手动添加属性。

关于c# - 我可以绑定(bind)到实用程序类吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28978446/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com