首页 > 其他分享 >WPF ErrorTemplate

WPF ErrorTemplate

时间:2024-05-03 21:57:42浏览次数:11  
标签:ErrorTemplate Windows System MainWindow handler using WPF public

//xaml
<Window x:Class="WpfApp91.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp91"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.Resources>
        <ControlTemplate x:Key="errorTemplate">
            <Border BorderBrush="Red" BorderThickness="10">
                <Grid>
                    <AdornedElementPlaceholder x:Name="_el"/>
                    <TextBlock Text="{Binding [0].ErrorContent}"
                        Foreground="Red" HorizontalAlignment="Right"
                        VerticalAlignment="Center" Margin="0,0,6,0"/>
                </Grid>
            </Border>
        </ControlTemplate>
    </Window.Resources>
    <Grid TextBlock.FontSize="30">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <TextBlock Text="Name:" Margin="6"/>
        <TextBox Grid.Column="1" Validation.ErrorTemplate="{StaticResource ResourceKey=errorTemplate}" >
            <TextBox.Text>
                <Binding Path="Name" ValidatesOnDataErrors="True"
                         UpdateSourceTrigger="PropertyChanged">
                    <Binding.ValidationRules>
                        <local:MinCharsRule MinimumChars="3"/>
                    </Binding.ValidationRules>
                </Binding> 
            </TextBox.Text> 
        </TextBox>
        <TextBlock Text="Age:" Grid.Row="1" Margin="6"/>
        <TextBox Text="{Binding Age,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged, 
            ValidatesOnExceptions=True,ValidatesOnDataErrors=True}"  Grid.Column="1" Grid.Row="1" Margin="6"/>
    </Grid>
</Window>


//cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApp91
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            DataContext = new Person
            {
                Name = "Fred",
                Age = 17
            };
        }
    }

    public class Person : INotifyPropertyChanged,IDataErrorInfo
    {
        public event PropertyChangedEventHandler PropertyChanged;
        public void OnPropertyChanged(string propName)
        {
            var handler = PropertyChanged;
            if(handler!=null)
            {
                handler?.Invoke(this,new PropertyChangedEventArgs(propName));
            }
        }

        private int age;
        public int Age
        {
            get
            {
                return age;
            }
            set
            {
                if(value<1)
                {
                    throw new ArgumentException("Age must be a positive integer!");
                }
                if(value!=age)
                {
                    age = value;
                    OnPropertyChanged("Age");
                }
            }
        }

        private string name;
        public string Name
        {
            get
            {
                return name;
            }
            set
            {
                if (value!=name)
                {
                    name = value;
                    OnPropertyChanged("Name");
                }
            }
        }

        public string Error
        {
            get
            {
                return null;
            }
        }

        public string this[string columnName]
        {
            get
            {
                switch(name)
                {
                    case "Name":
                        if(string.IsNullOrWhiteSpace(Name))
                        {
                            return "Name cannot be empty!";
                        }
                        break;
                    case "Age":
                        if(Age<1)
                        {
                            return "Age must be a positive integer";
                        }
                        break;
                }
                return null;
            }
        }
    }

    class MinCharsRule : ValidationRule
    {
        public int MinimumChars { get; set; }
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            if(value?.ToString()?.Length< MinimumChars)
            {
                return new ValidationResult(false, "Use at least " + MinimumChars.ToString()
                    + " characters");
            }
            return new ValidationResult(true, null);
        }
    }
}

 

标签:ErrorTemplate,Windows,System,MainWindow,handler,using,WPF,public
From: https://www.cnblogs.com/Fred1987/p/18171681

相关文章

  • WPF ValidatesOnDataErrors IDataErrorInfo ValidationRule
    //xaml<Windowx:Class="WpfApp91.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.mic......
  • WPF datagrid datagridtemplatecolumn DataGridTemplateColumn.CellEditingTemplate D
    //xaml<Windowx:Class="WpfApp89.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.mic......
  • WPF Datagrid DataGridComboBoxColumn ObjectDataProvider ObjectDataProvider.Method
    //xaml<Windowx:Class="WpfApp90.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.mic......
  • WPF上位机 - 使用转换器实现TIA Wincc中的文本列表功能
    TIAwincc中可以根据变量的值,显示出定义的文本。在WPF中可以通过转换器实现。使用哈希表存储变量和文本,根据变量值返回对应的文本显示在View中usingSystem;usingSystem.Collections.Generic;usingSystem.Globalization;usingSystem.Linq;usingSystem.Text;usingSy......
  • WPF上位机 - 使用转换器实现TIA Wincc中的位控制可见性或外观功能
    在TIAWincc中有这样的功能,使用Trueorfalse控制控件的可见性或者外观的情况。在上位机中需要使用转换器这样对Trueorfalse值转换为需要的笔刷或者Visible属性。usingSystem;usingSystem.Collections.Generic;usingSystem.Globalization;usingSystem.Linq;using......
  • WPF上位机 - S7.NETPlus批量读取数据
    在编写上位机程序中,需要读取PLC数据。使用到了S7.NETPlus这个库。S7.NETPlus提供了很多读取和写入数据的方式。大批量读取数据的方式包括一下几个方法ReadbytesReadClassReadStructReadMultipleVarsPLC侧的数据是一个Array的UDT数据,其中UDT中还包含了很多的UDT。在使用库......
  • WPF上位机 - 轴运动控制
    最近学习WPF,写了一个WPF上位机使用S7.NETPlus库与西门子1500TPLC,控制西门子伺服的通用上位机界面。分享在写上位机过程中踩的一些坑和使用体验。上位机介绍可以看到上位机分为3个区域轴选择,使能区域控制参数设置区域诊断区域选择使能区域选择区域读取TIA中组态的轴工艺......
  • WPF TreeView HierarchicalDataTemplate
    //xaml<Windowx:Class="WpfApp87.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.mic......
  • WPF Text MultiBinding StringFormat
    <TextBlock.Text><MultiBindingStringFormat="R:{0:N0},G:{1:N0},B:{2:N0}"><BindingPath="Value"ElementName="_red"/><BindingPath="Value"ElementName="_green"/>......
  • WPF MultiBinding
    <Windowx:Class="WpfApp84.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.......