MVVM在Silverlight中连接事件处理程序的方法

时间:2012-06-16 19:32:57

标签: wpf silverlight events mvvm prism

在Silverlight / WPF中使用MVVM模式,如何连接事件处理程序?我正在尝试将XAML Click 属性绑定到视图模型中的委托,但无法使其工作。

换句话说,我想替换它:

<Button Content="Test Click" Click="Button_Click" />

其中Button_Click为:

private void Button_Click(object sender, RoutedEventArgs e) 
{ 
    // ...
}

用这个:

<Button Content="Test Click" Click="{Binding ViewModel.HandleClick}" />

其中HandleClick是处理程序。尝试此操作会引发运行时异常:

  

'System.Windows.Data.Binding'类型的对象无法转换为'System.Windows.RoutedEventHandler'类型。

2 个答案:

答案 0 :(得分:4)

MVVM的方法是使用命令和ICommand interfaceButton控件有一个名为Command的属性,它接收ICommand类型的对象

ICommand的常用实现是Prism's DelegateCommand。要使用它,您可以在视图模型中执行此操作:

public class ViewModel
{
    public ICommand DoSomethingCommand { get; private set; }

    public ViewModel()
    {
        DoSomethingCommand = new DelegateCommand(HandleDoSomethingCommand);
    }

    private void HandleDoSomethingCommand()
    {
        // Do stuff
    }
}

然后在XAML中:

<Button Content="Test Click" Command={Binding DoSomethingCommand} />

此外,请确保将viewmodel设置为视图的DataContext。一种方法是在您的视图中使用代码隐藏:

this.DataContext = new ViewModel();
如果您想了解有关MVVM的更多信息,

This article是一个很好的起点。

答案 1 :(得分:0)

答案是在Prism框架中使用Microsoft提供的扩展。使用DLL System.Windows.Interactivity.dll Microsoft.Expression.Interactions.dll ,可以将事件绑定到视图模型中的处理程序方法:

<Button Content="Test Click"
    xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"      
    xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
    >
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="Click">
            <ei:CallMethodAction TargetObject="{Binding ViewModel}" MethodName="HandleClick" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
</Button>
相关问题