Populate DataGrid through Button Command - xaml

TheContext refers to my ViewModel in the resources section
<DataGrid DataContext="{StaticResource TheContext}"
ItemsSource="{Binding Path=Cars}">
This is my viewModel.cs
public CarsSearchResultsViewModel()
{
ButtonCommand = new DelegateCommand(x => GetCars());
}
public void GetCars()
{
List<Car> cars = new List<Car>();
cars.Add(new Car() { Make = "Chevy", Model = "Silverado" });
cars.Add(new Car() { Make = "Honda", Model = "Accord" });
cars.Add(new Car() { Make = "Mitsubishi", Model = "Galant" });
Cars = new ObservableCollection<Car>(cars);
}
private ObservableCollection<Car> _cars;
public ObservableCollection<Car> Cars
{
get { return _cars; }
private set
{
if (_cars == value) return;
_cars = value;
}
}
I have tried adding OnPropertyChanged("Cars"), I have tried adding adding People = null before adding the list, I have tried adding UpdateSourceTrigger=PropertyChanged to the ItemsSource, and before using ObservableCollection I tried using IViewCollection.
Im not trying to update or delete from a collection, just populate the grid with a button click. If i run GetCars() in the constructor without the command it works fine.

Your ViewModel needs to implement the INotifyPropertyChanges interface, and call OnpropertyChanged in the setter of your ObservableCollection so that when you reinstated the UI will get notified so you Cars property should looks somethink like this :
private ObservableCollection<Car> _cars ;
public ObservableCollection<Car> Cars
{
get
{
return _cars;
}
set
{
if (_cars == value)
{
return;
}
_cars = value;
OnPropertyChanged();
}
}
The Cars collection needs to be defined inside TheContext class since it is your Context and that last one needs to implement the mentioned interface :
public class TheContext:INotifyPropertyChanged
{
//Cars property and your code ..
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}

Related

How to make a TextBlock of an UWP-Application update automatically?

