Should ItemSource and BindingContext both be set when using MVVM (Xamarin.Froms ListView)? - mvvm

Model:
public class Question : INotifyPropertyChanged
{
private float? _answer;
public float? Answer
{
get => _answer;
set
{
_answer = value;
NotifyPropertyChanged();
}
}
protected void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
View model:
public class QuestionViewModel
{
private ObservableCollection<Question> _questions;
public ObservableCollection<Question> Questions
{
get => _questions;
set
{
if (_questions != value)
{
_questions = value;
}
}
}
}
XAML:
<ListView x:Name="ListViewQuestions" SelectionMode="Single" HasUnevenRows="True" HeightRequest="250" VerticalOptions="FillAndExpand">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Entry x:Name="EntryAnswer" Text="{Binding Answer,Mode=TwoWay}" Keyboard="Numeric" FontSize="Medium" VerticalOptions="End"
HorizontalOptions="FillAndExpand" Grid.Row="0" Grid.Column="1" >
<Entry.Behaviors>
<behaviors:EntryMaxValueBehavior MaxValue="{Binding MaxVal}" BindingContext="{Binding BindingContext, Source={x:Reference EntryAnswer}}" />
<behaviors:EntryMinValueBehavior MinValue="{Binding MinVal}" BindingContext="{Binding BindingContext, Source={x:Reference EntryAnswer}}" />
</Entry.Behaviors>
</Entry>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
In my page OnAppearing method, I set the ListViewQuestions like this:
var questions = await DataStore.GetQuestions(_inspection.Id);
var questionsViewModel = new QuestionViewModel { Questions = new ObservableCollection<Question>(questions) };
ListViewQuestions.ItemsSource = null;
ListViewQuestions.ItemsSource = questionsViewModel.Questions;
However, when values are entered into EntryAnswer, the setter in the Question model is not called, as I would expect. I thought that maybe this was because the BindingContext for the ListView needed to be set, so I set it like this:
ListViewQuestions.BindingContext = questionsViewModel;
However, the setter in the Question model is still not called. I also tried implementing INotifyPropertyChanged in the QuestionViewModel, but still no joy. I checked that the ObservableCollection in the View Model is set correctly, with actual data, and it is. Can anyone spot what might be going wrong here?
Edit 1: I also tried not setting the ItemSource, but only setting the ListViewQuestions.BindingContext to the view model, but then the ListView was not being populated with any data.

Here is how this works together.
The BindingContext is the object that will be the scope for whatever bindings that are in the page or it's children, unless you specify a different context for a certain child object, but let's not overcomplicate things for now.
This means, that when you have set the BindingContext, all Bindings will now start looking into the object referenced in the BindingContext. In your case, you set the BindingContext to an instance of QuestionViewModel.
You want your ListView, to get its items from the QuestionViewModel.Questions property. So, you set a binding like this:
<ListView x:Name="ListViewQuestions" ItemsSource="{Binding Questions}" ...>.
Questions needs to be a public property in the BindingContext, in our case QuestionViewModel. You got this right already.
Now, whenever you assign something to Questions this should also propagate to your ListView because of the binding.
Inside your ListView you are using a ViewCell, now note, that the scope does change here. Each cell represents an instance of an object inside the ItemsSource. In our case, each cell will hold a Question. You are using this:
<Entry x:Name="EntryAnswer" Text="{Binding Answer,Mode=TwoWay}" ...>
This means Answer needs to be a public property inside Question. You got this right already.
When you implement it like this, basically the only thing you do is fill your view model and assign that to the BindingContext of your page. If you are using an MVVM framework, this might happen automatically.
At some point, you might run into some trouble that the UI doesn't update and you will have to implement the INotifyPropertyChanged interface. Have a close look at what object doesn't update on screen and implement the interface on that object along with the needed plumbing, but from what I can see in this code, this isn't needed right now. And besides, you have implemented it the right way in your Question right now.
I hope this makes sense! It's a bit hard to wrap your head around the first time, but once you get the swing of it, it is pretty easy!

In your Answer Setter try:
set
{
float? temp = null;
if(float.TryParse(value, out temp)
{
_answer = temp;
NotifyPropertyChanged("Answer");
}
}
It seems like for this to work though your setter would have to be called, and you indicate that it is not, so I think it must be the min, max binding where this is kicking out the error. For now perhaps get rid of that and see if the setter will get called.
In WPF using a converter is typical and I think will work with the Xamarin as well. See this for a good example of how to implement IValueConverter.

Related

UWP Data-Binding not working with ViewModel

Fairly new to UWP and MVVM I came across a problem which might seem obvious to many of you.
In my project I have 3 folders named Views, ViewModels and Models which include some files as seen in the image bellow:
Can't upload image yet (reputation):
http://i.imgur.com/42f5KeT.png
The problem:
I am trying to implement MVVM. I have searched hours for articles and videos but it seems I am always missing something. I have some bindings in the LoginPage.xaml which I then modify in a class inside Models/LoginPageModel.cs. I have an INotifyPropertyChanged class in my LoginPageViewModel.cs where every time a property changes in my LoginPageModel.cs I want the INotifyPropertyChanged class to trigger which will then change the property in the LoginPage.xaml View. Below I have the content of those files.
This is a sample of my LoginPageModel.cs code:
using System;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace App_Name.Models
{
class LoginPageModel
{
private NotifyChanges notify;
public async void LogIn()
{
if (something is true)
notify.LoginUIVisibility = Visibility.Visible;
}
}
}
This is my LoginPageViewModel.cs:
using System.ComponentModel;
using System.Runtime.CompilerServices;
using Windows.UI.Xaml;
namespace App_Name.ViewModels
{
public class NotifyChanges : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private Visibility loginUIVisibility = Visibility.Collapsed;
public Visibility LoginUIVisibility
{
get
{
return loginUIVisibility;
}
set
{
if (value != loginUIVisibility)
{
loginUIVisibility = value;
NotifyPropertyChanged("LoginUIVisibility");
}
}
}
}
}
Here is an example of LoginPage.xaml:
<Page
x:Class="App_Name.LoginPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App_Name"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:vm="using:App_Name.ViewModels"
mc:Ignorable="d">
<Page.DataContext>
<vm:NotifyChanges/>
</Page.DataContext>
<StackPanel Visibility="{Binding LoginUIVisibility}">
Here is my LoginPage.xaml.cs:
namespace App_Name
{
public sealed partial class LoginPage : Page
{
private LoginPageModel login;
public LoginPage()
{
InitializeComponent();
login.LogIn();
}
}
}
I don't know why this is not working. Bindings used not to work, but now at runtime it gives me an unhandled exception and I think it has to do with not assigning any value to the private NotifyChanges notify and private LoginPageModel login objects, but I don't know what. Thanks everyone for your time in advance!
Please if you need clarifications for my question just write a comment. Thank you!
I am trying to implement MVVM.
And you're not getting it right yet. Forget about the Bindings for a moment, let's focus on the architecture.
Going down the acronym, you need
a Model. It supports your business logic and usually is defined by your backend (database). It should not depend on (be aware of) the Views or ViewModels. A lightweight UWP app could do without a Model layer.
a View. This is the XAML part that we like to keep as simple as possible, a.o. reasons because it's hardest to test.
a ViewModel. It's purpose is to serve the View. It should contain properties and commands the View can directly bind to. It does as much conversion and aggregation as possible to keep the View light. It usually relies on (0 or more) Models or Services.
Given this, it is not the case that you should always have 1 Model for 1 ViewModel. A ViewModel could use multiple Models, or none.
It is clear that your LoginPageModel.Login() is in the wrong place. Login() should be a method (Command) on your ViewModel.
Your story should go like this:
I want a LoginView
So I need to support it with a LoginViewModel, implementing INPC
The ViewModel probably needs to use a LoginService or a UserModel. But it would only need a Model instance after a successful login. A LoginModel doesn't sound right.
Have a look at Template10 to get started with View, ViewModel and a thread-safe BindableBase.
You could also look a the picture over here for a full (over the top maybe) layout of MVVM.
And here is the call for change in the main class:
NotifyChanges notifyChanges = new NotifyChanges();
notifyChanges.LoginUIVisibility = Visibility.Visible;
You have instantiated notifyChanges in the XAML file by adding <vm:NotifyChanges/>. And add a binding to StackPanel by using <StackPanel Visibility="{Binding LoginUIVisibility}">. But you created a new notifyChanges, and you did not bind the new notifyChanges to StackPanel. So it won't work. You could initialize viewModel just like following code.
MainPage
private LoginViewModel viewModel;
public MainPage()
{
this.InitializeComponent();
viewModel = this.DataContext as LoginViewModel;
}
private void showDetail_Click(object sender, RoutedEventArgs e)
{
viewModel.LoginUIVisibility = Visibility.Visible;
}
MainPage.xaml
<Page.DataContext>
<vm:LoginViewModel />
</Page.DataContext>
<StackPanel Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Button x:Name="loginButon" Content="Login" Visibility="{Binding LoginUIVisibility}" />
<Button x:Name="showDetail" Content="Show" Click="showDetail_Click" />
</StackPanel>

Best practice MVVM navigation using Master Detail page?

I want to follow the MVVM pattern as much as possible, but I don't know if I am doing the navigation quite well. Note that I am using a MasterDetail page and I want to maintain the Master page, changing only the Detail side when I navigate.
Here is the way I navigate from my ViewModel. In this example, from ViewModelOne to ViewModelTwo:
public class ViewModelOne : ViewModelBase
{
private void GoToViewTwo()
{
var viewTwo = new ViewTwo(new ViewModelTwo());
((MasterView)Application.Current.MainPage).NavigateToPage(viewTwo);
}
}
MasterView implementation:
public class MasterView : MasterDetailPage
{
public void NavigateToPage(Page page)
{
Detail = new NavigationPage(page);
IsPresented = false;
}
}
ViewTwo implementation:
public partial class ViewTwo : PageBase
{
public MenuView(ViewModelTwo vm)
: base(vm)
{
InitializeComponent();
}
}
PageBase implementation:
public class PageBase : ContentPage
{
public PageBase(ViewModelBase vmb)
{
this.BindingContext = vmb;
}
}
Is this the best approach (and best performance) for do the navigation? When I do some navigations, the app starts to run slower and maybe there is something I am not doing fine.
Is this the best approach for do the navigation showing always a MasterDetail page?
Thanks.
I think you're certainly on the right track, however there are a few issues here:
Firstly, you should not be instantiating Views in your view model. As soon as your View Model becomes aware of the view, then you've pretty much broken the pattern.
var viewTwo = new ViewTwo(new ViewModelTwo());
Your view creation should be the responsibility of the master view. In fact, you don't even need to worry about creating views, as you can use a DataTemplate for that. I'll explain that later.
Firstly, we need to separate your View Models from the Views, here is what I propose:
You'll need some kind of base class or interface for your view models in order to keep things generic, you'll see why in a moment. Let's start out with a simple example:
public abstract class ViewModel : INotifyPropertyChanged
{
public event EventHandler OnClosed;
public event EventHandler OnOpened;
//Don't forget to implement INotifyPropertyChanged.
public bool IsDisplayed { get; private set; }
public void Open()
{
IsDisplayed = true;
//TODO: Raise the OnOpened event (Might be a better idea to put it in the IsDisplayed getter.
}
public void Close()
{
IsDisplayed = false;
//TODO: Raise the OnClosed event.
}
}
This of course is a very simple base view model, you can extend on this later, the main reason for this is to allow you to create a master view model which will be responsible for displaying your current page. Here's a simple example of a master view model:
public class MasterViewModel : INotifyPropertyChanged
{
//Don't forget to implement INotifyPropertyChanged.
public ViewModel CurrentPage { get; private set; }
public MasterViewModel()
{
//This is just an example of how to set the current page.
//You might want to use a command instead.
CurrentPage = new MovieViewModel();
}
//TODO: Some other master view model functionality, like exiting the application.
}
Please note that INotifyPropertyChanged would probably be better in some kind of base class, instead of having to re-implement the same code over and over.
Now the MasterViewModel is pretty simple, it just holds the current page, however the purpose of having the master is to allow for application level code to be executed, like closing the app, that way you're keeping this logic away from your other view models.
Right, now onto the good stuff.
Your detail has a relationship to it's parent, therefore it would make sense to say that it is the responsibility of the parent to manage it. In this case, your master-detail view model would look something like this:
public class MovieViewModel : ViewModel
{
protected PickGenreViewModel ChildViewModel { get; private set; }
public MovieViewModel()
{
ChildViewModel = new PickGenreViewModel();
//TODO: Perhaps subscribe to the closed event?
}
//Just an example but an important thing to note is that
//this method is protected because it's the MovieViewModel's
//responsibility to manage it's child view model.
protected void PickAGenre()
{
ChildViewModel.Open();
}
//TODO: Other view model functionality.
}
So, now we've got some kind of view model structure here, I bet you're asking "What about the views?", well, that's where the DataTemplate comes in.
In WPF, it's possible to assign a view to a Type, for example, you can assign the MovieView to the MovieViewModel in XAML, like this:
xmlns:Views="clr-namespace:YourNamespace.Views"
xmlns:ViewModels="clr-namespace:YourNamespace.ViewModels"
...
<DataTemplate DataType="{x:Type ViewModels:MovieViewModel}">
<Views:MovieView/>
</DataTemplate>
Ok great!, now to get the Master View to actually display the current page's view, you simply need to create a ContentPresenter, and bind it's Content to the CurrentPage. Your Master View will look something like this:
<Window
...
xmlns:ViewModels="clr-namespace:YourNamespace.ViewModels">
<Window.DataContext>
<ViewModels:MasterViewModel/>
</Window.DataContext>
<Grid>
<ContentPresenter Content="{Binding CurrentPage}"/>
</Grid>
To extend this further, it's not only the MasterView that needs to contain a ContentPresenter for it's child, it is also the MovieView which needs one for it's child PickGenreViewModel. You can use the same method again:
<Grid>
<!-- The main view code for the movie view -->
...
<Border Visibility="{Binding ChildViewModel.IsDisplayed, Converter=...">
<ContentPresenter Content="{Binding ChildViewModel}"/>
</Border>
</Grid>
Note: Use a boolean to Visibility converter to determine whether to display the child content.
Using this method you don't have to worry about instantiating any views, as the DataTemplate and ContentPresenter handles that for you, all you need to worry about is mapping the view models to the appropriate view.
Phew! That was a lot to take in.
The main points to take away from this are:
You shouldn't be creating views in your view models, remember, UI is UI, Data is Data.
View model responsibilities lie with whoever owns them, for a parent-child relationship, it makes sense to let the parent manage the child, as opposed to a view model manager.
A final note is that there are certainly more than one other ways of achieving this, as I just mentioned, some kind of view and view model manager to be responsible for creating/removing views and view models.

How can I bind source MediaCapture to CaptureElement using Caliburn.Micro?

On Windows Phone 8.1, I am using the Caliburn.Micro view-model-first approach, but as the view model cannot have any knowledge of the view, I cannot see how I can bind a MediaCapture object to a CaptureElement in the view.
I had the same problem. I'm using MVVM Light with Windows Phone 8.1 WinRT (Universal Apps).
I used ContentControl and binded to CaptureElement:
<ContentControl HorizontalAlignment="Left"
Width="320" Height="140" Content="{Binding CaptureElement}"/>
CaptureElement and MediaCapture are properties in my ViewModel:
private MediaCapture _mediaCapture;
public MediaCapture MediaCapture
{
get
{
if (_mediaCapture == null) _mediaCapture = new MediaCapture();
return _mediaCapture;
}
set
{
Set(() => MediaCapture, ref _mediaCapture, value);
}
}
private CaptureElement _captureElement;
public CaptureElement CaptureElement
{
get
{
if (_captureElement == null) _captureElement = new CaptureElement();
return _captureElement;
}
set
{
Set(() => CaptureElement, ref _captureElement, value);
}
}
And next I call ConfigureMedia() in ViewModel's constructor:
async void ConfigureMedia()
{
await MediaCapture.InitializeAsync();
CaptureElement.Source = MediaCapture;
await MediaCapture.StartPreviewAsync();
}
It's important to firstly initialize MediaCapture, next set Source and finally StartPeview. For me it works :)
If you're trying to keep strict view / view model separation then there are couple of possibilities.
Have you tried straight binding?
<CaptureElement Source="{Binding SomeMediaCapture}" />
If that doesn't work another one is create your own attached property that you could put on CaptureElement. When that property is set you can set the source yourself.
<CaptureElement custom:CaptureHelper.Source="{Binding SomeMediaCapture}" />
Here's a sample of doing some similar with web view and creating an html binding.
The way I tend to do this though is create an interface abstracting the view (say ICaptureView) that the view implements.
I can then cast the view held by the view model
var captureView = (ICaptureView) GetView();
where ICaptureView implements a SetCaptureSource method. This way it's still testable as you can attach a mock ICaptureView to the view model for testing.
Adding to Hawlett's answer, I had to do a little bit more to get the camera displaying correctly. I have changed ConfigureMedia() to be:
private async void ConfigureMedia()
{
_deviceInformationCollection = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
await MediaCapture.InitializeAsync(new MediaCaptureInitializationSettings
{
VideoDeviceId = _deviceInformationCollection[_deviceInformationCollection.Count - 1].Id
// The rear-facing camera is the last in the list
});
MediaCapture.VideoDeviceController.PrimaryUse = CaptureUse.Photo;
MediaCapture.SetPreviewRotation(VideoRotation.Clockwise90Degrees);
CaptureElement.Source = MediaCapture;
CaptureElement.Stretch = Stretch.UniformToFill;
await MediaCapture.StartPreviewAsync();
}
I used ContentControl and bound to CaptureElement and It works for me but only the first time. If I navigate to another page and I come back to camera's page I can't see camera preview. I don't call method as StopPreviewAsync() I only navigate to another page.

MVVM View event Viewmodel command binding

I'm looking for a good (read: simple) example on how to implement event aggregators with Prism. I've never used Prism and I'm also quite new to MVVM itself.
I have a WPF canvas as a View and I want to handle the MouseUp event on the canvas in the Viewmodel. Now the powers that be at our organization wants me to use Prism, and apparently Prism recommends using event aggregators, which is why I need a sample to get me started.
all you need for this is the EventToCommand behavior from MVVMLight or from System.Windows.Interactivity (Blend SDK). i would recommend you to take the MVVMLight version because it has some usefull specials:)
<Canvas>
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseUp" >
<i:InvokeCommandAction Command="{Binding YourMouseUpViewModelCommand}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Canvas>
EventAggregator from Prism i mostly used for decoupled Viewmodel to Viewmodel communication.
I didn't know PRISM's EventAggregator allowed for event->command binding.
Another option for you in this case is using a "behavior". Here's a decent overview Behaviors: http://wpftutorial.net/Behaviors.html. You can ignore the Blend part of the tutorial; the important part is that you have at least the Blend 3 SDK installed. Here's how I did this:
public class ButtonDoubleClickCommandBehavior : Behavior<Button>
{
public ICommand DoubleClickCommand
{
get { return (ICommand)GetValue(DoubleClickCommandProperty); }
set { SetValue(DoubleClickCommandProperty, value); }
}
public static readonly DependencyProperty DoubleClickCommandProperty =
DependencyProperty.Register("DoubleClickCommand", typeof(ICommand), typeof(ButtonDoubleClickCommandBehavior));
protected override void OnAttached()
{
this.AssociatedObject.MouseDoubleClick += AssociatedObject_MouseDoubleClick;
}
protected override void OnDetaching()
{
if (this.AssociatedObject != null)
{
this.AssociatedObject.MouseDoubleClick -= AssociatedObject_MouseDoubleClick;
}
}
void AssociatedObject_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
if (DoubleClickCommand != null && DoubleClickCommand.CanExecute(null))
{
DoubleClickCommand.Execute(null);
}
}
}
You could add another dependency property to the behavior to bind a command parameter so you can execute the command with that parameter; I just used null in my example.
And my XAML:
<Button Content="{Binding Path=Description}" VerticalAlignment="Center" HorizontalAlignment="Stretch" Template="{StaticResource TextBlockButtonTemplate}" Style="{StaticResource ZynCommandButton}" Tag="DescriptionButton">
<e:Interaction.Behaviors>
<ZViewModels:ButtonDoubleClickCommandBehavior DoubleClickCommand="{Binding Path=ItemDescriptionCommand}"/>
</e:Interaction.Behaviors>
</Button>
A more generic way using behaviors is proposed at AttachedCommandBehavior V2 aka ACB and it even supports multiple event-to-command bindings,
Here is a very basic example of use:
<Border local:CommandBehavior.Event="MouseDown"
local:CommandBehavior.Command="{Binding DoSomething}"
local:CommandBehavior.CommandParameter="From the DarkSalmon Border"
/>

