【问题标题】:WPF handling RoutedEvent from UserControlWPF 处理来自 UserControl 的 RoutedEvent
【发布时间】:2009-06-22 06:38:28
【问题描述】:

我有一个UserControl,默认是VS生成的,只加了TextBlock:

<UserControl x:Class="MyNameSpace.Presentation.MyControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Name="myControl">
    <Grid>
        <TextBlock x:Name="SomeTextBox" Text="SomeText"></TextBlock>
    </Grid>

现在,我从后面的代码中动态地将这个控件的几个实例放入父控件的 WrapPanel 中。我想处理来自 MyControl 实例的所有鼠标左键单击。我有以下代码:

<UserControl x:Class="Minimo.Presentation.FirstParent"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Presentation="clr-namespace:Minimo.Presentation"
Height="300" Width="300">
<WrapPanel Name="wrapPanelOfMyControls" MyControl.MouseLeftButtonDown="WrapPanel1_OnMouseLeftButtonDown">
</WrapPanel>

在事件处理程序中,我做了一些动作,它起作用了。但是,在编辑 XAML 文件时出现以下错误: 在“MyControl”类型中找不到可附加属性“MouseLeftButtonDown”。如何解决这个问题?

【问题讨论】:

    标签: wpf user-controls event-handling routedevent


    【解决方案1】:

    这只是 XAML 编译器/设计器的一个错误,可以放心地忽略。但是,您可以通过指定它更清楚的类型来“修复”它:

    UIElement.MouseLeftButtonDown="WrapPanel1_OnMouseLeftButtonDown"
    

    【讨论】:

    • 谢谢,问题解决了。另一方面,它不是让包装面板处理程序来处理所有子控件的鼠标点击事件,即使不是来自 MyControl 实例? (而仅从此控件中显式键入 MyControl.MouseLeftButtonDown)
    • 两种形式的作用完全相同——它们只是以不同的方式引用同一个路由事件。而且因为它是一个路由事件,所以如果孩子尚未将 PreviewMouseLeftButtonDown 事件标记为已处理,则面板将始终有机会处理它。
    • 这个 bug 仍然存在,5 年多了!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-15
    • 1970-01-01
    相关资源
    最近更新 更多