왜이 동작을 포함하도록 연결된 속성을 만들지 않습니까? 이런 식으로 뭔가 :
public class TextBoxHelper
{
public static bool GetRestrictToNumerical(DependencyObject obj)
{
return (bool)obj.GetValue(RestrictToNumericalProperty);
}
public static void SetRestrictToNumerical(DependencyObject obj, bool value)
{
obj.SetValue(RestrictToNumericalProperty, value);
}
public static readonly DependencyProperty RestrictToNumericalProperty =
DependencyProperty.RegisterAttached("RestrictToNumerical", typeof(bool), typeof(TextBoxHelper), new PropertyMetadata(false, onRestrictToNumericalChanged));
private static void onRestrictToNumericalChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var tb = d as TextBox;
if (tb == null)
return;
if ((bool)e.NewValue)
tb.KeyDown += tb_KeyDown;
else
tb.KeyDown -= tb_KeyDown;
}
static void tb_KeyDown(object sender, Windows.UI.Xaml.Input.KeyRoutedEventArgs e)
{
e.Handled = e.Key < VirtualKey.Number0 || e.Key > VirtualKey.Number9;
}
}
당신은이처럼 XAML에서 사용할 것 :
<Page
x:Class="App4.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App4"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<TextBox VerticalAlignment="Center" local:TextBoxHelper.RestrictToNumerical="True" InputScope="Number" />
</Grid>
</Page>
This은, 내 의견으로는, 모든 입력 검증을위한 깨끗한 MVVM 접근 방식입니다 당신이 수도 해야 할 일. 당신의 간단한 질문에 대해서는 과잉이라고 할지라도보다 정교한 검증을하는 것이 좋습니다.