我想要这样的东西:
<DatePicker SelectedDate="{Binding StartDate}" />
对此有任何控制或简单的解决方案吗? (我使用 MVVM。)
最佳答案
在这种情况下,您必须只有属性 StartDate
在 ViewModel 中,它将正常工作。
当你在 DatePicker 中更改日期时,它会自动反射(reflect)在 ViewModel 类的 StartDate 属性中。
简单 View 模型:
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));
}
}
简单 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>
代码隐藏:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new MainViewModel();
}
}
关于wpf - 如何使用 Bindings 获取 DateTime 值? (WPF-MVVM),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13959543/