I have a background-thread which updates a Integer-value once per second. How can I map this Integer to a Text-Field of my XAML form that the Form always shows the current value and updates automatically if the Integer changes?
You can use a ViewModel with a binding.
With OnPropertyChanged() it will automatically changed and displayed in your UI.
here is an example to give you an idea
use in your xaml:
<TextBox x:Name="MyTextBox" Text="{Binding Name}".../>
in your code behind:
...
var vm = new ViewModel("Nr.7");
this.BindingContext = vm;
foreach(var x in Whatever)
{
vm.Name = x;
}
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace MyAppNamespace
{
// This class implements INotifyPropertyChanged
// to support one-way and two-way bindings
// (such that the UI element updates when the source
// has been changed dynamically)
public class ViewModel : INotifyPropertyChanged
{
private string name;
// Declare the event
public event PropertyChangedEventHandler PropertyChanged;
public ViewModel()
{
}
public ViewModel(string value)
{
this.name = value;
}
public string Name
{
get { return name; }
set
{
name = value;
// Call OnPropertyChanged whenever the property is updated
OnPropertyChanged();
}
}
// Create the OnPropertyChanged method to raise the event
// The calling member's name will be used as the parameter.
protected void OnPropertyChanged([CallerMemberName] string name = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
}

Xamarin MVVM push user data to viewmodel

like the title says I want to give through the user information to my viewmodel, but the problem is that the viewmodel is registered as a dependency and I am binding its content to the xaml page itself. How do I send the user information to the viewmodel itself?
Thank you!
Xaml.cs part:
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class Calendar : ContentPage
{
public Calendar(User user)
{
InitializeComponent();
FileImageSource image = new FileImageSource
{
File = "calendar.png"
};
Icon = image;// push user information to the ICalendarViewModel
BindingContext = AppContainer.Container.Resolve<ICalendarViewModel>();
}
}
Interface:
public interface ICalendarViewModel : INotifyPropertyChanged
{
}
Bootstrap part registering dependencies:
public class Bootstrap
{
public IContainer CreateContainer()
{
var containerBuilder = new ContainerBuilder();
RegisterDependencies(containerBuilder);
return containerBuilder.Build();
}
protected virtual void RegisterDependencies(ContainerBuilder builder)
{
builder.RegisterType<CalendarViewModel>()
.As<ICalendarViewModel>()
.SingleInstance();
}
}
CalendarViewModel: I do not know if this will help
public class CalendarViewModel : ViewModelBase, ICalendarViewModel
{
public event PropertyChangedEventHandler PropertyChanged;
public string ErrorMessage { get; set; }
private CourseInformation _information;
private ICourseInformationRepository _repository;
public CalendarViewModel()
{
_repository = new CourseInformationRepository();
LoadData();
}
private ObservableCollection<CourseInformation> _courses;
public ObservableCollection<CourseInformation> Courses
{
get
{
return _courses;
}
set
{
_courses = value;
RaisePropertyChanged(nameof(Courses));
}
}
private void LoadData()
{
try
{
ObservableCollection<CourseInformation> CourseList = new ObservableCollection<CourseInformation>(_repository.GetAllCourseInformation());
Courses = new ObservableCollection<CourseInformation>();
DateTime date;
foreach (var course in CourseList)
{
string [] cour = course.Date.Split('/');
cour[2] = "20" + cour[2];
date = new DateTime(Convert.ToInt32(cour[2]), Convert.ToInt32(cour[1]), Convert.ToInt32(cour[0]));
if (date == DateTime.Now)//TESTING WITH TEST DATE, datetime.now
{
if (course.FromTime.Length < 4)
{
course.FromTime = "0" + course.FromTime;
}
if (course.UntilTime.Length < 4)
{
course.UntilTime = "0" + course.UntilTime;
}
course.FromTime = course.FromTime.Insert(2, ":");
course.UntilTime = course.UntilTime.Insert(2, ":");
Courses.Add(course);
}
}
}
catch (ServerUnavailableException e)
{
ErrorMessage = "Server is niet beschikbaar, ophalen van kalender is niet mogelijk.";
}
}
private void RaisePropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
Bootstrap binding in app.xaml.cs:
public partial class App : Application
{
public App()
{
InitializeComponent();
AppContainer.Container = new Bootstrap().CreateContainer();
MainPage = new LoginView();
}
protected override void OnStart()
{
// Handle when your app starts
}
protected override void OnSleep()
{
// Handle when your app sleeps
}
protected override void OnResume()
{
// Handle when your app resumes
}
}
I wanted to comment (not enough reputation) on #LeRoy, use a framework. I would recommend FreshMVVM and you can pass objects into the ViewModel and even pass in Services. It makes it all nice and clean, and it just works.
Should not your CalendarViewModel viewModel contain BindableBase ?
public class CalendarViewModel : BindableBase, ViewModelBase, ICalendarViewModel
what framework are you using? prism, freshmvvm.
Your View and Viewmodel is normally automatically handled by the framework, all you need to do is register your page.
Container.RegisterTypeForNavigation<Views.CalendarPage>();

BindableProperty not updated on ViewModel

In Xamarin.Forms I implemented a custom Picker.
The ItemsSource is set correctly. However when i change the selected item it does not update the property on my ViewModel.
The BindablePicker:
public class BindablePicker : Picker
{
public BindablePicker()
{
this.SelectedIndexChanged += OnSelectedIndexChanged;
}
public static BindableProperty ItemsSourceProperty =
BindableProperty.Create<BindablePicker, IEnumerable>(o => o.ItemsSource, default(IEnumerable), propertyChanged: OnItemsSourceChanged);
public static BindableProperty SelectedItemProperty =
BindableProperty.Create<BindablePicker, object>(o => o.SelectedItem, default(object), propertyChanged: OnSelectedItemChanged);
public IEnumerable ItemsSource
{
get { return (IEnumerable)GetValue(ItemsSourceProperty); }
set { SetValue(ItemsSourceProperty, value); }
}
public object SelectedItem
{
get { return (object)GetValue(SelectedItemProperty); }
set { SetValue(SelectedItemProperty, value); }
}
private static void OnItemsSourceChanged(BindableObject bindable, IEnumerable oldvalue, IEnumerable newvalue)
{
var picker = bindable as BindablePicker;
picker.Items.Clear();
if (newvalue != null)
{
//now it works like "subscribe once" but you can improve
foreach (var item in newvalue)
{
picker.Items.Add(item.ToString());
}
}
}
private void OnSelectedIndexChanged(object sender, EventArgs eventArgs)
{
if (SelectedIndex < 0 || SelectedIndex > Items.Count - 1)
{
SelectedItem = null;
}
else
{
SelectedItem = Items[SelectedIndex];
}
}
private static void OnSelectedItemChanged(BindableObject bindable, object oldvalue, object newvalue)
{
var picker = bindable as BindablePicker;
if (newvalue != null)
{
picker.SelectedIndex = picker.Items.IndexOf(newvalue.ToString());
}
}
}
The Xamlpage:
<controls:BindablePicker Title="Category"
ItemsSource="{Binding Categories}"
SelectedItem="{Binding SelectedCategory}"
Grid.Row="2"/>
The ViewModel properties, didn't implement the NotifyPropertyChanged on the properties since they only need to be updated from the ´Viewto theViewModel`:
public Category SelectedCategory { get; set; }
public ObservableCollection<Category> Categories { get; set; }
When creating your BindableProperty:
public static BindableProperty SelectedItemProperty =
BindableProperty.Create<BindablePicker, object>(o => o.SelectedItem, default(object), propertyChanged: OnSelectedItemChanged);
without specifying the defaultBindingMode, the BindingMode is set to OneWay, meaning the Binding is updated from source (your view model) to target (your view).
This can be fixed by changing the defaultBindingMode:
public static BindableProperty SelectedItemProperty =
BindableProperty.Create<BindablePicker, object>(o => o.SelectedItem, default(object), BindingMode.TwoWay, propertyChanged: OnSelectedItemChanged);
or, if it's the default you want for your picker, but want to update the source only in this view, you can specify the BindingMode for this instance of the Binding only:
<controls:BindablePicker Title="Category"
ItemsSource="{Binding Categories}"
SelectedItem="{Binding SelectedCategory, Mode=TwoWay}"
Grid.Row="2"/>
Beside adding the Mode=TwoWay to my binding a had to change some things in my picker so it could work with the actual objects i had it bound to.
The Items property of the Xamarin Picker is an IList<string>
since all my items are added to it as a string it keeps the same indexed value.
Therefor the ItemsSource is changed to an IList:
public IList ItemsSource
{
get { return (IList)GetValue(ItemsSourceProperty); }
set { SetValue(ItemsSourceProperty, value); }
}
I also modified the SelectedIndexChangedmethod so it doesn't retrieve the item from the Items but from the ItemsSource, wich is in my case an IList<Category>:
private void OnSelectedIndexChanged(object sender, EventArgs eventArgs)
{
if (SelectedIndex < 0 || SelectedIndex > Items.Count - 1)
{
SelectedItem = null;
}
else
{
SelectedItem = ItemsSource[SelectedIndex];
}
}
In my ViewModel i no longer use the ObservableCollection for my Categories but add these items to an IList<Category>.
The ObservableCollectionhas no use since when my BindablePicker binds to the ItemsSource the items are added to the internal IList<string>. when adding an item to the collection it will not be updated. I now update the entire ItemSourceif an item is changed.

How To send Command Parameter In Mvvm Silverlight 5

I Have Implemented Icommand in my mvvm architecture as SimpleCommand.cs
public class SimpleCommand<T1, T2> : ICommand
{
private Func<T1, bool> canExecuteMethod;
private Action<T2> executeMethod;
public SimpleCommand(Func<T1, bool> canExecuteMethod, Action<T2> executeMethod)
{
this.executeMethod = executeMethod;
this.canExecuteMethod = canExecuteMethod;
}
public SimpleCommand(Action<T2> executeMethod)
{
this.executeMethod = executeMethod;
this.canExecuteMethod = (x) => { return true; };
}
public bool CanExecute(T1 parameter)
{
if (canExecuteMethod == null) return true;
return canExecuteMethod(parameter);
}
public void Execute(T2 parameter)
{
if (executeMethod != null)
{
executeMethod(parameter);
}
}
public bool CanExecute(object parameter)
{
return CanExecute((T1)parameter);
}
public void Execute(object parameter)
{
Execute((T2)parameter);
}
public event EventHandler CanExecuteChanged;
public void RaiseCanExecuteChanged()
{
var handler = CanExecuteChanged;
if (handler != null)
{
handler(this, EventArgs.Empty);
}
}
}
And Implemented this ICommand in my viewModel As follows:
private ICommand printCommand;
public ICommand PrintCommand
{
get { return printCommand; }
set { printCommand = value; }
}
myviewmodel() // in Constructor of ViewModel
{
this.PrintCommand = new SimpleCommand<Object, EventToCommandArgs>(ExecutePrintCommand);
}
}
On XAML : I Have Called Command="{Binding PrintCommand}"
<Button Content="Print Button" Command="{Binding PrintCommand}" Width="120" Height="25" Margin="3"></Button>
It Works Perfectly...
But When I try To Send CommandParameter to Command As:
<Button Content="Print Button" Command="{Binding PrintCommand}" Width="120" Height="25" Margin="3" CommandParameter="{Binding ElementName=grdReceipt}"></Button>
Then Command is not executing.
and Giving Error as :
Unable to cast object of type 'System.Windows.Controls.Grid' to type
'PropMgmt.Shared.EventToCommandArgs'.
Please Help.Thanks In Advance.
The problem is this part in your SimpleCommand implementation
public void Execute(object parameter){
Execute((T2)parameter);
}
T2 in your case is of type EventToCommandArgs, but as parameter
CommandParameter="{Binding ElementName=grdReceipt}"
you are passing a System.Windows.Controls.Grid, which results in the exception you have mentioned.
Also is your implementation of the command incorrect. The parameter passed to CanExecute and Execute are the same object. The following implementation works using only one generic type.
public class SimpleCommand<T1> : ICommand
{
private Func<T1, bool> canExecuteMethod;
private Action<T1> executeMethod;
public SimpleCommand(Func<T1, bool> canExecuteMethod, Action<T1> executeMethod)
{
this.executeMethod = executeMethod;
this.canExecuteMethod = canExecuteMethod;
}
public SimpleCommand(Action<T1> executeMethod)
{
this.executeMethod = executeMethod;
this.canExecuteMethod = (x) => { return true; };
}
public bool CanExecute(T1 parameter)
{
if (canExecuteMethod == null) return true;
return canExecuteMethod(parameter);
}
public void Execute(T1 parameter)
{
if (executeMethod != null)
{
executeMethod(parameter);
}
}
public bool CanExecute(object parameter)
{
return CanExecute((T1)parameter);
}
public void Execute(object parameter)
{
Execute((T1)parameter);
}
public event EventHandler CanExecuteChanged;
public void RaiseCanExecuteChanged()
{
var handler = CanExecuteChanged;
if (handler != null)
{
handler(this, EventArgs.Empty);
}
}
}
Using this implementation you can define:
this.PrintCommand = new SimpleCommand<object>(ExecutePrintCommand);
Since your ExecutePrintCommand gets an object as parameter you need to do a type check or cast to the type you need. In your case you will get a System.Windows.Controls.Grid.
public void ExecutPrintCommand(object parameter) {
System.Windows.Controls.Grid grid = parameter as System.Windows.Controls.Grid;
if (grid != null) {
// do something with the Grid
}
else {
// throw exception or cast to another type you need if your command should support more types.
}
}

Why my WP emulator stops on splashscreen

I created a WP Class Library BusinessLogic project which is composed by these three class
1) Bottle Class
namespace BusinessLogic
{
public class Bottle : INotifyPropertyChanged
{
// Due to INotifyPropertyChanged interface
public event PropertyChangedEventHandler PropertyChanged;
// Proprietà Title
private string title;
public string Title
{
set
{
if (title != value)
{
title = value;
OnPropertyChanged("Title");
}
}
get
{
return title;
}
}
// Proprietà PhotoFileName
private string photoFileName;
public string PhotoFileName
{
set
{
if (photoFileName != value)
{
photoFileName = value;
OnPropertyChanged("PhotoFileName");
}
}
get
{
return photoFileName;
}
}
protected virtual void OnPropertyChanged(string propChanged)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propChanged));
}
}
}
2) Bottles Class
namespace BusinessLogic
{
public class Bottles : INotifyPropertyChanged
{
// Due to INotifyPropertyChanged interface
public event PropertyChangedEventHandler PropertyChanged;
// Proprietà MainTitle
private string mainTitle;
public string MainTitle
{
set
{
if (mainTitle != value)
{
mainTitle = value;
OnPropertyChanged("MainTitle");
}
}
get
{
return mainTitle;
}
}
// Proprietà bottles
private ObservableCollection<Bottle> bottleSet = new ObservableCollection<Bottle>();
public ObservableCollection<Bottle> BottleSet
{
set
{
if (bottleSet != value)
{
bottleSet = value;
OnPropertyChanged("BottleSet");
}
}
get { return bottleSet; }
}
protected virtual void OnPropertyChanged(string propChanged)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propChanged));
}
}
}
3) BottlesPresenter Class
namespace BusinessLogic
{
public class BottlesPresenter : INotifyPropertyChanged
{
// Due to INotifyPropertyChanged interface
public event PropertyChangedEventHandler PropertyChanged;
// Proprietà BottleMatrix
private Bottles bottlesMatrix;
public Bottles BottlesMatrix
{
protected set
{
if (bottlesMatrix != value)
{
bottlesMatrix = value;
OnPropertyChanged("BottlesMatrix");
}
}
get { return bottlesMatrix; }
}
public BottlesPresenter()
{
XmlSerializer xml = new XmlSerializer(typeof(Bottles));
using (StreamReader fileReader = new StreamReader(#"C:\Stuff\WindowsPhone\AppLearningHowTo2\AppLearningHowTo2\DAL\DB.xml"))
{
BottlesMatrix = (Bottles)xml.Deserialize(fileReader);
}
}
protected virtual void OnPropertyChanged(string propChanged)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propChanged));
}
}
}
The BottlePresenter constructor should deserialize from an xml file located into the file system. It contains the following tags
<?xml version="1.0"?>
<Bottles xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<MainTitle>MainTitle</MainTitle>
<Bottleset>
<Bottle>
<Title>Title1</Title>
<PhotoFileName>PhotoFileName1</PhotoFileName>
</Bottle>
<Bottle>
<Title>Title2</Title>
<PhotoFileName>PhotoFileName2</PhotoFileName>
</Bottle>
</Bottleset>
</Bottles>
Then I created a WP Application and I made a reference to the BusinessLogic.dll project library.
In the MainPage.xaml file I put the XML namespace declaration
xmlns:businesslogic="clr-namespace:BusinessLogic;assembly=BusinessLogic"
I then instantiated the BottlesPresenter class in the MainPage.xaml Resources collection
<phone:PhoneApplicationPage.Resources>
<businesslogic:BottlesPresenter x:Key="bottlesPresenter" />
</phone:PhoneApplicationPage.Resources>
And finally put a TextBlock in the content area with a binding to that resource:
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<TextBlock HorizontalAlignment="Center"
VerticalAlignment="Center"
Text="{Binding Source={StaticResource bottlesPresenter},
Path=Bottles.MainTitle}" />
Unfortunately I launch the debugger, the emulator switch on, reach the splashscreen and doesn't go on.
In a nutshell: I can't reach to create an instance of the BottlesPresenter class.
I banged my head against the wall for weeks without finding a solution.
Please could someone give me a hand?
Thank you very much
Antonio
Emulator behaves like that when WP7 cannot construct Application object. From question, I see only 1 reference from Application to your code. It's BottlePresenter in Resources.
XamlLoader tries to create instance of this type.
See what's inside your BottlePresenter constructur:
public BottlesPresenter()
{
XmlSerializer xml = new XmlSerializer(typeof(Bottles));
using (StreamReader fileReader = new StreamReader(
#"C:\Stuff\WindowsPhone\AppLearningHowTo2\AppLearningHowTo2\DAL\DB.xml"))
{
BottlesMatrix = (Bottles)xml.Deserialize(fileReader);
}
}
First line is OK.
Second line is OK.
Third line causes exception, because path "C:\Stuff\WindowsPhone\AppLearningHowTo2\AppLearningHowTo2\DAL\DB.xml" is not acceptable on Windows Phone.
All files you can access is Content of your XAP, Resources in your assembly, and files in Isolated Storage.
Following articles might help you All about WP7 Isolated Storage - Read and Save Text files