编程语言
首页 > 编程语言> > c# – 绑定MVVM模式中自定义元素的自定义事件

c# – 绑定MVVM模式中自定义元素的自定义事件

作者:互联网

我正在尝试使用MVVM模式绑定LiveChart的笛卡尔图表元素的“DataClick”事件.

我有这样的Charts.xml:

<ContentControl Grid.Row="0">
        <lvc:CartesianChart x:Name="ContrastChart" Series="{Binding ContrastSeriesCollection}">
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="DataClick">
                    <i:InvokeCommandAction Command="{Binding ChartDataClick}" />
                </i:EventTrigger>
            </i:Interaction.Triggers>
        </lvc:CartesianChart>
    </ContentControl>

这是我的ViewModel上的ICommand ChartDataClick:

        public ICommand ChartDataClick {
        get
        {
            if(_dataClickCommand == null)
            {
                _dataClickCommand = new DelegateCommand( 
                    () => 
                    {
                        MessageBox.Show("Data Clicked!");
                    } 
                    );
            }

            return _dataClickCommand;
        }
    }

如果我为“MouseEnter”切换例如“DataClick”,我会触发我的命令.

所以我假设问题是DataClick是一个自定义事件.

有人知道解决方法吗?
我真的尝试过我能在Google上找到的所有可能有用的东西,但到目前为止还没有…

LiveCharts活动:Events Documentation

解决方法:

EventTrigger没有区别对待.

我们可以通过实现具有自定义路由事件抽头的MyButtonSimple来检查这一点.

我们可以从代码中的处理程序开始

<custom:MyButtonSimple 
    x:Name="mybtnsimple" Tap="mybtnsimple_Tap"
    Content="Click to see Tap custom event work">
</custom:MyButtonSimple>

到ViewModel ICommand

<custom:MyButtonSimple 
    x:Name="mybtnsimple"  
    Content="Click to see Tap custom event work">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="Tap">
            <i:InvokeCommandAction Command="{Binding Command}" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
</custom:MyButtonSimple>

一切都按预期工作

这些触发器的缺点是它们必须放在UIElement引发事件上.
换句话说,他们忽略了Bubbling或Tunneling事件.这就是为什么没有Interaction.Triggers的替代方案:

<Grid custom:MyButtonSimple.Tap="mybtnsimple_Tap">
    <custom:MyButtonSimple 
        x:Name="mybtnsimple"  
        Content="Click to see Tap custom event work">
    </custom:MyButtonSimple>
</Grid>

总而言之,不会在CartesianChart上引发DataClick事件(但是在逻辑树的下方),因此您无法以这种方式处理它.

标签:c,mvvm,wpf,prism,livecharts
来源: https://codeday.me/bug/20190702/1352503.html