I have a simple class called Person.cs as follows:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string City { get; set; }
}
I have a ViewModel called MainWindowViewModel.cs as follows:
public class MainWindowViewModel : INotifyPropertyChanged
{
public MainWindowViewModel()
{
People = new ObservableCollection<Person>();
}
private ObservableCollection<Person> _people;
public ObservableCollection<Person> People
{
get
{
return _people;
}
set
{
_people = value;
OnPropertyChanged("People");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
I have a Datagrid in MainWindow.xaml as follows:
All is working fine upto this point. Now I want to delete the empty rows in DataGrid when it looses focus. I can do that as below :
private void maindg_LostFocus(object sender, RoutedEventArgs e)
{
var list = (IList)maindg.ItemsSource;
var elementType = list.GetType().GetGenericArguments()[0];
var newElement = Activator.CreateInstance(elementType);
foreach(var item in maindg.Items)
{
if((((Person)item).FirstName = null || ((Person)item).FirstName = "") && (((Person)item.LastName) = null || ((Person)item).LastName = "") && (((Person)item).City = null || ((Person)item).City = ""))
{
list.Remove(item);
}
}
}
But I am planning to create something like reusable control, so I cannot typecast item
to Person
object. So, how can I check if item
is null or empty?