wpf - 如何使用 Bindings 获取 DateTime 值? (WPF-MVVM)

标签 wpf datetime mvvm binding

我想要这样的东西:

<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/

相关文章:

c# - 单击一次部署后的通知图标设置

c# - 在单击Gridview行时,更新另一个控件

wpf - 在 WPF StatusBar 中显示抓取器?

c# - 如何将一段时间分组为年度? (将时间跨度分成年度)

wpf - 命令执行对话框关闭后 MVVM UI 更新

Python 日期时间减法包括 0 到小时部分

php - MySQL/PHP - 时间流逝

c# - Datagrid.IsSelected 绑定(bind)和滚动

wpf - 我可以避免为依赖属性显式调用 RaisePropertyChanged 吗?

c# - 在现代 UI (Metro) 图表中以编程方式 (MVVM) 添加 ChartSeries