gpt4 book ai didi

c# - 基本 WPF 验证

转载 作者:行者123 更新时间:2023-11-30 22:32:13 25 4
gpt4 key购买 nike

我刚刚开始使用 WPF,尤其是验证 TextBox 中的条目。

这是我的 XAML:-

<Window x:Class="WpfTestBinding.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow"
Height="350"
Width="525"
Loaded="OnInit">
<Grid>
<Button Content="OK" Height="23" HorizontalAlignment="Left" Margin="235,164,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="206,108,0,0"
Name="textBox1" VerticalAlignment="Top" Width="120" >
<TextBox.Text>
<Binding Path="Description" UpdateSourceTrigger="LostFocus" >
<Binding.ValidationRules>
<ExceptionValidationRule />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
</Grid>
</Window>

这是我的绑定(bind)代码:-

namespace WpfTestBinding
{
class MyDataItem
{
private String _description;
public String Description
{
get { return _description; }
set
{
_description = value;

Debug.WriteLine("Setting description ="+value);

if (String.IsNullOrEmpty( value ))
{
throw new ApplicationException("Description is mandatory.");
}
}
}
}
}

这是我的支持代码:-

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows;

namespace WpfTestBinding
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

private void OnInit(object sender, RoutedEventArgs e)
{
this.DataContext = new MyDataItem();
}

private void button1_Click(object sender, RoutedEventArgs e)
{
Debug.WriteLine("Button clicked.");
}
}
}

首先,如果我选择文本框并从中选择标签,什么也没有发生,我希望抛出“Description is Mandatory”异常?如果我然后在文本框中输入内容并立即删除它,然后按 Tab 键会抛出异常??然后未处理此异常,我收到未处理的异常错误。

最佳答案

首先,您不会对异常进行验证,异常旨在指示程序流程中发生了异常情况并提供错误。

参见 Data Validation in 3.5清楚地解释 WPF 验证的工作原理

其次,当您简单地进入和离开 TextBox 时看不到它的原因是您实际上并没有更新绑定(bind)属性的值。当您输入一个值然后将其删除时,您正在更新该值。

关于c# - 基本 WPF 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8839149/

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