Home > Back-end >  How to bind UWP Control's Methods to a Method or Command in MVVM
How to bind UWP Control's Methods to a Method or Command in MVVM

Time:08-02

I am completely new to MVVM and I am creating an UWP app for keeping track of my software development, I am still learning.

So what I want to make is:

An app that contains single page ->

In MainPage.xaml I have something like this:

<!--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:

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 :

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. 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 ?
  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 ? ( my viewmodel is bind to view using <MainPage.DataContext> and I wanna keep code behind completely empty. )
  3. Where shall I put Data class that can manage load save and edit data to savefile.
  4. 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. And what are services and helpers.
  5. Shall I really use Mvvm for this ?
    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,
    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, I think code-behind
    is better and it keeps things simple.

Please answer these questions I am really struggling in making this app.

CodePudding user response:

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

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.

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 ? ( my viewmodel is bind to view using <MainPage.DataContext> and I wanna keep code behind completely empty. )

Base on the first question, you could detect Page Loaded event and Invoke CommandAction where in the ViewModel. Then loading the file in the viewmodel 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

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. And what are services and helpers.

For mvvm design, model view viewmodel are necessary. 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. We suggest you make sample project with TempleStudio that contains some base service and behaviors.

Shall I really use Mvvm for this ? 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, 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, I think code-behind is better and it keeps things simple.

Your understanding is correct, But Decoupling(mvvm) your code has many benefits, including:

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. 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. 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.

  • Related