C# 在代码隐藏之外的其他位置捕获事件
我在我的应用程序中有一些窗口,它们将以其样式封装在C# 在代码隐藏之外的其他位置捕获事件,c#,wpf,C#,Wpf,我在我的应用程序中有一些窗口,它们将以其样式封装在中。在这种风格中,我构建了一个模板,其中有一些自定义用户控件,如自定义标题栏和包含任何窗口内容的ContentPresenter。目标是提取每个窗口所需的xaml,并将其放入样式中的模板中这正是wpf的用途。 然后,当用户在任何地方单击其内容时,我希望从这些窗口的所有窗口引发一个事件。因此,我在样式中添加了: <ContentPresenter PreviewMouseDown="somethingMouseDowned" />
中。在这种风格中,我构建了一个模板,其中有一些自定义用户控件,如自定义标题栏和包含任何窗口内容的ContentPresenter
。目标是提取每个窗口所需的xaml,并将其放入样式中的模板中这正是wpf的用途。
然后,当用户在任何地方单击其内容时,我希望从这些窗口的所有窗口引发一个事件。因此,我在样式中添加了:
<ContentPresenter PreviewMouseDown="somethingMouseDowned" />
请注意,首先,我将此应用于窗口内的grisd,在代码隐藏(xaml.cs)中,我处理了事件,做了我想做的事情,一切都很好
但我希望事件处理在窗口中不可见。这就是为什么我把PreviewMouse放在样式中。我也不希望在我的代码隐藏中有任何处理代码
问题是我不知道如何在代码隐藏之外的其他地方处理事件。我需要其他选择
提前感谢在某种程度上,您必须在codebehind中包含一些代码才能处理该事件。但是,为了尽量减少codebehind中的代码量,您可以利用并将所有事件处理封装到presenter类中,或者您可以利用其他一些工具集,如本文所述。如果您在其他类中有静态事件处理程序,请尝试使用
{x:Static anotherClass.somethingMouseDowned}您还可以使用AttachedProperty(EventToCommand)并将此事件绑定到viewmodel中的命令(ICommand)。 代码如下:
public static class ContenPreviewMouseDownCommandBinding
{
public static readonly DependencyProperty CommandProperty =
DependencyProperty.RegisterAttached("Command", typeof (ICommand), typeof (ContenPreviewMouseDownCommandBinding),
new PropertyMetadata(default(ICommand), HandleCommandChanged));
private static void HandleCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var contentPresenter = d as ContentPresenter;
if(contentPresenter!=null)
{
contentPresenter.PreviewMouseDown += new MouseButtonEventHandler(contentPresenter_PreviewMouseDown);
}
}
static void contentPresenter_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
var contentPresenter = sender as ContentPresenter;
if(contentPresenter!=null)
{
var command = GetCommand(contentPresenter);
command.Execute(e);
}
}
public static void SetCommand(ContentPresenter element, ICommand value)
{
element.SetValue(CommandProperty, value);
}
public static ICommand GetCommand(ContentPresenter element)
{
return (ICommand) element.GetValue(CommandProperty);
}
}
在XAML中:
<ContentPresenter CommandBindings:ContenPreviewMouseDownCommandBinding.Command="{Binding Path=AnyCommandInScopeOfDataContext}">
</ContentPresenter>
什么样的控制?这是一个用户控件(WPF)吗?您似乎对XAML的一般工作方式有一些严重的误解。我建议您从基础开始,在尝试创建复杂的组合、自定义样式的UI之前,遵循WPF XAML中的一些“Hello,World!”
类型的教程。请重新考虑@HighCore谢谢。你考虑过使用指挥系统吗?在MVVM(Model-View-ViewModel)模式中,目标是根本不在代码中放置任何代码,而是将所有逻辑都放在ViewModel对象中。MVVM使用命令系统来实现这一点,这就是我所做的。谢谢!:)非常感谢您的回复!非常感谢。:)