Hey there. I found some example Code for ViewModel which does not work for me. My problem is that when I start the app it is about to launch and then just closes itself. I get no errors from Visual Studio besides the notification that there is something wrong with XamarinFormsPrevieweriOS.
This is my Code:
SimpleMultiplierViewModel.cs:
namespace BookCodedotNet2
{
class SimpleMultiplierViewModel : INotifyPropertyChanged
{
double multiplicand, multiplier, product;
public event PropertyChangedEventHandler PropertyChanged;
public double Multiplicand
{
set
{
if (multiplicand != value)
{
multiplicand = value;
OnPropertyChanged("Multiplicand");
UpdateProduct();
}
}
get
{
return Multiplicand;
}
}
public double Multiplier
{
set
{
if (multiplier != value)
{
multiplier = value;
OnPropertyChanged("Multiplier");
UpdateProduct();
}
}
get
{
return multiplier;
}
}
public double Product
{
protected set
{
if (product != value)
{
product = value;
OnPropertyChanged("Product");
}
}
get
{
return product;
}
}
void UpdateProduct()
{
Product = Multiplicand * Multiplier;
}
protected void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if(handler != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public SimpleMultiplierViewModel()
{
}
}
}
SimpleMultiplierPage.xaml:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="BookCodedotNet2.SimpleMultiplierPage"
xmlns:local="clr-namespace:BookCodedotNet2"
Padding="10,0">
<ContentPage.Resources>
<ResourceDictionary>
<local:SimpleMultiplierViewModel x:Key="viewModel"/>
<Style TargetType="Label">
<Setter Property="FontSize" Value="Large"/>
</Style>
</ResourceDictionary>
</ContentPage.Resources>
<StackLayout BindingContext="{StaticResource viewModel}">
<StackLayout VerticalOptions="CenterAndExpand">
<Slider Value="{Binding Multiplicand}"/>
<Slider Value="{Binding Multiplier}"/>
</StackLayout>
<StackLayout Orientation="Horizontal"
Spacing="0"
VerticalOptions="CenterAndExpand"
HorizontalOptions="Center">
<Label Text="{Binding Multiplicand, StringFormat='{0:F3}'}"/>
<Label Text="{Binding Multiplier, StringFormat=' x {0:F3}'}"/>
<Label Text="{Binding Product, StringFormat=' = {0:F3}'}"/>
</StackLayout>
</StackLayout>
</ContentPage>