첨부 소스 코드는 나눔고딕코딩 폰트를 사용합니다.
728x90
반응형
728x170

TestProject.zip
다운로드

▶ CourseValidationRule.cs

using System.Globalization;
using System.Windows.Controls;
using System.Windows.Data;

namespace TestProject
{
    /// <summary>
    /// 코스 검증 규칙
    /// </summary>
    public class CourseValidationRule : ValidationRule
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Method
        ////////////////////////////////////////////////////////////////////////////////////////// Public

        #region 검증하기 - Validate(value, cultureInfo)

        /// <summary>
        /// 검증하기
        /// </summary>
        /// <param name="value">값</param>
        /// <param name="cultureInfo">문화 정보</param>
        /// <returns>검증 결과</returns>
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            Course course = (value as BindingGroup).Items[0] as Course;

            if(course.StartDate > course.EndDate)
            {
                return new ValidationResult(false, "시작일은 종료일보다 앞서야 합니다.");
            }
            else
            {
                return ValidationResult.ValidResult;
            }
        }

        #endregion
    }
}

 

728x90

 

▶ MainWindow.xaml

<Window x:Class="TestProject.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:TestProject"
    Width="800"
    Height="600"
    Title="DataGrid 클래스 : RowValidationRules 속성을 사용해 검증하기"
    FontFamily="나눔고딕코딩"
    FontSize="16">
    <Grid>
        <Grid.Resources>
            <local:CourseCollection x:Key="CourseCollectionKey"/>
        </Grid.Resources>
        <DataGrid Name="dataGrid"
            RowHeaderWidth="30"
            AutoGenerateColumns="False"
            ItemsSource="{StaticResource CourseCollectionKey}">
            <DataGrid.Resources>
                <Style x:Key="EditingElementStyleKey"
                    TargetType="{x:Type TextBox}">
                    <Setter Property="Padding" Value="-2" />
                    <Style.Triggers>
                        <Trigger Property="Validation.HasError" Value="True">
                            <Setter Property="Background" Value="Red"/>
                            <Setter Property="ToolTip"
                                Value="{Binding RelativeSource={RelativeSource Self},
                                    Path=(Validation.Errors)[0].ErrorContent}" />
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </DataGrid.Resources>
            <DataGrid.Columns>
                <DataGridTextColumn
                    Header="코스명" 
                    Binding="{Binding Name, TargetNullValue=(enter a course name)}" />
                <DataGridTextColumn
                    Header="코스 ID"
                    EditingElementStyle="{StaticResource EditingElementStyleKey}"
                    Binding="{Binding ID, ValidatesOnExceptions=True}" />
                <DataGridTextColumn
                    Header="시작일"
                    EditingElementStyle="{StaticResource EditingElementStyleKey}"
                    Binding="{Binding StartDate, ValidatesOnExceptions=True, StringFormat=yyyy-MM-dd}" />
                <DataGridTextColumn
                    Header="종료일"
                    EditingElementStyle="{StaticResource EditingElementStyleKey}"
                    Binding="{Binding EndDate, ValidatesOnExceptions=True, StringFormat=yyyy-MM-dd}" />
            </DataGrid.Columns>
            <DataGrid.RowValidationRules>
                <local:CourseValidationRule ValidationStep="UpdatedValue" />
            </DataGrid.RowValidationRules>
            <DataGrid.RowValidationErrorTemplate>
                <ControlTemplate>
                    <Grid
                        Margin="0 -2 0 -2"
                        ToolTip="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGridRow}},
                            Path=(Validation.Errors)[0].ErrorContent}">
                        <Ellipse
                            StrokeThickness="0"
                            Fill="Red" 
                            Width="{TemplateBinding FontSize}" 
                            Height="{TemplateBinding FontSize}" />
                        <TextBlock
                            Text="!"
                            Foreground="White" 
                            FontSize="{TemplateBinding FontSize}" 
                            FontWeight="Bold"
                            HorizontalAlignment="Center" />
                    </Grid>
                </ControlTemplate>
            </DataGrid.RowValidationErrorTemplate>
        </DataGrid>
    </Grid>
</Window>

 

300x250

 

▶ MainWindow.xaml.cs

using System;
using System.Windows;

namespace TestProject
{
    /// <summary>
    /// 메인 윈도우
    /// </summary>
    public partial class MainWindow : Window
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor
        ////////////////////////////////////////////////////////////////////////////////////////// Public

        #region 생성자 - MainWindow()

        /// <summary>
        /// 생성자
        /// </summary>
        public MainWindow()
        {
            InitializeComponent();

            this.dataGrid.InitializingNewItem += (sender, e) =>
            {
                Course course = e.NewItem as Course;

                course.StartDate = course.EndDate = DateTime.Today;
            };
        }

        #endregion
    }
}
728x90
반응형
그리드형(광고전용)
Posted by icodebroker

댓글을 달아 주세요