كيفية نقل RoutedCommand معالج من العرض-codebehind إلى ViewModel?
-
03-07-2019 - |
سؤال
التالية RoutedCommand سبيل المثال يعمل.
ومع ذلك ، فإن التعامل مع الزر الذي ينفذ الأمر في codebehind من رأي.الطريق وأنا أفهم MVVM ، يجب أن تكون في ViewModel.
ومع ذلك ، عندما تتحرك طريقة ViewModel (وتغييره إلى الجمهور) ، أحصل على خطأ "ManagedCustomersView لا تحتوي على تعريف OnSave".حتى إذا قمت بتغيير RoutedCommand المعلمة الثانية إلى typeof(ManageCustomersViewModel), أحصل على نفس الخطأ.
كيف يمكنني نقل الأوامر معالج من رأي-codebehind إلى 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));
}
الأوامر.cs:
using System.Windows.Input;
using TestDynamicForm123.View;
namespace TestDynamicForm123
{
public class Commands
{
public static RoutedCommand SaveCustomer =
new RoutedCommand("SaveCustomer", typeof(ManageCustomersView));
}
}
المحلول
سوف تعرض الممتلكات الخاصة بك قبالة ViewModel مراجع الأمر.
class MyViewModel
{
public RoutedCommand SaveCmd{ get{ return Commands.SaveCustomer; } }
}
ثم في XAML
<Button Command="{Binding SaveCmd}" />
ومع ذلك قد تجد أنه من الأسهل استخدام RelayCommand بحيث يمكنك تحديد القيادة الفعلية المنطق في النموذج الخاص بك وكذلك.
لا تنتمي إلى StackOverflow