如何解决使用WPF专注于验证错误
我有一个小型应用程序,其中有一个通过MVVM绑定到模型的文本框:
我的模特:
public class MyModel : INotifyPropertyChanged
{
private double _myValue = 0;
public event PropertyChangedEventHandler PropertyChanged;
public double MyValue
{
get => _myValue;
set
{
if(value != _myValue)
{
if (value == 4)
throw new InvalidOperationException();
_myValue = value;
OnPropertyChanged();
}
}
}
/// <summary>
/// Called when a property was changed.
/// </summary>
/// <param name="propertyName">Name of the affected property.</param>
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this,new PropertyChangedEventArgs(propertyName));
}
}
我的视图如下:
<Window x:Class="ValidationTests.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:ValidationTests"
mc:Ignorable="d"
Title="MainWindow" Height="201.696" Width="322.679">
<Window.Resources>
<Style TargetType="TextBox" BasedOn="{StaticResource {x:Type TextBox}}">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="True">
<Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self},Path=(Validation.Errors)[0].ErrorContent}" />
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBox Grid.Row="0" Text="{Binding MyValue,Mode=TwoWay,ValidatesOnExceptions=True}"
HorizontalAlignment="Center" Width="150" VerticalAlignment="Center"/>
<Button Grid.Row="1" HorizontalAlignment="Center" Width="100" VerticalAlignment="Center" Height="30" Content="Test"/>
</Grid>
</Window>
现在,当发生验证错误时,我想将重点放在文本框上。我该如何实现?这种风格有可能吗?
解决方法
如果要防止键盘焦点在TextBox
包含有效值之前丢失,可以使用附加行为或直接在视图中处理PreviewLostKeyboardFocus
事件:>
private void TextBox_PreviewLostKeyboardFocus(object sender,KeyboardFocusChangedEventArgs e) =>
e.Handled = Validation.GetHasError((TextBox)sender);
您还应该将UpdateSourceTrigger
设置为PropertyChanged
以在丢失焦点之前执行验证:
<TextBox Text="{Binding MyValue,UpdateSourceTrigger=PropertyChanged,ValidatesOnExceptions=True}"
HorizontalAlignment="Center" Width="150" VerticalAlignment="Center"
PreviewLostKeyboardFocus="TextBox_PreviewLostKeyboardFocus"/>
您不能使用Style
或其他方式在纯XAML中实现此功能。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。