I have a very simple binding problem with a DatePicker that is eluding me.
I have a ListBox bound to a list of objects with a DateTime property. I have an editing portion of my page for changing the selected item. This works fine – when I update the date in the DatePicker, the ListBox shows my updated date.
However, when I then select another item, the DatePicker control incorrectly updates the Date on the new item as well.
Here’s my code:
C#:
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
namespace BindingTest
{
public partial class MainPage
{
public MainPage()
{
InitializeComponent();
var vm = new ViewModel();
DataContext = vm;
}
}
public class ViewModel : INotifyPropertyChanged
{
public ViewModel()
{
List = new ObservableCollection<Item>();
for (var n = 0; n < 10; n++)
List.Add(new Item { Date = DateTime.Now.AddDays(n) });
}
public ObservableCollection<Item> List { get; set; }
private Item _selectedItem;
public Item SelectedItem
{
get { return _selectedItem; }
set { _selectedItem = value; OnPropertyChanged("SelectedItem"); }
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
public class Item : INotifyPropertyChanged
{
private DateTime _date;
public DateTime Date
{
get { return _date; }
set { _date = value; OnPropertyChanged("Date"); }
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
}
XAML:
<UserControl xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk" x:Class="BindingTest.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid x:Name="LayoutRoot" Background="White">
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<ListBox ItemsSource="{Binding List}"
DisplayMemberPath="Date"
SelectedItem="{Binding SelectedItem, Mode=TwoWay}" />
<StackPanel Grid.Column="1" DataContext="{Binding SelectedItem}">
<TextBlock Text="Date:" />
<sdk:DatePicker SelectedDate="{Binding Date, Mode=TwoWay}" />
</StackPanel>
</Grid>
</UserControl>
How can I fix this?
Seems the easiest way to solve this is to delay the change of selection so that the DatePicker updates the correct binding before the selection is changed.