简体   繁体   English

如何将 UWP 控件的方法绑定到 MVVM 中的方法或命令

[英]How to bind UWP Control's Methods to a Method or Command in MVVM

I am completely new to MVVM and I am creating an UWP app for keeping track of my software development, I am still learning.我对 MVVM 完全陌生,我正在创建一个 UWP 应用程序来跟踪我的软件开发,我还在学习。

So what I want to make is:所以我想做的是:

An app that contains single page ->包含单页的应用程序 ->

In MainPage.xaml I have something like this:在 MainPage.xaml 我有这样的事情:

<!--MainPage Content-->
<Grid>
    <!--For SearchBox-->
    <AutoSuggestBox x:Name="SearchBox"/>

    <!--For Adding Item-->
    <AppBarButton x:Name="AddAppButton"/>

    <!--Listview that contains main data-->
    <ListView x:Name="AppsListView"/>

    <!--This is DataTemplate of listview-->
    <DataTemplate>
        <Grid>
            <!--Icon of App-->
            <Image/>
            <!--Name of App-->
            <TextBlock/>
            <!--For Editing Item-->
            <AppBarButton/>
            <!--For Deleting Item-->
            <AppBarButton/>
        </Grid>
    </DataTemplate>
</Grid>

In Model I have something like this:在 Model 我有这样的事情:

public class DevApp
{
    public string name { get; set; } // For App Name
    public string Iconsource { get; set; } // For App Icon
    public ICommand EditCommand; // For Edit AppBarButton
    public ICommand DeleteCommand; // For Delete AppBarButton
}

In ViewModel, something like:在 ViewModel 中,类似:

public class ViewModel
{
    // For ItemSource of ListView
    public ObservableCollection<DevApp> DevApps = new ObservableCollection<DevApp>();

    // For Add AppBarButton
    public ICommand AddCommand;
}

Now this is me first time trying to create a neat and clean Mvvm app.现在这是我第一次尝试创建一个整洁干净的 Mvvm 应用程序。 Now I have this question:现在我有这个问题:

  1. I know how to bind command to button or AppBarButton but how am I supposed to bind a Methods of a Xaml Control such as Listview's SelectionChanged() or AutoSuggestBox's TextChanged() Methods to ViewModel?我知道如何将命令绑定到按钮或 AppBarButton,但我应该如何将 Xaml 控件的方法(例如 Listview 的 SelectionChanged() 或 AutoSuggestBox 的 TextChanged() 方法)绑定到 ViewModel?
  2. How can I Load Data from save file?如何从保存文件中加载数据? As there is no InitializeComponent() in ViewModel like in CodeBehind to start from, where shall I pull LoadData() method which loads data to ListView?由于 ViewModel 中没有像 CodeBehind 中那样的 InitializeComponent() 从哪里开始,我应该从哪里拉出将数据加载到 ListView 的 LoadData() 方法? ( my viewmodel is bind to view using <MainPage.DataContext> and I wanna keep code behind completely empty. ) (我的视图模型使用 <MainPage.DataContext> 绑定到视图,我想让代码完全为空。)
  3. Where shall I put Data class that can manage load save and edit data to savefile.我应该把可以管理加载保存和编辑数据到保存文件的数据 class 放在哪里。
  4. How shall I distribute responsibilities among classes?我应该如何在班级之间分配职责?
    I have seen people using mvvm and they create files like:我见过有人使用 mvvm,他们创建的文件如下:
    services, helpers, contracts, behaviours, etc.服务、助手、合同、行为等。
    and I have seen same thing in Windows Community Toolkit Sample App Is it required for Mvvm.我在 Windows 社区工具包示例应用程序中看到了同样的事情 Mvvm 是否需要它。 And what are services and helpers.什么是服务和助手。
  5. Shall I really use Mvvm for this?我真的应该为此使用 Mvvm 吗?
    I tried using Mvvm in this just for curiosity but like我只是出于好奇而尝试在此使用 Mvvm 但喜欢
    ITS BEEN 1 MONTH I AM MAKKING THIS APP, but it gets messed up again and again,我正在制作这个应用程序已经 1 个月了,但它一次又一次地搞砸了,
    If I used Code Behind it would have been done in few days.如果我使用 Code behind,它会在几天内完成。 BY time now I realize that Mvvm is good at data bind in complex apps but到现在为止,我意识到 Mvvm 擅长复杂应用程序中的数据绑定,但是
    When it comes to simple things like a simple app with listview, I think code-behind当谈到简单的事情时,比如一个简单的应用程序列表视图,我认为代码隐藏
    is better and it keeps things simple.更好,它使事情变得简单。

Please answer these questions I am really struggling in making this app.请回答这些问题,我在制作这个应用程序时真的很努力。

