1

Ok. I'm following a tutorial to master MVVM Pattern to my app.

I've followed the tutorial quite well, I got to the part of commandings and when I try to apply command to a button it doesnt seem to work at all, my button never disables. I've seen other MVVM sources and my code seems to be fine besides I found this tutorial on internet it was meant for WPF, but it also apply for UWP Windows 10 Apps.

So I'll paste my classes and Xaml views.

this is my Model:

using System.ComponentModel;

namespace MVVMDemo.Model
{
public class Student : INotifyPropertyChanged
{
    private string firstName;
    private string lastName;

    public string FirstName
    {
        get
        {
            return firstName;
        }

        set
        {
            if (firstName != value)
            {
                firstName = value;
                RaisePropertyChanged("FirstName");
                RaisePropertyChanged("FullName");
            }
        }
    }

    public string LastName
    {
        get { return lastName; }

        set
        {
            if (lastName != value)
            {
                lastName = value;
                RaisePropertyChanged("LastName");
                RaisePropertyChanged("FullName");
            }
        }
    }

    public string FullName
    {
        get
        {
            return firstName + " " + lastName;
        }
    }

    public event PropertyChangedEventHandler PropertyChanged = delegate { };

    private void RaisePropertyChanged(string property)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
    }
}
}

The model code I believe has no errors on it. this is my ViewModel:

using MVVMDemo.Model;
using System.Collections.ObjectModel;

namespace MVVMDemo.ViewModel
{
public class StudentViewModel
{
    /*Let’s add a property of MyICommand type in StudentView Model class. 
     * Now we need to construct an instance in the StudentViewModel. We will
     * use the overloaded constructor of MyICommand that takes two parameters.*/
    public MyICommand DeleteCommand { get; set; }

    /*Now add the implementation of OnDelete and CanDelete methods.*/
    public StudentViewModel()
    {
        LoadStudents();
        DeleteCommand = new MyICommand(OnDelete, CanDelete);
    }

    private bool CanDelete()
    {
        //if (SelectedStudent != null)
        //    return true;
        //return false;
        return SelectedStudent != null;
    }

    private void OnDelete()
    {
        Students.Remove(SelectedStudent);
    }

    /*We also need to add a new SelectedStudent so that the user 
     * can delete the Selected Item from ListBox.*/
    private Student _selectedStudent;

    public Student SelectedStudent
    {
        get
        {
            return _selectedStudent;
        }
        set
        {
            _selectedStudent = value;
            DeleteCommand.RaiseCanExecuteChanged();
        }
    }
    public ObservableCollection<Student> Students
    {
        get;
        set;
    }


    public void LoadStudents()
    {
        ObservableCollection<Student> students = new ObservableCollection<Student>();

        students.Add(new Student { FirstName = "Mark", LastName = "Allain" });
        students.Add(new Student { FirstName = "Allen", LastName = "Brown" });
        students.Add(new Student { FirstName = "Linda", LastName = "Hamerski" });

        Students = students;
    }
}
}

This is my ViewModelLocator:

using MVVMDemo.ViewModel;

namespace MVVMDemo.VML
{
public class ViewModelLocator
{
private static StudentViewModel studentViewModel = new StudentViewModel();

    public static StudentViewModel StudentViewModel
    {
        get { return studentViewModel; }
    }
}
}

and at Last this is my View my UserControl StudentView

<UserControl
    x:Class="MVVMDemo.Views.StudentView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:MVVMDemo.Views"
    xmlns:vml="using:MVVMDemo.VML"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    DataContext="{Binding Source={StaticResource mainViewModelLocator}, Path=StudentViewModel}"
    d:DesignHeight="300"
    d:DesignWidth="400">  

<!--We will apply MVVM Using ItemTemplates-->
<UserControl.Resources>
    <DataTemplate x:Key = "studentsTemplate">

        <StackPanel Orientation = "Horizontal">
            <TextBox Text = "{Binding Path = FirstName, Mode = TwoWay}" 
        Width = "100" Margin = "3 5 3 5"/>

            <TextBox Text = "{Binding Path = LastName, Mode = TwoWay}" 
        Width = "100" Margin = "0 5 3 5"/>

            <TextBlock Text = "{Binding Path = FullName, Mode = OneWay}" 
        Margin = "0 5 3 5"/>
        </StackPanel>

    </DataTemplate>
