RowDefinition、ColumnDefinitions 定义与使用

Code:
在这里插入图片描述

效果图:
在这里插入图片描述

Code:
在这里插入图片描述

效果图:
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
WPF中可以使用`IDataErrorInfo`接口进行数据校验,该接口定义了两个属性:`Error`和`Item[]`。其中`Error`表示整个数据模型的错误,`Item[]`表示每个属性的错误信息。 首先,在ViewModel中实现`IDataErrorInfo`接口,例如: ```csharp public class PersonViewModel : INotifyPropertyChanged, IDataErrorInfo { private string name; public string Name { get { return name; } set { if (name != value) { name = value; OnPropertyChanged("Name"); } } } public string Error { get { return null; } } public string this[string columnName] { get { string error = null; switch (columnName) { case "Name": if (string.IsNullOrEmpty(Name)) error = "Name is required."; break; } return error; } } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } ``` 上面的代码中,`Name`属性表示一个人的姓名,使用`this[string columnName]`方法实现对该属性的校验,如果`Name`为空,则返回错误信息。 然后,在View中绑定ViewModel,并使用`Validation.ErrorTemplate`样式显示错误信息,例如: ```xaml <Window x:Class="WpfApp1.MainWindow" ... xmlns:local="clr-namespace:WpfApp1" Title="MainWindow" Height="450" Width="800"> <Window.DataContext> <local:PersonViewModel /> </Window.DataContext> <Window.Resources> <Style TargetType="{x:Type TextBox}"> <Setter Property="Validation.ErrorTemplate"> <Setter.Value> <ControlTemplate> <StackPanel> <TextBlock Text="{Binding Path=AdornedElement.(Validation.Errors)[0].ErrorContent}" Foreground="Red" /> <AdornedElementPlaceholder /> </StackPanel> </ControlTemplate> </Setter.Value> </Setter> </Style> </Window.Resources> <Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="100" /> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <Label Grid.Row="0" Grid.Column="0" Content="Name:" /> <TextBox Grid.Row="0" Grid.Column="1" Text="{Binding Name, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" /> <Button Grid.Row="1" Grid.Column="1" Content="Save" /> </Grid> </Window> ``` 上面的代码中,`TextBox`使用`ValidatesOnDataErrors=True`属性开启数据校验,使用`Validation.ErrorTemplate`样式显示错误信息。当`Name`为空时,该`TextBox`下方会显示红色的错误信息。 通过上述方式,可以方便地对WPF应用程序中的数据进行校验。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值