我用DataGrid创建了一个简单的WPF应用程序,其中wchich与Employee对象绑定到了List:
public class Employee
{
private string _name;
public int Id { get; set; }
public string Name
{
get { return _name; }
set
{
if (String.IsNullOrEmpty(value))
throw new ApplicationException("Name cannot be empty. Please specify the name.");
_name = value;
}
}
如您所见,我想阻止创建没有设置Name属性的Employees。
因此,我制定了一个验证规则:
public class StringValidationRule : ValidationRule
{
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
string str = value as string;
if (String.IsNullOrEmpty(str))
return new ValidationResult(false, "This field cannot be empty");
else
return new ValidationResult(true, null);
}
}
名称的XAML字段如下:
<DataGridTextColumn Header="Name"
ElementStyle="{StaticResource datagridElStyle}" >
<DataGridTextColumn.Binding>
<Binding Path="Name" Mode="TwoWay" NotifyOnValidationError="True" ValidatesOnExceptions="True" UpdateSourceTrigger="PropertyChanged" >
<Binding.ValidationRules>
<emp:StringValidationRule/>
</Binding.ValidationRules>
</Binding>
</DataGridTextColumn.Binding>
</DataGridTextColumn>
如果我尝试在DataGrid中编辑现有员工行的名称并将其设置为空字符串,则datagrid将标记错误的字段,并且不允许保存行。这是正确的行为。
但是,如果我创建一个新行并按键盘上的Enter键,则会使用_name设置为NULL创建此新行,并且验证不起作用。我猜这是因为DataGrid为新的行对象调用默认构造函数并将_name字段设置为NULL。
验证新行的正确方法是什么?
参考方案
您可以在IDataError
对象上实现Employee
。 here上有一个不错的页面。
我有一个选项卡控件,该控件动态地填充有包含各种大小的用户控件的选项卡。打开选项卡后,我希望窗口自动调整大小,使其在活动用户控件下有意义。有一种干净的方法可以做到这一点吗?我正在使用标准的mvvm模式。 参考方案 在Window类上使用SizeToContent属性。<Window x:Class="WpfApplication1.MainWi…
WPF WebBrowser甚至使用ObjectForScripting在单独的线程上锁定UI - javascript在与WPF Web浏览器控件绑定的ObjectForScripting上调用方法时,网页UI锁定会出现一个奇怪的问题。进一步的研究使我们意识到整个UI(包括WPF应用程序而不是WebBrowser)都已锁定。使用的技术是带有Caliburn.Micro和Autofac的WPF。我在COM可见类上使用方法来推送到Caliburn.Micro提供的事件聚合器。进…
C#WPF-如何始终从文本框中获取当前文本? - c#我在FileWindow.xaml中有一个TextBox:<TextBox x:Name="textBox" HorizontalAlignment="Left" Height="23" Margin="233,230,0,0" TextWrapping="Wra…
WPF MVVM中的动态TabControl - c#我几周前开始使用WPF(在C#中),现在我需要一些高级帮助来使用tabcontrol。首先,我正在使用MVVM(模型视图ViewModel)模式来设计我的应用程序,并且我有一个约束,即试图不要在文件(初始化xaml文件)后面的代码中添加代码。现在,我的问题是在MainWindow视图(窗口)中动态创建新的tabItem,当单击按钮(例如“新建选项卡”按钮)时…
在datagrid(wpf)中选择行索引 - c#如何在datagrid中选择行索引? 事件SelectionChanged以下代码不起作用: private DataGridRow dgr = new DataGridRow(); private void dataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e) { thi…