I'm working on a C# WPF solution, based on XAML windows.
On one of those windows, I've added a DatePicker, and I want something to be done at two moments:
- When the window is loaded
- When the date in the
DatePickeris changed.
This can be done very easily:
public void LoadData()
{
date_DatePicker.SelectedDate = DateTime.Today;
Do_Something();
}
private void DatePicker_DateChanged(object sender, SelectionChangedEventArgs e)
{
if (date_DatePicker.SelectedDate.HasValue)
{
Do_Something();
}
}
... but you see the problem: as the loading of the window caused a date, being filled in in the DatePicker, this launches the Do_Something(), causing this method to be launched twice.
I thought of disabling this, by checking e.OriginalSource, but apparently the date is already filled in there too (I was hoping (DatePicker)(e.OriginalSource).SelectedDate to be null).
Is there a way to say something like:
public void LoadData()
{
disable_Events();
date_DatePicker.SelectedDate = DateTime.Today;
re-enable_Events();
Do_Something();
}
or:
private void DatePicker_DateChanged(object sender, SelectionChangedEventArgs e)
{
if ((date_DatePicker.SelectedDate.HasValue) &&
!(previous_value_was_empty(sender,e))) // <--- does such a thing exist?
Thanks in advance
My typical approach is to use a flag:
You may want to use try/finally if there is a risk that
DoSomethingthrows exceptions.