Reputation: 396
I am trying to bind my MouseDoubleClick
event to whenever the user double clicks only on a day in the calendar, which will open a new window for that day. However the latter is performed and fetches the highlighted day even if the user double clicks anywhere else in the calendar area.
I tried to do it using the style option however I am getting the same result as if I place it in the calendar definition line:
<Calendar x:Name="calendar" Grid.Column="1" HorizontalAlignment="Stretch"
Margin="10,7,0,0" VerticalAlignment="Top" IsTodayHighlighted="True"
MouseDoubleClick="event">
Same Result as
<Style TargetType="CalendarDayButton">
<EventSetter Event="MouseDoubleClick" Handler="Cdb_MouseDoubleClick"/>
</Style>
How can I differentiate between when a day is press, when the month is pressed, when nothing is pressed, instead of what is focused?
EDIT (this method is working using xaml):
<Calendar x:Name="calendar" Grid.Column="1" HorizontalAlignment="Stretch"
Margin="10,7,0,0" VerticalAlignment="Top"
IsTodayHighlighted="True" SelectionMode="SingleDate">
<Calendar.CalendarDayButtonStyle>
<Style TargetType="CalendarDayButton">
<EventSetter Event="MouseDoubleClick" Handler="CalendarDayButton_MouseDoubleClick"/>
</Style>
</Calendar.CalendarDayButtonStyle>
</Calendar>
private void CalendarDayButton_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
MessageBox.Show("Test");
}
Upvotes: 1
Views: 1639
Reputation: 1870
For something like this, I generally look at e.OriginalSource
, then walk up the visual tree to find the target parent type, in your case CalendarDayButton
. The original source is generally a TextBlock
or some primitive, as that is what user actually clicks on. Also, there is no need for applying a style to CalendarDayButton
.
So if you put the double click event handler on your Calendar
as per your first line of code, you can do it like below. There, if a visual parent of the is not found, FindParentOfType()
method will return null
. Then it is just a matter of testing for null
. If not null
, means you have the correct target.
<Calendar x:Name="calendar" Grid.Column="1" HorizontalAlignment="Stretch"
Margin="10,7,0,0" VerticalAlignment="Top" IsTodayHighlighted="True"
MouseDoubleClick="calendar_MouseDoubleClick">
private void calendar_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
DependencyObject originalSource = e.OriginalSource as DependencyObject;
CalendarDayButton day = FindParentOfType<CalendarDayButton>(originalSource);
if (day != null)
{
//open menu
}
e.Handled = true;
}
//and you will need this helper method
//generally a staple in any WPF programmer's arsenal
public static T FindParentOfType<T>(DependencyObject source) where T : DependencyObject
{
T ret = default(T);
DependencyObject parent = VisualTreeHelper.GetParent(source);
if (parent != null)
{
ret = parent as T ?? FindParentOfType<T>(parent) as T;
}
return ret;
}
Upvotes: 1