Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 4544864
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 21, 20262026-05-21T15:43:55+00:00 2026-05-21T15:43:55+00:00

Lets say I have a set of model classes like this: public class Person

  • 0

Lets say I have a set of model classes like this:

public class Person
{
    public string Name { get; set; }
    public ObservableCollection<Job> Jobs { get; private set; }
}
public class Job
{
    public string Title { get; set; }
    public DateTime? Start { get; set; }
    public DateTime? End { get; set; }
}

I set up my xaml like this to display a list of people and all details on a single view:

<StackPanel Orientation="Horizontal">
    <ListView ItemsSource="{Binding}" Width="200" DisplayMemberPath="Name" IsSynchronizedWithCurrentItem="True" />
    <DockPanel Width="200" Margin="10,0">
        <TextBox Text="{Binding Name}" DockPanel.Dock="Top" Margin="0,0,0,10"/>
        <ListView ItemsSource="{Binding Jobs}" Name="_jobList" DisplayMemberPath="Title" IsSynchronizedWithCurrentItem="True"/>
    </DockPanel>
    <StackPanel Width="200" DataContext="{Binding ElementName=_jobList, Path=SelectedItem}">
        <TextBox Text="{Binding Title}"/>
        <DatePicker SelectedDate="{Binding Start}"/>
        <DatePicker SelectedDate="{Binding End}"/>
    </StackPanel>
</StackPanel>

The DataContext for the entire Window is an ObservbleCollection of People. This seems to work fairly well. I would now like to add some validation and I have no idea where to start.

I would like to validate the Job fields so that the user cannot select another Job (or person) if the title is empty or a duplicate within the same person, or if the dates are out of order. Additionally, the Person cannot be changed if the name is empty.

I have read a bit about validation in WPF, but have not found any clear solution for this scenario. What is the best practice for doing something like this?

