路由事件“the member is not recognized or is not accessible”的成员未被识别或无法访问。

4
不使用输入设备生成的事件,我想在代码后台以编程方式触发自定义事件,作为xaml中的EventTrigger。
这应该非常容易,但我无法找到任何示例。
从研究WPF4 Unleashed第6章、路由事件实现EventTrigger.RoutedEvent属性自定义路由事件作为EventTrigger和许多其他内容中,我得出了以下结论:

MainWindow.xaml.cs:

namespace RoutedEventTrigger
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            RaiseEvent(new RoutedEventArgs(fooEvent, this));
        }
        public static readonly RoutedEvent fooEvent = EventManager.RegisterRoutedEvent(
        "foo", RoutingStrategy.Direct, typeof(RoutedEventHandler), typeof(MainWindow));

        // Provide CLR accessors for the event 
        public event RoutedEventHandler foo
        {
            add { AddHandler(fooEvent, value); }
            remove { RemoveHandler(fooEvent, value); }
        }
    }
}

MainWindow.xaml:

MainWindow.xaml

顺便提一下,我对WPF还比较新手,请不要太苛刻。

3个回答

6

Okuma Scott,

您尝试过构建(重建)项目吗?WPF要求您构建项目,以便项目更改对XAML解析器可见。使用以下代码进行构建非常好。

代码

public partial class MainWindow : Window
{
    public MainWindow() => InitializeComponent();

    public static readonly RoutedEvent fooEvent = EventManager.RegisterRoutedEvent("foo",
        RoutingStrategy.Direct, typeof(RoutedEventHandler), typeof(MainWindow));

    // Provide CLR accessors for the event 
    public event RoutedEventHandler foo
    {
        add => AddHandler(fooEvent, value);
        remove => RemoveHandler(fooEvent, value);
    }
}

XAML.

<Window x:Class="WpfApplication3.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication3"
        Title="MainWindow" Height="350" Width="525">
    <Window.Triggers>
        <EventTrigger RoutedEvent="local:MainWindow.foo" />
    </Window.Triggers>
</Window>

编辑:直到重新构建项目之前,同样的解析器错误一直显示。


我没想到尝试那个方法,但它奏效了!难以置信。我原本以为对xaml所做的更改会立即显示出来。我认为我一定做错了什么,因为预览窗口无法显示,提示“无效标记”,而简单地构建项目并不能解决这个问题。我实际上必须要(Clean Solution) --> (Rebuild)来清除错误。谢谢! - Scott Solmer
重启、清理、重建都没用!它可以构建和运行得很完美,但设计师失败了。唉。 - Ciantic

2
<Window.Triggers>
    <EventTrigger RoutedEvent="{x:Static local:MainWindow.foo}" />
</Window.Triggers>

我遇到了相同的问题,但是你提供的所有解决方案对我都不起作用。 但是上面的代码片段确实为我解决了这个问题。

0

我也遇到了同样的问题,但是重建并没有起作用,直到我重新启动了我的工作室。关闭并重新打开项目后,一切正常。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接