我正在尝试在MVVM模式中实现附加行为功能。我有一个Calendar
控件,想要处理MouseDoubleClick
事件。我是使用System.Windows.Interactivity和Interaction.Triggers
做的。但是,我也在BlackoutDates
中使用Calendar
并双击停电日期会导致最后一个有效的选定日期传递到MouseDoubleClick
方法,而不是点击的日期。
所以我现在定位CalendarDayButton
,它会让我点击日期,但CDB没有Commands
,所以我需要使用附加行为。但我仍然不了解如何将MouseDoubleClick
处理程序信息导入ViewModel。我目前的代码:
查看
<Calendar HorizontalAlignment="Left" VerticalAlignment="Top" Margin="20,48,0,0"
SelectedDate="{Binding ReportDate, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
DisplayDateStart="{Binding ReportDateStart, Mode=OneTime}"
DisplayDateEnd="{Binding ReportDateEnd, Mode=OneTime}"
local:AttachedProperties.RegisterBlackoutDates="{Binding NoProdDates, Mode=OneWay}">
<Calendar.CalendarDayButtonStyle>
<Style TargetType="CalendarDayButton">
<Setter Property="local:AttachedBehaviors.IsValidDateSelected"
Value="{Binding ValidDateSelected, Mode=TwoWay}"/>
</Style>
</Calendar.CalendarDayButtonStyle>
</Calendar>
的视图模型
...
private bool validDateSelected;
public bool ValidDateSelected
{
get { return validDateSelected; }
set
{
if (validDateSelected != value)
{
validDateSelected = value;
RaisePropertyChanged("ValidDateSelected");
}
}
}
...
附加行为类
using System.Windows;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
namespace MDOD
{
public class AttachedBehaviors : DependencyObject
{
public static readonly DependencyProperty IsValidDateSelectedProperty =
DependencyProperty.RegisterAttached("IsValidDateSelected", typeof(bool), typeof(AttachedBehaviors),
new UIPropertyMetadata(false, OnIsValidDateSelectedChanged));
public static bool GetIsValidDateSelected(DependencyObject obj)
{
return (bool)obj.GetValue(IsValidDateSelectedProperty);
}
public static void SetIsValidDateSelected(DependencyObject obj, bool value)
{
obj.SetValue(IsValidDateSelectedProperty, value);
}
private static void OnIsValidDateSelectedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
CalendarDayButton cdb = d as CalendarDayButton;
if (cdb != null)
{
if ((bool)e.NewValue)
{
cdb.MouseDoubleClick += cdb_MouseDoubleClick;
}
else
{
cdb.MouseDoubleClick -= cdb_MouseDoubleClick;
}
}
}
private static void cdb_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
// How do I get this info to the ViewModel?
}
}
}