Why my WP emulator stops on splashscreen - silverlight-4.0

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

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>();

Universal Windows Apps 8.1 data binding issue

Simple two way data binding to a model's property is not working, to reproduce the issue, I have created a new project in Visual Studio 2013 i.e. with Blank App (Universal Apps) template with .NET framework 4.5
Project folders and files
The model
namespace UWP.MVVM.Models
{
public class PersonModel
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
}
The base view model
namespace UWP.MVVM.Core
{
using System.ComponentModel;
using System.Runtime.CompilerServices;
public class VMBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
The INavigable interface
namespace UWP.MVVM.Core
{
#if WINDOWS_PHONE_APP
using Windows.Phone.UI.Input;
#endif
public interface INavigable
{
void Activate(object parameter);
void Deactivate(object parameter);
#if WINDOWS_PHONE_APP
void BackButtonPressed(BackPressedEventArgs e);
#endif
}
}
The main view model
namespace UWP.MVVM.ViewModels
{
using UWP.MVVM.Core;
using UWP.MVVM.Models;
#if WINDOWS_PHONE_APP
using Windows.Phone.UI.Input;
#endif
public class MainViewModel : VMBase, INavigable
{
private PersonModel person;
public MainViewModel()
{
this.Person = new PersonModel();
}
public PersonModel Person
{
get
{
return this.person;
}
set
{
if (value == this.person)
{
return;
}
this.person = value;
this.NotifyPropertyChanged();
}
}
public void Activate(object parameter)
{
this.Person.FirstName = "Gerrard";
}
public void Deactivate(object parameter)
{
}
#if WINDOWS_PHONE_APP
public void BackButtonPressed(BackPressedEventArgs e)
{
}
#endif
}
}
The main page view
<Page
x:Class="UWP.MVVM.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:UWP.MVVM"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:vm="using:UWP.MVVM.ViewModels"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<!--<Page.DataContext>
<vm:MainViewModel/>
</Page.DataContext>-->
<Grid Margin="24,24">
<TextBox Header="First Name"
Text="{Binding Person.FirstName}"/>
</Grid>
</Page>
The main page code behind
namespace UWP.MVVM
{
using UWP.MVVM.Core;
#if WINDOWS_PHONE_APP
using Windows.Phone.UI.Input;
#endif
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using UWP.MVVM.ViewModels;
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
this.DataContext = new MainViewModel();
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached.
/// This parameter is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
var navigableViewModel = this.DataContext as INavigable;
if (navigableViewModel != null)
{
navigableViewModel.Activate(e.Parameter);
}
#if WINDOWS_PHONE_APP
HardwareButtons.BackPressed += HardwareButtons_BackPressed;
#endif
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
base.OnNavigatedFrom(e);
var navigableViewModel = this.DataContext as INavigable;
if (navigableViewModel != null)
{
navigableViewModel.Deactivate(e.Parameter);
}
#if WINDOWS_PHONE_APP
HardwareButtons.BackPressed -= HardwareButtons_BackPressed;
#endif
}
#if WINDOWS_PHONE_APP
private void HardwareButtons_BackPressed(object sender, BackPressedEventArgs e)
{
var navigableViewModel = this.DataContext as INavigable;
if (navigableViewModel != null)
{
navigableViewModel.BackButtonPressed(e);
}
}
#endif
}
}
I tried using Mode=TwoWay on the TextBox and it is not working, but when I set the DataContext in xaml instead of the code behind then data binding works even without the Mode=TwoWay property.
I want to set the DataContext in the code behind file as in the real project where I am having this issue, I am using MVVM-light libraries along with its SimpleIoc container, so I want to get the view model instance from SimpleIoc and set the DataContext because the view model dependencies are injected by the SimpleIoc and the code will be a lot cleaner.
The problem is: you only notify the change of PersonModel Person. The ViewModel need to notify the change of the property of PersonModel.
Since you are using MVVM Light, change your Model to:
public class PersonModel : ObservableObject
{
public int Id { get; set; }
string _FirstName = "";
public string FirstName {
get {
return _FirstName;
}
set {
Set(ref _FirstName, value);
}
}
public string LastName { get; set; }
}

Populate DataGrid through Button Command

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));
}
}

Windows 8 Combobox PlaceholderText

i am using "visual studio express for windows 8" and using Combo Box control as
<ComboBox Name="Categories" >
<x:String>apple</x:String>
<x:String>ball</x:String>
<x:String>cat</x:String>
<x:String>dog</x:String>
</ComboBox>
i want to show placeholder text in it to show some text until user hasn't selected any item from it. But when i use property PlaceholderText as described in microsoft reference to show text but when i use it the sdk shows this error
The member "PlaceholderText" is not recognized or is not accessible.
or is there any other method so that i can show some default text in Combobox.
Thanks.
This is for Windows 8.1 preview and not Windows 8 development. You will need to install the preview at this time before you can use and develop with this combobox. Looking at the docs for placeholder it states:
Minimum supported client Windows 8.1 Preview
Edit
To do this manually simply preload the combobox by hand. Here is an example, let us start with the ViewModel where the constructor will load an initial value into the combobox named "Loading"
public class MainVM : INotifyPropertyChanged
{
private List<string> _dataList;
public List<string> ComboData
{
get { return _dataList; }
set
{
if (_dataList != value)
{
_dataList = value;
OnPropertyChanged();
}
}
}
public MainVM()
{
ComboData = new List<string> {"Loading..."};
}
#region INotify Property Changed Implementation
/// <summary>
/// Event raised when a property changes.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Raises the PropertyChanged event.
/// </summary>
/// <param name="propertyName">The name of the property that has changed.</param>
public void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
}
Now on the main page xaml bind to ComboData, but we need to be wary of the first situation where a list of one items will have loading, and we want to make that the selected item.
<ComboBox ItemsSource="{Binding ComboData}" Height="30" Width="300" Loaded="OnLoaded" />
Ok, in the code behind of the page we will set our datacontext to be the ViewModel we setup before, but also have an OnLoaded method which checks for the 1 item loading situation. In the below example we simulate a 3 second delay of loading the rest of the data.
public sealed partial class MainPage : Page
{
public MainVM ViewModel { get; set; }
public MainPage()
{
this.InitializeComponent();
DataContext = ViewModel = new MainVM();
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
var cBox = sender as ComboBox;
if (cBox != null)
{
if ((cBox.Items != null) && (cBox.Items.Count == 1))
{
cBox.SelectedIndex = 0;
// Debug code to simulate a change
Task.Run(() =>
{
// Sleep 3 seconds
new System.Threading.ManualResetEvent(false).WaitOne(3000);
Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{ ViewModel.ComboData = new List<string> {"Alpha", "Gamma", "Omega"}; });
});
}
}
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
}
}