2009-04-30 20 views
8

Ví dụ RoutedCommand sau đây hoạt động.Làm thế nào để di chuyển trình xử lý RoutedCommand của tôi từ View-codebehind sang ViewModel?

Tuy nhiên, việc xử lý cho nút thực hiện lệnh nằm trong mã số của khung nhìn. Cách tôi hiểu MVVM, nó phải ở trong ViewModel.

Tuy nhiên, khi tôi di chuyển phương thức sang ViewModel (và thay đổi thành công khai), tôi gặp lỗi "ManagedCustomersView không chứa định nghĩa về OnSave". Ngay cả khi tôi thay đổi tham số thứ hai RoutedCommand thành typeof (ManageCustomersViewModel), tôi cũng gặp lỗi tương tự.

Làm cách nào tôi có thể di chuyển trình xử lý lệnh từ View-codebehind sang ViewModel?

ManageCustomersView.xaml:

<UserControl.CommandBindings> 
    <CommandBinding Command="local:Commands.SaveCustomer" Executed="OnSave"/> 
</UserControl.CommandBindings> 
... 
<Button Style="{StaticResource formButton}" 
    Content="Save" 
    Command="local:Commands.SaveCustomer" 
    CommandParameter="{Binding Id}"/> 

ManageCustomersView.xaml.cs:

private void OnSave(object sender 
        , System.Windows.Input.ExecutedRoutedEventArgs e) 
{ 
    int customerId = ((int)e.Parameter); 
    MessageBox.Show(String.Format 
     ("You clicked the save button for customer with id {0}.", customerId)); 
} 

Commands.cs:

using System.Windows.Input; 
using TestDynamicForm123.View; 

namespace TestDynamicForm123 
{ 
    public class Commands 
    { 
     public static RoutedCommand SaveCustomer = 
      new RoutedCommand("SaveCustomer", typeof(ManageCustomersView)); 
    } 
} 

Trả lời

8

Bạn sẽ phơi bày một thuộc tính khỏi ViewModel của bạn tham chiếu đến lệnh.

class MyViewModel 
{ 
    public RoutedCommand SaveCmd{ get{ return Commands.SaveCustomer; } } 
} 

Sau đó, trong XAML

<Button Command="{Binding SaveCmd}" /> 

Tuy nhiên bạn có thể tìm thấy nó dễ dàng hơn để sử dụng RelayCommand để bạn có thể xác định logic lệnh thực tế trong mô hình của bạn là tốt.

+0

hmm, tôi đã thêm hai bit mã đó và bây giờ nhấp vào nút của tôi không làm gì cả. Tôi có thể đưa ra các UserControl.CommandBindings hoặc để lại nó, nhưng điều đó không có hiệu lực. Không có gì trong đầu ra. Tôi cần thay đổi gì khác? –

+0

Hãy xem RoutedCommand giúp dễ dàng hơn nhiều. Bạn có thể trả về RoutedCommand mới (p => MessageBox.Show ("Saving.")) Tất cả từ bên trong model view của bạn. –

+0

Tôi nghĩ người bình luận trước đó có nghĩa là RelayCommand. –

Các vấn đề liên quan