문제

I'm trying to understand this concept and it's eluding me.

What is the general concept behind this? I know it's possible, but I'm not totally following how to do this based on my research/own test projects.

I want to avoid code behind at all costs in my View. I want to decouple events such as "PreviewMouseDown" from the View and have them trigger a Command in the ViewModel.

Can anyone give me some basic guidance on how to accomplish this?

Summary:

View (PreviewMouseDown) -> Calls Command in ViewModel (MyPreviewMouseDownCommand)

Thank you

도움이 되었습니까?

해결책

It's all about Commanding and Binding. But I'll encourage you to better use a framework that provides you the plumbing. If you want View first strategy you can you go with MVVM Light as Reed suggested. But, if you want ViewModel first approach (which I personally found to be more simple to understand) then I'll suggest you to use Caliburn Micro.

Anyway, you'll end up using Event to Command or the Interactivity Library (from the Blend SDK) if you want to go code-behind clean.

다른 팁

At risk of being downvoted I don't think this is the worst thing in the world

public void PreviewMouseDown(Object sender, RoutedEventArgs e)
{
    var viewModel= (MyViewModel)DataContext;
    if (viewModel.MyCommand.CanExecute(null))
        viewModel.MyCommand.Execute(null);
}

This is typically handled via some form of Attached Property or (Blend) Behavior.

For example, MVVM Light includes an EventToCommand Behavior which allows you to route any event to an ICommand in XAML, with no code behind added.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top