【发布时间】:2018-06-01 15:21:36
【问题描述】:
创建了用户控件。控件有一个不支持命令的字段,我决定使用事件触发器来调用命令。但它不起作用。该应用程序遵循 MVVM 模式。告诉我,我做错了什么?
在 UserControl 中为绑定属性创建 DP:
public ICommand EditorFormula {
get { return (ICommand)GetValue(EditorFormulaProperty); }
set { SetValue(EditorFormulaProperty, value); }
}
public static readonly DependencyProperty EditorFormulaProperty =
DependencyProperty.Register("EditorFormula", typeof(ICommand), typeof(FormIndexControl), null);
在我的 UserControl 中创建控件:
<UserControl x:Class="UControls.FormIndexControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:wpfm="clr-namespace:WpfMath.Controls;assembly=WpfMath"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:local="clr-namespace:test"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="200" DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Grid>
<StackPanel>
<wpfm:FormulaControl Formula="{Binding Path=IndexFormula}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseLeftButtonDown">
<i:InvokeCommandAction Command="{Binding Path=EditorFormula}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</wpfm:FormulaControl>
</StackPanel>
</Grid>
</UserControl>
绑定用户控件 XAML:
<uc:FormIndexControl EditorFormula="{Binding DataContext.CommandOpenEditor , RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}"/>
并创建命令。 DelegateCommand 类实现了 ICommand 接口(确实有效):
public class test{
public test(){
CommandOpenEditor = new DelegateCommand(OpenEditorFormula);
}
public ICommand CommandOpenEditor { get; set; }
private void OpenEditorFormula(object obj) {
// He not invoked
}
}
【问题讨论】:
-
尝试调试,看看你的 UC 是否获得了正确的 dataContext