我想要一种简单的方法来确保类中的某些属性包含值和/或在一个范围内(即:长度不超过 50 个字符)。我使用了关于如何验证类属性的问题和答案?不幸的是,我无法让它工作。
为了测试它,我使用 C# 创建了一个非常简单的 WinForm 示例。即使我做的一切都一样,但当我应用不正确的值(即:将年龄设置为高于允许的限制)时,它永远不会引发验证异常。
有人可以解释为什么它不抛出异常吗?就好像这个类不知道它应该使用必需的属性。
表格1.cs
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.ComponentModel.DataAnnotations;
namespace RequiredFieldsInClassExample {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void btnTest_Click(object sender, EventArgs e) {
try {
lstStatus.Items.Clear();
lstStatus.Items.Add("Creating list of people");
List<Person> CollectionOfPeople = new List<Person>();
lstStatus.Items.Add("Creating a good person");
Person Jeff = new Person();
Jeff.Age = 33;
Jeff.Firstname = "Jeff";
Jeff.Lastname = "Jefferson";
Jeff.GroupCode = "JJJ";
CollectionOfPeople.Add(Jeff);
lstStatus.Items.Add("Creating a …Run Code Online (Sandbox Code Playgroud) 我在 UWP 应用程序的设置页面上有一个 ToggleSwitch,我注意到 ToggleSwitch 的标题文本无法包装它。当我在电话模拟器中测试该应用程序时,Header 会直接离开页面。知道如何像使用 TextBlock 一样使文本换行吗?
<StackPanel Margin="10,0">
<ToggleSwitch Name="toggleOne" Header="Check this on if you want the app to automatically trigger the zombie apocalypse" Margin="10" />
<ToggleSwitch Name="toggleTwo" Header="Short Sample Text" Margin="10" />
</StackPanel>
Run Code Online (Sandbox Code Playgroud)