How do I use grouping using Collection View MVVM?

I'm fairly new to MVVM, and I have recently started a project cleaning up my codebehind and bit by bit I am moving everything to Model and ViewModel.
My problem is, now, how do you use grouping using Collection View without any code behind? I thought I had figured it out, after reading answers to similar questions here on Stackoverflow, but I still can't get it to work. Probably a silly mistake, but I would be very grateful if somebody could have a look at my code and let me know what they think. All feedback is great feedback, I really want to become a good programmer :)
The list is btw of the type ObservableCollection in the Menu class.
<CollectionViewSource x:Key="foods" Source="{Binding Items}">
<CollectionViewSource.GroupDescriptions>
<PropertyGroupDescription PropertyName="Category"/>
</CollectionViewSource.GroupDescriptions>
</CollectionViewSource>
<ListBox x:Name="selectedMenuItem" Foreground="White" Grid.Column="0" Grid.Row="1" ItemsSource="{Binding Source={StaticResource foods}}"
DisplayMemberPath="Name" Background="{x:Null}" BorderThickness="0">
<ListBox.GroupStyle>
<x:Static Member="GroupStyle.Default"/>
</ListBox.GroupStyle>
</ListBox>
private CollectionViewSource _items;
private Menu _menu = new Menu();
public ICollectionView Items
{
get
{
if (_items == null)
{
_items = new CollectionViewSource {Source = new ObservableCollection<MenuItem>(_menu.MyMenu)};
}
return _items.View;
}
}
I'm assuming your problem is that data doesn't show up in your ListBox? Try programmatically adding your groupings to _items and binding your ListBox.ItemsSource directly to Items:
public ICollectionView Items
{
get
{
if (_items == null)
{
_items = new CollectionViewSource {Source = new ObservableCollection<MenuItem>(_menu.MyMenu)};
_items.GroupDescriptions.Add(new PropertyGroupDescription("Category"));
}
return _items.View;
}
}
<ListBox x:Name="selectedMenuItem" Foreground="White" Grid.Column="0" Grid.Row="1" ItemsSource="{Binding Items}"
DisplayMemberPath="Name" Background="{x:Null}" BorderThickness="0">
<ListBox.GroupStyle>
<x:Static Member="GroupStyle.Default"/>
</ListBox.GroupStyle>
</ListBox>
You can then do away with the foods resource, assuming I haven't boffed my code.