I have a very simple DatePicker binding problem that eludes me.
I have a ListBox associated with a list of objects with a DateTime property. I have part of editing my page to change the selected item. This works great - when I update the date in DatePicker, the ListBox shows my updated date.
However, when I then select another item, the DatePicker control does not update the date correctly in the new item either.
Here is my code:
FROM#:
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?
source share