检查所选日期是否已更改WPF

本文关键字:WPF 是否 日期 检查 | 更新日期: 2023-09-27 18:17:09

我想将文本框中的数据保存到一个文件中。但是我的文本框在用户更改日期后应该是清晰的,并且应该保存数据。是否有一种方法来检查日期是否已经更改-像bool这样的东西会很好。

private void calendar_SelectedDatesChanged(object sender, SelectionChangedEventArgs e)
    {
        // ... Get reference.
        var calendar = sender as Calendar;
        // ... See if a date is selected.
        if (calendar.SelectedDate.HasValue)
        {
            DateTime date = calendar.SelectedDate.Value;
            Stream stream = File.Open(date.ToString("MMddyyyy") + ".txt", FileMode.OpenOrCreate); // Convert the date to a legal title for a text file
            StreamWriter sw = new StreamWriter(stream);
            if(stream.Length != 0) // Check if stream is not empty 
            {
                StreamReader sr = new StreamReader(stream);
                textbox.Text = sr.ReadToEnd(); 
            }
            //sw.Write(textbox.Text);
            //sw.Dispose(); 
            // ... Display SelectedDate in Title 
            this.Title = date.ToShortDateString();
            stream.Close();
        }
        //textbox.Text = ""; 
    }
XAML代码:

<Window x:Class="Terminkalender.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Kalender" Height="350" Width="525" >
<Grid>
    <Calendar   SelectedDatesChanged="calendar_SelectedDatesChanged" Name="calendar" Background="Orange" HorizontalAlignment="Left" VerticalAlignment="Top" Height="310" Width="178" RenderTransformOrigin="0.528,0.769"/>
    <TextBox Name="textbox" AcceptsReturn="True"  HorizontalAlignment="Left" Height="149" Background="Aqua" Margin="245,10,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="248"/>
</Grid>

检查所选日期是否已更改WPF

您可以声明Nullable<DateTime>属性并将其数据绑定到Calendar.SelectedDate属性,并添加条件检查以确定值是否已更改:

private Nullable<DateTime> selectedDate;
public Nullable<DateTime> SelectedDate
{
    get { return selectedDate; }
    set 
    {
        if (selectedDate != value) { /* SelectedDate has changed */ }
        selectedDate = value; 
        NotifyPropertyChanged("SelectedDate");
    }
}

<Calendar SelectedDate="{Binding SelectedDate}" />