Also, is my binding ok the way I set the DataContext on the last panel like that? It works, but it feels a little sketchy. The alternative is declaring resources for the CollectionDataSources and I couldn’t really figure that method out very easily either.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-21T15:43:55+00:00Added an answer on May 21, 2026 at 3:43 pm

    For the validation part you can start here: http://codeblitz.wordpress.com/2009/05/08/wpf-validation-made-easy-with-idataerrorinfo/

    After you understand the article you could modify your classes like this:
    For example let’s add a non-empty title validation for job title and job start date:

    Job class:

     public class Job : IDataErrorInfo
        {
            public string Title { get; set; }
            public DateTime? Start { get; set; }
            public DateTime? End { get; set; }
    
            public string Error
            {
                get { throw new NotImplementedException(); }
            }
    
            public string this[string columnName]
            {
                get
            {
                string result = null;
                if (columnName == "Title")
                {
                    if (string.IsNullOrEmpty(Title))
                        result = "Please enter a Title ";
                }
                if (columnName == "Start")
                {
                    if (Start == null)
                        result = "Please enter a Start Date";
                    else if (Start > End)
                    {
                        result = "Start Date must be less than end date";
                    }
                }
                return result;
            }
            }
        }
    

    //////////Supposing we used a window called MainWindow for you xaml code it would look like
    MainWindow.xaml

    <Window x:Class="WpfApplication1.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="MainWindow" Height="350" Width="525"
            x:Name="mainWindow">
        <Window.Resources>
            <ControlTemplate x:Key="errorTemplate">
                <DockPanel LastChildFill="true">
                    <Border Background="Red" DockPanel.Dock="right" Margin="5,0,0,0" Width="20" Height="20" CornerRadius="10"
                                        ToolTip="{Binding ElementName=customAdorner, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}">
                        <TextBlock Text="!" VerticalAlignment="center" HorizontalAlignment="center" FontWeight="Bold" Foreground="white">
                        </TextBlock>
                    </Border>
                    <AdornedElementPlaceholder Name="customAdorner" VerticalAlignment="Center" >
                        <Border BorderBrush="red" BorderThickness="1" />
                    </AdornedElementPlaceholder>
                </DockPanel>
            </ControlTemplate>
    
        </Window.Resources>
            <Grid>
            <StackPanel Orientation="Horizontal">
                <ListView ItemsSource="{Binding}" Width="200" DisplayMemberPath="Name" IsSynchronizedWithCurrentItem="True" IsEnabled="{Binding ElementName=mainWindow, Path=FormHasNoNoErrors}"/>
                <DockPanel Width="200" Margin="10,0">
                    <TextBox Text="{Binding Name}" DockPanel.Dock="Top" Margin="0,0,0,10"/>
                    <ListView ItemsSource="{Binding Jobs}" Name="_jobList" DisplayMemberPath="Title" IsSynchronizedWithCurrentItem="True" IsEnabled="{Binding ElementName=mainWindow, Path=FormHasNoNoErrors}" />
                </DockPanel>
                <StackPanel Width="200" DataContext="{Binding ElementName=_jobList, Path=SelectedItem}">
                    <TextBox Text="{Binding Title, ValidatesOnDataErrors=true, NotifyOnValidationError=true}" Validation.Error="Validation_OnError" Validation.ErrorTemplate="{StaticResource errorTemplate}"/>
                    <DatePicker SelectedDate="{Binding Start, ValidatesOnDataErrors=true, NotifyOnValidationError=true}" Validation.Error="Validation_OnError" Validation.ErrorTemplate="{StaticResource errorTemplate}"/>
                    <DatePicker SelectedDate="{Binding End}"/>
                </StackPanel>
            </StackPanel>
        </Grid>
    </Window>
    

    ////////MainWindow.xaml.cs

       public partial class MainWindow : Window, INotifyPropertyChanged
        {
    
    
            public MainWindow()
            {
                var jobs1 = new ObservableCollection<Job>()
                                {
                                    new Job() {Start = DateTime.Now, End = DateTime.Now.AddDays(1), Title = "Physical Enginer"},
                                    new Job() {Start = DateTime.Now, End = DateTime.Now.AddDays(1), Title = "Mechanic"}
    
                                };
                var jobs2 = new ObservableCollection<Job>()
                                {
                                    new Job() {Start = DateTime.Now, End = DateTime.Now.AddDays(1), Title = "Doctor"},
                                    new Job() {Start = DateTime.Now, End = DateTime.Now.AddDays(1), Title = "Programmer"}
    
                                };
                var personList = new ObservableCollection<Person>()
                                       {
                                           new Person() {Name = "john", Jobs = jobs1},
                                           new Person() {Name="alan", Jobs=jobs2}
                                       };
    
                this.DataContext = personList;
                InitializeComponent();
            }
    
            private void Validation_OnError(object sender, ValidationErrorEventArgs e)
            {
                if (e.Action == ValidationErrorEventAction.Added)
                    NoOfErrorsOnScreen++;
                else
                    NoOfErrorsOnScreen--;
            }
    
            public bool FormHasNoNoErrors
            {
                get { return _formHasNoErrors; }
                set 
                { 
                    if (_formHasNoErrors != value)
                    {
                        _formHasNoErrors = value;
                         PropertyChanged(this, new PropertyChangedEventArgs("FormHasNoErrors")); 
                    }
                }
            }
    
            public int NoOfErrorsOnScreen
            {
                get { return _noOfErrorsOnScreen; }
                set 
                { 
                    _noOfErrorsOnScreen = value;
                    FormHasNoNoErrors = _noOfErrorsOnScreen == 0 ? true : false;
                }
            }
    
            private int _noOfErrorsOnScreen = 0;
            private bool _formHasNoErrors = true;
    
            public event PropertyChangedEventHandler PropertyChanged = delegate {};
        }
    

    //////////////////////

    I would like to validate the Job
    fields so that the user cannot select
    another Job (or person) if the title
    is empty or a duplicate within the
    same person, or if the dates are out
    of order. Additionally, the Person
    cannot be changed if the name is
    empty.

    One simple solution is to disable the listboxes if the forms has errors (that’s what I did in the code above), and enable them when there are no errors. Also you should probably put a nice red border with tooltip on them, explaining the user why he can’t select anymore.

    For validating if the title is duplicate within the same person, you could extend the validation mechanism above to have a ValidationService class that receives a Person and looks if the person who has the job also has another one with the same name.

    public class Person: IDataErrorInfo
    {

        public string this[string columnName]
        {
            get
        {
            //look inside person to see if it has two jobs with the same title
            string result = ValidationService.GetPersonErrors(this);
            return result;
         }
    ...
     }
    

    Also, is my binding ok the way I set
    the DataContext on the last panel like
    that? It works, but it feels a little
    sketchy. The alternative is declaring
    resources for the
    CollectionDataSources and I couldn’t
    really figure that method out very
    easily either.

    It’s not in the MVVM spirit, and if what you’re doing is going to be something more than a small test project you should try learn MVVM (You could start here: http://fernandomachadopirizen.wordpress.com/2010/06/10/a-simple-introduction-to-the-model-view-viewmodel-pattern-for-building-silverlight-and-windows-presentation-foundation-applications/)

    Then you would not bind to a list of persons directly but instead you would have some MainWindowViewModel class to which you bind. This MainWindowViewModel class would contain the list of persons and you would bind to that.
    And for the selection you would have a CurrentJob property in your MainWindowViewModel, that is the currently selected job, and you would bind to that:

    Basically something like this:

    <StackPanel Orientation="Horizontal">
        <ListView ItemsSource="{Binding PersonList}" SelectedItem="{Binding CurrentPerson, Mode=TwoWay}" Width="200" DisplayMemberPath="Name" IsSynchronizedWithCurrentItem="True" IsEnabled="{Binding ElementName=mainWindow, Path=FormHasNoNoErrors}"/>
        <DockPanel Width="200" Margin="10,0">
            <TextBox Text="{Binding Name}" DockPanel.Dock="Top" Margin="0,0,0,10"/>
            <ListView ItemsSource="{Binding Jobs}" SelectedItem="{Binding CurrentJob, Mode=TwoWay}", DisplayMemberPath="Title" IsSynchronizedWithCurrentItem="True" />
        </DockPanel>
        <StackPanel Width="200">
            <TextBox Text="{Binding CurrentJob.Title}"/>
           .....
        </StackPanel>
    </StackPanel> 
    

    And your MainWindowViewModel:

    public class MainWindowViewModel : 
    {
    ...
       //Public Properties
       public ObservableCollection<Person> PersonList ....
       public Job CurrentJob ....
    ....
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

So lets say I have an object class MyItem { public string Name {get;
Let's say you have this Model: //model public class Stuff { public string Name
Lets say i have a class [Serializable()] public class Car { public string model;
Lets say I have model inheritance set up in the way defined below. class
In my action class I have a Map<Long, Set<String>> attribute, named accountsMap. Lets say
Lets say have this immutable record type: public class Record { public Record(int x,
Lets say I have some view models set up as follows: public class User
Let's say I have a model class, public class NameModel { public string Title
Lets say I have to Grails domain classes: Car and Person. class Car {
I'm not getting the syntax right. Lets say I have this... #include <set> ...

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.