c# - 如何使用数据注释为 WPF 中的文本框创建输入验证?

标签 c# wpf xaml

我想在文本框中输入空值时为用户显示输入验证,有没有一种简单的方法可以使用数据注释为 WPF 执行此操作? 我是 WPF 和 C# 的新手,如果有人能为我解释一下,我将不胜感激。 我想要这样或类似的东西: enter image description here

最佳答案

使用 ValidationRule在您的绑定(bind)上可以获得您想要的效果,您可以在 XAML 中以声明方式指定它们,并且您可以根据需要将它们自定义和复杂化:

<TextBox    x:Name="FilePathTextBox" Width="350" Margin="5,0,0,0">
    <TextBox.Text>
        <Binding Path="FilePath" UpdateSourceTrigger="PropertyChanged" >
            <Binding.ValidationRules>
                <this:FilePathValidationRule />
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</TextBox>

将产生这个:

enter image description here

引用我的博文 Taking data binding, validation and MVVM to the next level

关于c# - 如何使用数据注释为 WPF 中的文本框创建输入验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38349486/

相关文章:

c# - Xamarin Android 调试错误

c# - 顶级任务导致错误 "The current SynchronizationContext may not be used as a TaskScheduler."

c# - 了解 XAML/WPF 中的样式和模板

c# - 在 WPF C# 中使用数据绑定(bind)更改组合框的选定索引

wpf - WPF 中基于数据的模板选择

c# - C#创建一个对象时,会在内存中创建一个类中的多少个方法?

c# - 使用 Fluent Assertions 库的多个断言

c# - Log4Net 错误 : "Failed to find configuration section log4net"

c# - WPF ListView GridView 单元格样式和绑定(bind)

xaml - 防止系统 FontSize 更改影响 Xamarin 应用程序中的大小