【问题标题】:Binding custom events of custom elements in MVVM Pattern在 MVVM Pattern 中绑定自定义元素的自定义事件
【发布时间】:2016-10-11 12:08:32
【问题描述】:

我正在尝试使用 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;
        }
    }

如果我将例如“DataClick”切换为“MouseEnter”,我的命令就会被触发。

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

有人知道解决方法吗? 我真的尝试了所有可以在 Google 上找到的可以提供帮助的方法,但目前还没有...

LiveCharts 事件:Events Documentation

【问题讨论】:

标签: c# wpf mvvm prism livecharts


【解决方案1】:

EventTrigger 不歧视。

我们可以通过实现MyButtonSimple 来检查这一点,它有一个自定义路由事件Tap

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

<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 上。 换句话说,他们忽略冒泡或隧道事件。这就是为什么没有Interaction.Triggers 替代方案的原因:

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

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

【讨论】:

  • 所以我现在不能按照编码的方式处理这个事件吗?或者你认为有帮手什么的可能吗?如果我更改 LiveCharts 的代码以生成路由的“DataClick”事件会有所不同吗?
猜你喜欢
  • 1970-01-01
  • 2019-09-07
  • 2015-02-15
  • 1970-01-01
  • 2013-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多