WPF c#中的日历控制事件问题

本文关键字:控制 事件 问题 日历 WPF | 更新日期: 2023-09-27 18:11:31

我试图将TextBox绑定到Calendar控件上的选定日期,当它初始化时,没有问题。问题是,当我更改所选日期后,TextBox保持在其初始值(今天)。我尝试了3种方法,包括简单地返回到文本框。Text = Calendar.DisplayDate.ToString(),但问题仍然存在。

有谁知道是什么原因引起的,或者有什么方法可以解决这个问题吗?

注意方法2中的PropertyChanged不为空。

我的代码如下,实现了另外两个方法: XAML:

<Calendar Grid.Column="1" Height="170" HorizontalAlignment="Left" Name="calStart" VerticalAlignment="Top"  Width="180" IsTodayHighlighted="False" SelectedDatesChanged="CalStartSelectedDatesChanged">
            <Calendar.CalendarDayButtonStyle>
                <Style>
                    <Style.Triggers>
                    <DataTrigger Binding="{Binding Converter={StaticResource conv}}" Value="1">
                            <Setter Property="Button.Background" Value="LightGreen" />
                        </DataTrigger>
                </Style.Triggers>
                </Style>
            </Calendar.CalendarDayButtonStyle>
     </Calendar>
 <TextBox Height="23" HorizontalAlignment="Left" Margin="34,33,0,0" Text="{Binding StartBindProp, Mode=OneWay}" Name="txtStartDate" VerticalAlignment="Top" Width="120" Grid.Column="1" Grid.Row="1" />

c#方法1:

private void CalStartSelectedDatesChanged(object sender, SelectionChangedEventArgs e)
    {
        StartBindProp = calStart.DisplayDate.ToString();
    }

    public string StartBindProp
    {
        get { return (string)GetValue(StartBindPropProperty); }
        set { SetValue(StartBindPropProperty, value); }
    }
    // Using a DependencyProperty as the backing store for StartBindProp.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty StartBindPropProperty =
        DependencyProperty.Register("StartBindProp", typeof(string), typeof(MainControl), new UIPropertyMetadata(""));
方法2:

 private void CalEndSelectedDatesChanged(object sender, SelectionChangedEventArgs e)
    {
        EndBind = calEnd.DisplayDate.ToString();
    }
    private string m_EndBind = "endtest";

    public string EndBind
    {
        get { return m_EndBind; }
        set
        {
            m_EndBind = value;
            if (null != PropertyChanged)
            {
                PropertyChanged(this, new PropertyChangedEventArgs("EndBind"));
            }
        }
    }

谢谢你的帮助!

编辑:下面的xaml也有同样的问题(并且显然将日历呈现为只读):

<TextBox Text="{Binding ElementName=calStart, Path=DisplayDate, Mode=OneWay}" />

WPF c#中的日历控制事件问题

使用Calendar.SelectedDate(或SelectedDates,如果有多个)代替DisplayDate

我相信DisplayDate用于确定日历中哪个日期周围有"选定"轮廓(因为可以选择多个日期),而SelectedDate是控件的实际值。

您可以在Calendar控件中找到MSDN文档