C# WPF中的日历控件奇怪的行为
我正在尝试绑定日历的“DisplayDate”,以使控件在日期发生更改时发出通知 这是我的xamlC# WPF中的日历控件奇怪的行为,c#,wpf,binding,wpf-controls,C#,Wpf,Binding,Wpf Controls,我正在尝试绑定日历的“DisplayDate”,以使控件在日期发生更改时发出通知 这是我的xaml <Window x:Class="CalenderControl.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2
<Window x:Class="CalenderControl.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Calendar x:Name="_calendar" DisplayMode="Year" DisplayDate="{Binding Display}"/>
</Grid>
</Window>
案例1:
在这一切之后。我已经为datacontext分配了viewmodel
public MainWindow()
{
InitializeComponent();
this.DataContext = new ViewModel() { Display = DateTime.Parse("10/10/2015") };
}
这就是绑定后的外观
案例2:
然后,我尝试不使用ViewModel分配DataContext
public MainWindow()
{
InitializeComponent();
// --- Commenting out ---
//this.DataContext = new ViewModel() { Display = DateTime.Parse("10/10/2015") };
}
这就是它在没有绑定的情况下的外观
为什么在分配DataContext时宽度会变得奇怪?我做错什么了吗 由于未知原因,该问题似乎与
DisplayMode=“Year”
我可以建议您执行以下步骤,似乎在我的测试应用程序中工作
1) 从Xaml中删除DisplayMode
2) 设置DataContext后,附加以下内容:
Action act = delegate()
{
_calendar.SelectedDate = ((ViewModel)DataContext).Display;
_calendar.DisplayMode = CalendarMode.Year;
_calendar.SelectedDate = null;
};
Dispatcher.BeginInvoke(act, DispatcherPriority.ApplicationIdle);
看起来很奇怪,但应该有用。如果需要,无法将SelectedDate设置回null
添加:SelectedDate技巧似乎是将日历日期设置为2015年所必需的,在您的屏幕截图中是第1年;-) 不是
DisplayDate
绑定导致Calendar
控件拉伸;它正在将显示模式设置为“年份
”。它看起来像是日历控件中的一个bug。它应该是OnPropertyChanged(“Display”);未更改属性(“显示日期”);在二传中。(与宽度问题无关)@Nikita。对现在更新。谢谢你。万岁。如预期的那样工作。非常感谢。我仍然对这种行为感到困惑。非常非常奇怪……但这似乎起到了作用!如果对你有帮助,请随时接受答案。
Action act = delegate()
{
_calendar.SelectedDate = ((ViewModel)DataContext).Display;
_calendar.DisplayMode = CalendarMode.Year;
_calendar.SelectedDate = null;
};
Dispatcher.BeginInvoke(act, DispatcherPriority.ApplicationIdle);