如何使用绑定获取 DateTime 值?(WPF-MVVM)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13959543/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I get a DateTime value with Bindings? (WPF-MVVM)
提问by BlackCat
I would like something like this:
我想要这样的东西:
<DatePicker SelectedDate="{Binding StartDate}" />
Is there any control or easy solution for this? (I use MVVM.)
是否有任何控制或简单的解决方案?(我使用 MVVM。)
回答by kmatyaszek
In this case you must have only property StartDatein ViewModel and it will be working.
在这种情况下,您必须StartDate在 ViewModel 中只有属性,它才能工作。
And when you change date in the DatePicker, it will be automatically reflected in the property StartDate in ViewModel class.
而当你在 DatePicker 中更改日期时,它会自动反映在 ViewModel 类中的属性 StartDate 中。
Simple 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));
}
}
Simple View:
简单视图:
<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>
Code-behind:
代码隐藏:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new MainViewModel();
}
}
回答by Kent Boogaart
See the WPF Toolkit(note: CodePlex is down/slow at the time of writing).
请参阅WPF 工具包(注意:CodePlex 在撰写本文时已关闭/缓慢)。

