【问题标题】:Xaml Calendar DisplayMode="Year" not working when used with Grid.Definitions and DataContext与 Grid.Definitions 和 DataContext 一起使用时,Xaml 日历 DisplayMode="Year" 不起作用
【发布时间】:2023-03-19 10:04:01
【问题描述】:

我在DisplayMode="Year"this.DataContext = new SampleModel(); 中使用日历,所以我可以访问模型的属性。但是日历呈现错误(见截图)

代码归结为: Xaml:

<Window x:Class="Excel2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="600" Width="800">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="250"></ColumnDefinition>
            <ColumnDefinition Width="2*"></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="220"></RowDefinition>
            <RowDefinition Height="*"></RowDefinition>
        </Grid.RowDefinitions>

        <Calendar DisplayMode="Year"></Calendar>
    </Grid>
</Window>

后面的代码:

using ....

namespace Excel2
{
    class SampleModel
    {
    }

    public partial class MainWindow : Window
    {
        public MainWindow()
        {            
            InitializeComponent();
            this.DataContext = new SampleModel();
        }
    }
}

结果: 如您所见,日历渲染时没有显示任何年份信息。

如果我不使用网格定义,Displaymode=Yearthis.DataContext =... 一切都会正确呈现。

这是 XAML 中的错误吗?

【问题讨论】:

    标签: xaml calendar grid datacontext displaymode


    【解决方案1】:

    由于这个问题已经被问了一年多,但仍然没有任何可接受的答案,所以我想贡献一下我如何摆脱这个错误。

    我将我的 xaml 更改为:

     <Calendar Grid.Row="0" Grid.Column="3" x:Name="_calendar" DisplayModeChanged="_calendar_DisplayModeChanged" Loaded="_calendar_OnLoaded"
                              DisplayDate="{Binding SelectedMonth, UpdateSourceTrigger=PropertyChanged}" DisplayMode="Month" />
    
     //Setting DisplayMode="Month" in xaml and will change it back to "Year" in code behind. so my codebehind code is
    
    
        private void _calendar_DisplayModeChanged(object sender, CalendarModeChangedEventArgs e)
        {
            _calendar.DisplayMode = CalendarMode.Year;
        }
    
        private void _calendar_OnLoaded(object sender, RoutedEventArgs e)
        {
            _calendar.DisplayMode = CalendarMode.Year;
        }
    

    已加载的事件需要第一次更改显示模式,并且在选择更改时,需要在后续调用时更改显示模式的事件。

    我希望它对将来的人有所帮助。

    【讨论】:

    • 我不明白你为什么没有对这个答案投赞成票。我一直在努力实现这个monthpicker,而你是唯一一个有工作解决方案的人......非常感谢!
    • 很高兴它帮助了@Speuline
    • 如果您有几分钟的时间,我对您的代码还有另一个问题:stackoverflow.com/questions/40491255/…
    • 很长一段时间后,不再使用 xaml,我注意到我没有奖励那个答案。感激不尽
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-10
    • 1970-01-01
    • 1970-01-01
    • 2018-02-26
    相关资源
    最近更新 更多