</UserControl.Resources>

<Grid>
    <StackPanel Orientation="Horizontal">
        <!--In StudentView.xaml, we need to add SelectedItem property in a ListBox
        which will bind to the SelectStudent property.-->
        <ListView ItemsSource="{Binding Students}" 
                  ItemTemplate="{StaticResource studentsTemplate}"
                  SelectedItem="{Binding SelectedStudent}"/>

        <Button Content = "Delete"  
                Command="{Binding DeleteCommand}"
                HorizontalAlignment = "Left" 
                VerticalAlignment = "Top" 
                Width = "75"/>
    </StackPanel>        
</Grid>
</UserControl>

I'm applying the viewmodellocator on the app.xaml file at application level:

<Application.Resources>
    <vml:ViewModelLocator x:Key="mainViewModelLocator"/>
</Application.Resources>

and I call my view on the main page like this:

can somebody help me, I've run this code on VS2015 and VS2017 and the Delete button never gets enabled and it also doesnt delete the rows from the listview or listbox i've tried changing them and nothing seems to be different.

I've even had a commanding implemetation without using the relaycommand pattern as it is used here. I would appreciate your help.

Thanks!!!

2 Answers 2

6

Edit : (this is not an answer but another way to do it)

Do you know you can bind methods directly to events with {x:Bind}. You don't need to use ICommand.

XAML

     <Button Grid.Row="4"
      x:Uid="Send"
      VerticalAlignment="Top"
      HorizontalAlignment="Left"
      MinWidth="80"
      Click="{x:Bind ViewModel.SendFeedback}"/>

Code Behind

    public async void SendFeedback()
    {
        // Code
    }

Easier with this way :)

2
  • 1
    Yes I knew that, but x:Bind has some limitations like for example we cant use UpdateSourceTrigger, you cant bind to ElementName, RelativeSource and Source. that why I prefered to stick with Binding sintax. And the behavior you are purposing isnt the same as behavior, with the click event. I rather use event on the code-behind for viewing or styling purposes and maintain the viewmodel strictly to data binding, navigation and validation. Commented Apr 1, 2017 at 20:42
  • @FiratEsmer I was wondering if you would have time to give a suggestion to my somewhat similar post here.
    – nam
    Commented Sep 28, 2019 at 6:28
1

You're missing a line in the setter to raise the property changed notification

public Student SelectedStudent
{
    get
    {
        return _selectedStudent;
    }
    set
    {
        _selectedStudent = value;
        RaisePropertyChanged("SelectedStudent"); // your version of this notifier
        DeleteCommand.RaiseCanExecuteChanged();
    }
}

The above is enough to fix the issue, but, aside from that, you can simply check the private backing field in CanDelete:

return _selectedStudent != null;
4
  • Thanks man!! you answer was enough to solve my issue. the only thing that bothers me, is that it only worked when i checked the private backing field in my CanDelete method. why didnt it work with the public property SelectedStudent??? Hopefully you can answer that doubt, because the example I found at this page: tutorialspoint.com/mvvm/mvvm_view_viewmodel_communication.htm it uses only the public property, I just dont understand it. Commented Apr 1, 2017 at 20:27
  • Never mind man, Now its working with the Public Property, must have been some kind of bug of VS2017. Thanks for your answer, I had added the INotifyPropertyChanged Before but I place it after the DeleteCommand.RaiseCanExecuteChanged(); After I place it before it, then it began working properly. Thanks for the help!!! nice answer. Commented Apr 1, 2017 at 20:35
  • Yes the ViewModel must implement : INotifyPropertyChanged
    – user6996876
    Commented Apr 1, 2017 at 20:42
  • I meant I had added RaisePropertyChanged("SelectedStudent") before command at my setter. thanks for your answer. Commented Apr 1, 2017 at 20:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.