私はこのようなものが欲しいです:
<DatePicker SelectedDate="{Binding StartDate}" />
これに対する制御または簡単な解決策はありますか? (私はMVVMを使用しています。)
この場合StartDate
、ViewModel にはプロパティのみが必要であり、機能します。
また、DatePicker で日付を変更すると、ViewModel クラスの StartDate プロパティに自動的に反映されます。
シンプルなViewModel:
class MainViewModel : INotifyPropertyChanged
{
private DateTime _startDate = DateTime.Now;
public DateTime StartDate
{
get { return _startDate; }
set { _startDate = value; OnPropertyChanged("StartDate"); }
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(name));
}
}
簡易表示:
<Window x:Class="SimpleBinding.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<StackPanel>
<DatePicker SelectedDate="{Binding StartDate}" />
</StackPanel>
</Window>
分離コード:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new MainViewModel();
}
}
WPF Toolkitを参照してください(注: CodePlex は、執筆時点でダウン/低速です)。