I know how to bind command to button or AppBarButton but how am I supposed to bind a Methods of a Xaml Control such as Listview's SelectionChanged() or AutoSuggestBox's TextChanged() Methods to ViewModel我知道如何将命令绑定到按钮或 AppBarButton 但我应该如何将 Xaml 控件的方法(例如 Listview 的 SelectionChanged() 或 AutoSuggestBox 的 TextChanged() 方法绑定到 ViewModel

You could bind SelectionChanged with command by using Xaml Behavior InvokeCommandAction , or using x:bind markup extension to bind a method, for more please refer to this link .您可以通过使用 Xaml Behavior InvokeCommandAction或使用 x:bind 标记扩展来绑定方法,将 SelectionChanged 与命令绑定,有关更多信息,请参阅此链接

How can I Load Data from save file?如何从保存文件中加载数据? As there is no InitializeComponent() in ViewModel like in CodeBehind to start from, where shall I pull LoadData() method which loads data to ListView?由于 ViewModel 中没有像 CodeBehind 中那样的 InitializeComponent() 从哪里开始,我应该从哪里拉出将数据加载到 ListView 的 LoadData() 方法? ( my viewmodel is bind to view using <MainPage.DataContext> and I wanna keep code behind completely empty. ) (我的视图模型使用 <MainPage.DataContext> 绑定到视图,我想让代码完全为空。)

Base on the first question, you could detect Page Loaded event and Invoke CommandAction where in the ViewModel.基于第一个问题,您可以在 ViewModel 中检测到 Page Loaded 事件并Invoke CommandAction Then loading the file in the viewmodel LoadedCommand .然后在视图LoadedCommand中加载文件。

<i:Interaction.Behaviors>
    <ic:EventTriggerBehavior EventName="Loaded">
        <ic:InvokeCommandAction Command="{x:Bind ViewModel.LoadedCommand}" />
    </ic:EventTriggerBehavior>
</i:Interaction.Behaviors>

Where shall I put Data class that can manage load save and edit data to savefile我应该把可以管理加载保存和编辑数据到保存文件的数据 class 放在哪里

The better place that savefile is current app's local folder, and it have full access permission, please refer to Work with files document.保存文件最好是当前应用的本地文件夹,并且有完全访问权限,请参考使用文件文档。

How shall I distribute responsibilities among classes?我应该如何在班级之间分配职责? I have seen people using mvvm and they create files like: services, helpers, contracts, behaviours, etc. and I have seen same thing in Windows Community Toolkit Sample App Is it required for Mvvm.我见过人们使用 mvvm,他们创建的文件如下:服务、助手、合同、行为等,我在 Windows 社区工具包示例应用程序中看到了同样的事情 Mvvm 是否需要它。 And what are services and helpers.什么是服务和助手。

For mvvm design, model view viewmodel are necessary.对于 mvvm 设计, model view viewmodel是必需的。 And it is not necessary to make services, helpers, contracts, behaviours , it should base on your design.并且没有必要制作服务、助手、契约、行为,它应该基于你的设计。 For example if you want to make NavigateService, you need make static service class to manager current app's navigation.例如,如果您想制作 NavigateService,您需要制作 static 服务 class 来管理当前应用程序的导航。 We suggest you make sample project with TempleStudio that contains some base service and behaviors.我们建议您使用TempleStudio 制作包含一些基本服务和行为的示例项目。

Shall I really use Mvvm for this?我真的应该为此使用 Mvvm 吗? I tried using Mvvm in this just for curiosity but like ITS BEEN 1 MONTH I AM MAKKING THIS APP, but it gets messed up again and again.出于好奇,我尝试在其中使用 Mvvm,但就像我正在制作这个应用程序已经 1 个月一样,但它一次又一次地搞砸了。 If I used Code Behind it would have been done in few days, BY time now I realize that Mvvm is good at data bind in complex apps but When it comes to simple things like a simple app with listview.如果我使用 Code behind,它会在几天内完成,现在我意识到 Mvvm 擅长复杂应用程序中的数据绑定,但是当涉及到简单的事情时,比如带有 listview 的简单应用程序。 I think code-behind is better and it keeps things simple.我认为代码隐藏更好,它使事情变得简单。

Your understanding is correct, But Decoupling(mvvm) your code has many benefits, including:您的理解是正确的,但是Decoupling(mvvm)您的代码有很多好处,包括:

Enabling an iterative, exploratory coding style.启用迭代的、探索性的编码风格。 Change that is isolated is less risky and easier to experiment with.孤立的变化风险较小,更容易进行试验。 Simplifying unit testing.简化单元测试。 Code units that are isolated from one another can be tested individually and outside of production environments.相互隔离的代码单元可以在生产环境之外单独测试。 Supporting team collaboration.支持团队协作。 Decoupled code that adheres to well-designed interfaces can be developed by separate individuals or teams, and integrated later.遵循精心设计的界面的解耦代码可以由单独的个人或团队开发,并在以后集成。 Improving maintainability.提高可维护性。 Fixing bugs in decoupled code is less likely to cause regressions in other code.修复解耦代码中的错误不太可能导致其他代码中的回归。 In contrast with MVVM, an app with a more conventional "code-behind" structure typically uses data binding for display-only data, and responds to user input by directly handling events exposed by controls.与 MVVM 相比,具有更传统的“代码隐藏”结构的应用程序通常对仅显示数据使用数据绑定,并通过直接处理控件公开的事件来响应用户输入。 The event handlers are implemented in code-behind files (such as MainPage.xaml.cs), and are often tightly coupled to the controls, typically containing code that manipulates the UI directly.事件处理程序在代码隐藏文件(例如 MainPage.xaml.cs)中实现,并且通常与控件紧密耦合,通常包含直接操作 UI 的代码。 This makes it difficult or impossible to replace a control without having to update the event handling code.这使得在不更新事件处理代码的情况下替换控件变得困难或不可能。 With this architecture, code-behind files often accumulate code that isn't directly related to the UI, such as database-access code, which ends up being duplicated and modified for use with other pages.使用这种架构,代码隐藏文件通常会累积与 UI 不直接相关的代码,例如数据库访问代码,这些代码最终会被复制和修改以供其他页面使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM