This is my first experience with C#, as well as .net in general. I'm trying to get an understanding of MVVM and how it can work with a screen I want to build.
My button text is not updating when I am changing it after a different button is clicked. The debugger is showing that even though the OnPropertyChanged function is getting called, the PropertyChanged is always null.
I've looked at some documentation and taken a look at other posts of people asking similar questions but none of those solutions have worked for me. I'm also looking for an explanation so I can understand what i'm doing wrong.
Code:
MonthViewPage.xaml
<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Mobile_Release_POC_4.MonthViewPage"
xmlns:local="clr-namespace:Mobile_Release_POC_4;assembly=Mobile_Release_POC_4"
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinForms.Input"
xmlns:sys="clr-namespace:System;assembly=mscorlib">
<ContentPage.BindingContext>
<local:WeekViewDatesViewModel MiddleWeekViewDate='{x:Static sys:DateTime.Now}' />
</ContentPage.BindingContext>
<StackLayout>
<Label Text="Monday, April 27, 2015"
HorizontalOptions="Center"></Label>
<Grid Padding="0" ColumnSpacing="-2">
<Grid.RowDefinitions>
<RowDefinition Height="75" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions >
<ColumnDefinition Width="50" />
</Grid.ColumnDefinitions>
<Button x:Name="monthViewDateButton1"
Text="{Binding MiddleWeekViewDate}"
FontSize="10"
Grid.Row="0"
Grid.Column="0"
/>
<Button x:Name="monthViewDateButton2"
Text="Tue 4/28"
FontSize="10"
Grid.Row="0"
Grid.Column="1"
Clicked="OnButtonClicked"
/>
</Grid>
</StackLayout>
MonthViewPage.xaml.cs
using Xamarin.Forms;
namespace Mobile_Release_POC_4
{
public partial class MonthViewPage : ContentPage
{
public MonthViewPage ()
{
InitializeComponent();
}
void OnButtonClicked(object sender , EventArgs args){
WeekViewDatesViewModel dc = new WeekViewDatesViewModel ();
dc.MiddleWeekViewDate = new DateTime (2014, 2, 2);
}
}
WeekViewDatesViewModel.cs
namespace Mobile_Release_POC_4
{
public class WeekViewDatesViewModel : INotifyPropertyChanged
{
DateTime middleWeekViewDate;
public event PropertyChangedEventHandler PropertyChanged;
public DateTime MiddleWeekViewDate
{
set
{
if (middleWeekViewDate != value)
{
middleWeekViewDate = value;
OnPropertyChanged("MiddleWeekViewDate");
}
}
get
{
return middleWeekViewDate;
}
}
protected void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (PropertyChanged != null)
{
PropertyChanged(this,
new PropertyChangedEventArgs(propertyName));
}
}
}
}
Thank you
Only create one ViewModel, its scope is the life of the page (at least).
Change your code to this:
public partial class MonthViewPage : ContentPage
{
public WeekViewDatesViewModel VM { get; set; }
public MonthViewPage ()
{
DataContext = VM = new WeekViewDatesViewModel();
InitializeComponent();
}
void OnButtonClicked(object sender , EventArgs args){
VM.MiddleWeekViewDate = new DateTime (2014, 2, 2);
}
}
Related
I have two XAML pages and one their common ViewModel page.I want to output data from one page to another from the collection of the selected item. It must be Label`s Text.
I have 2 problems
1)I can not bind text from label to the object field
2)If I bind Label`s Text to a variable.I can see data only on the current page. But if I go to another page and place the same label there, the information is not displayed.I do not understand why so because on the next page the same variable which already contains data
FIRST XAML PAGE
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="App1.TryPage">
<ContentPage.Content>
<StackLayout>
<CollectionView x:Name="AddCar" ItemsSource="{Binding Hearts}"
SelectionMode="None">
<CollectionView.ItemsLayout>
<GridItemsLayout Orientation="Vertical"
Span="2" />
</CollectionView.ItemsLayout>
<CollectionView.ItemTemplate>
<DataTemplate>
<Grid >
<Grid.RowDefinitions>
<RowDefinition Height="135" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="150" />
<ColumnDefinition Width="150" />
</Grid.ColumnDefinitions>
<Frame CornerRadius="10" BorderColor="Black" Padding="0" >
<Button
CornerRadius="10" HorizontalOptions="Center" VerticalOptions="Center" HeightRequest="135" WidthRequest="150"
BackgroundColor="{Binding CustButtonColor}" ImageSource="{Binding Image}"
Command="{ Binding BindingContext.ChangeColor,
Source={x:Reference Name=AddCar} }" CommandParameter="{Binding .}"/>
</Frame>
</Grid>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
<Label x:Name="small12" FontSize="Large" HorizontalOptions="Center" VerticalOptions="Start" Text="{Binding tryHeart.TypeHeart}" />
<Button Text="Navigate" Command="{Binding navigateCommand }">
</StackLayout>
</ContentPage.Content>
</ContentPage>
CODE BEHIND
public partial class TryPage : ContentPage
{
public TryPage()
{
InitializeComponent();
BindingContext = new TryPageCS(this.Navigation);
}
}
VIEW MODEL PAGE
public class TryPageCS : INotifyPropertyChanged
{
public ObservableCollection<CircleColor> Hearts { get; set; }
public ICommand ChangeColor { protected set; get; }
public TryHeart tryHeart { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
INavigation Navigation { get; set; }
public Command navigateCommand { get; set; }
public async Task GotoPage2()
{
await Navigation.PushModalAsync(new MainPage());
}
public TryPageCS(INavigation navigation)
{
tryHeart = new TryHeart();
this.Navigation = navigation;
this.navigateCommand = new Command(async () => await GotoPage2());
Hearts = new ObservableCollection<CircleColor>();
Hearts.Add(new CircleColor() { Name = "one", Image = "heart", CustButtonColor = Color.White });
Hearts.Add(new CircleColor() { Name = "two", Image = "heart", CustButtonColor = Color.White });
Hearts.Add(new CircleColor() { Name = "three", Image = "heart", CustButtonColor = Color.White });
Hearts.Add(new CircleColor() { Name = "four", Image = "heart", CustButtonColor = Color.White });
var DefaultCars = new ObservableCollection<CircleColor>();
DefaultCars = Hearts;
ChangeColor = new Command<CircleColor>((key) =>
{
foreach (var item in Hearts)
{
item.CustButtonColor = Color.White;
item.Image = "heart";
}
var car = key as CircleColor;
car.CustButtonColor = Color.LightCoral;
tryHeart.TypeHeart = car.Name;
});
}
}
SECOND PAGE
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
xmlns:controls="clr-namespace:App1"
x:Class="App1.MainPage">
<StackLayout>
<Label FontSize="Large" Text="{Binding tryHeart.TypeHeart}" />
</StackLayout>
</ContentPage>
CODE BEHIND
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
BindingContext = new TryPageCS(this.Navigation);
}
}
Also I have a class
public class TryHeart : INotifyPropertyChanged
{
string typeHeart;
public string TypeHeart
{
set
{
if (typeHeart != value)
{
typeHeart = value;
OnPropertyChanged("TypeHeart");
}
}
get
{
return typeHeart;
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
I will explain why I need it. In my real project I have to collect information about the car from different pages. object of this class it will be my machine. Therefore I want to write down the collected data in object of a class and then on the last page to display data
On the SECOND XAML PAGE I write only THE SAME LABEL
<Label x:Name="small123" FontSize="Large" HorizontalOptions="Center" VerticalOptions="Start" Text="{Binding Name}" />
Please,help me with my 2 problems
1)Why I can not to write
<Label x:Name="small12" FontSize="Large" HorizontalOptions="Center" VerticalOptions="Start" Text="{Binding tryHeart.TypeHeart}" />
Information does not display
2)How I must display information from one page from collection view of selected item to another page
Navigation does not contain a definition for PushModalAsync
For question 1
TryHeart in the ViewModel is a private property in your case . You need to set it as public .
public TryHeart tryHeart {get;set;}
public TryPageCS()
{
//...
tryHeart = new TryHeart();
//...
}
For question 2
If you want to handle navigation logic in VM , you need to pass the current navigation from current page .
in ViewModel
Add a property
INavigation CurrentNavigation { get; set; }
public TryPageCS(INavigation navigation)
{
CurrentNavigation = navigation;
}
And now you can use the property in the method
await CurrentNavigation.PushModalAsync(new MainPage());
in ContentPage
Pass the Navigation as params
BindingContext = new TryPageCS(this.Navigation);
I have been reading my code over and over for the past hour and cannot seem to understand why the changes I have added now don't allow my page to display (the page not displaying is NameEntryPage). The app starts on a the StartPage which has two buttons allowing the user to choose either One Player Game or Two Player Game. If the user chooses Two Player Game, then it navigates to NameEntryPage where the user can enter names for the two players. NameEntryPage has a button that when clicked passes the names entered and navigates to TwoPlayerPage. I have checked StartPage, OnePlayerPage, and TwoPlayerPage and they all still work. However, NameEntryPage does not load anything (and the button on StartPage that takes you there does not work either. To check the other pages I had to change the code in App() to begin on those pages)
App() code
public App()
{
InitializeComponent();
MainPage = new NavigationPage(new Views.NameEntryPage());
}
NameEntryPage.xaml code
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Class="SampleApp.Views.NameEntryPage">
<ContentPage.Content>
<StackLayout Margin="20">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
</Grid>
<Entry
x:Name="EntryNameP1"
Placeholder="Enter a name for Player 1"
Text="{Binding NameP1}"
Grid.Row="0" Grid.Column="0"/>
<Entry x:Name="EntryNameP2"
Placeholder="Enter a name for Player 2"
Text="{Binding NameP2}"
Grid.Row="1" Grid.Column="0"/>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Button Grid.Column="0"
Text="Start"/>
</Grid>
</StackLayout>
</ContentPage.Content>
code behind
namespace SampleApp.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class NameEntryPage : ContentPage
{
public NameEntryPage()
{
NavigationPage.SetHasNavigationBar(this, false);
InitializeComponent();
BindingContext = new NameEntryPageViewModel(Navigation, EntryNameP1.Text, EntryNameP2.Text);
}
}
}
VM code
public class NameEntryPageViewModel : INotifyPropertyChanged
{
public INavigation Navigation { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
var changed = PropertyChanged;
if (changed == null)
return;
changed.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private string nameP1;
public string NameP1
{
get
{
return NameP1;
}
set
{
if (NameP1 != value)
{
nameP1 = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("NameP1"));
}
}
}
private string nameP2;
public string NameP2
{
get
{
return NameP2;
}
set
{
if (NameP2 != value)
{
nameP2 = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("NameP1"));
}
}
}
public Command StartGameCommand { get; set; }
public NameEntryPageViewModel(INavigation navigation, string name1, string name2)
{
nameP1 = name1;
nameP2 = name2;
this.Navigation = navigation;
StartGameCommand = new Command(() => StartGame(nameP1, nameP2));
}
public NameEntryPageViewModel(INavigation navigation)
{
nameP1 = "Player 1";
nameP2 = "Player 2";
this.Navigation = navigation;
StartGameCommand = new Command(() => StartGame(nameP1, nameP2));
}
private void StartGame(string name1, string name2)
{
this.Navigation.PushAsync(new Views.TwoPlayerPage(name1, name2));
}
}
this will create an infinite loop
public string NameP1
{
get
{
return NameP1;
}
NameP1 will call the getter for NameP1, which calls the getter for NameP1, recursively until you crash
instead your getter should return the private nameP1 variable
public string NameP1
{
get
{
return namep1;
}
I try to rewrite my UWP C# app for Windows10 to Xamarin app using XAML. But Binding (for example here in ListView ItemSource=...) is not working for me and I don´t know why.
Visual Studio tells me, Cannot Resolve Symbol Recording due to unknown Data Context.
Here is my XAML (MainPage.xaml) for testing purpose:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:XamarinTest;assembly=XamarinTest"
x:Class="XamarinTest.MainPage">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="100" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="100" />
</Grid.ColumnDefinitions>
<ListView x:Name="listView" IsVisible="false" ItemsSource="{Binding Recording}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.View>
<StackLayout Orientation="Horizontal">
<Image Source="Accept" WidthRequest="40" HeightRequest="40" />
<StackLayout Orientation="Vertical" HorizontalOptions="StartAndExpand">
<Label Text="TEST" HorizontalOptions="FillAndExpand" />
<Label Text="TEST" />
</StackLayout>
</StackLayout>
</ViewCell.View>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
</ContentPage>
Here is C# (MainPage.xaml.cs):
namespace XamarinTest
{
public partial class MainPage : ContentPage
{
public MainPage()
{
this.InitializeComponent();
this.AllTestViewModel = new RecordingViewModel();
this.BindingContext = AllTestViewModel;
}
public RecordingViewModel AllTestViewModel { get; set; }
}
}
And finally ViewModel (RecordingViewModel.cs):
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using XamarinTest.Model;
namespace XamarinTest.ViewModel
{
public class RecordingViewModel : INotifyPropertyChanged
{
public ObservableCollection<Recording> Recordings { get; } = new TrulyObservableCollection<Recording>();
public RecordingViewModel()
{
Recordings.Add(new RecordingTest2()
{
TestName = "Test 1",
TestNote = "Vytvoreni DB",
TestTime = new TimeSpan(0, 0, 0)
});
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public sealed class TrulyObservableCollection<T> : ObservableCollection<T>
where T : INotifyPropertyChanged
{
public TrulyObservableCollection()
{
CollectionChanged += FullObservableCollectionCollectionChanged;
}
public TrulyObservableCollection(IEnumerable<T> pItems) : this()
{
foreach (var item in pItems)
{
this.Add(item);
}
}
private void FullObservableCollectionCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null)
{
foreach (Object item in e.NewItems)
{
((INotifyPropertyChanged)item).PropertyChanged += ItemPropertyChanged;
}
}
if (e.OldItems != null)
{
foreach (Object item in e.OldItems)
{
((INotifyPropertyChanged)item).PropertyChanged -= ItemPropertyChanged;
}
}
}
private void ItemPropertyChanged(object sender, PropertyChangedEventArgs e)
{
NotifyCollectionChangedEventArgs args = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, sender, sender, IndexOf((T)sender));
OnCollectionChanged(args);
}
}
}
Everything (models and viewmodels) are working in native UWP Windows 10 app. Only the Binding and making same view is problem in Xamarin. Could someone please help with binding?
Thx.
EDIT
Recording.cs is here:
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace XamarinTest.Model
{
public abstract class Recording : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public string TestName { get; set; }
private TimeSpan _testTime;
private string _testNote;
private string _actualIco = "Play";
private bool _isActive = false;
private bool _enabled = true;
public double IcoOpacity { get; private set; } = 1.0;
public string ActualIco
{
get => _actualIco;
set
{
if (_actualIco == null) _actualIco = "Admin";
_actualIco = value;
NotifyPropertyChanged("ActualIco");
}
}
public bool IsActive
{
get => _isActive;
set
{
if (_isActive == value) return;
_isActive = value;
IcoOpacity = !value ? 1.0 : 0.3;
NotifyPropertyChanged("IsActive");
NotifyPropertyChanged("IcoOpacity");
}
}
public bool Enabled
{
get => _enabled;
set
{
if (_enabled == value) return;
_enabled = value;
NotifyPropertyChanged("Enabled");
}
}
public string TestNote
{
get => _testNote;
set
{
if (_testNote == value) return;
_testNote = value;
NotifyPropertyChanged("TestNote");
}
}
public TimeSpan TestTime
{
get => _testTime;
set
{
if (_testTime == value) return;
_testTime = value;
NotifyPropertyChanged("TestTime");
}
}
protected Recording()
{
TestName = "Unkonwn";
TestNote = "";
_testTime = new TimeSpan(0, 0, 0);
}
protected Recording(string testName, string testNote, TimeSpan testTime)
{
TestName = testName;
TestNote = testNote;
_testTime = testTime;
}
public string OneLineSummary => $"{TestName}, finished: "
+ TestTime;
private void NotifyPropertyChanged(string propertyName = "")
{
var handler = PropertyChanged;
handler?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public abstract bool playTest();
}
}
I tried add DataContext in XAML (postet in origin question), because of intellisence like this:
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
xmlns:dvm="clr-namespace:XamarinTest.ViewModel"
xmlns:system="clr-namespace:System;assembly=System.Runtime"
d:DataContext="{system:Type dvm:RecordingViewModel}"
and this to Grid:
<Label Text="{Binding Recordings[0].TestName}" Grid.Row="0" Grid.Column="2" />
IntelliSence is OK, but text doesn´t show in app.
Finally is working!
XAML should looks like code below.
Imporant is xmls:viewModel="..." and <ContentPage.BindingContext>...</>.
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:viewModel="clr-namespace:XamarinTest.ViewModel;assembly=XamarinTest"
x:Class="XamarinTest.MainPage"
>
<ContentPage.BindingContext>
<viewModel:RecordingViewModel/>
</ContentPage.BindingContext>
<ListView x:Name="listView" ItemsSource="{Binding Recordings}" Grid.Row="1" Grid.Column="1">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.View>
<StackLayout Orientation="Horizontal">
<Image Source="Accept" WidthRequest="40" HeightRequest="40" />
<StackLayout Orientation="Vertical" HorizontalOptions="StartAndExpand">
<Label Text="{Binding TestName}" HorizontalOptions="FillAndExpand" />
<Label Text="{Binding TestNote}" />
</StackLayout>
</StackLayout>
</ViewCell.View>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
</ContentPage>
and MainPage.xaml.cs is okey
namespace XamarinTest
{
public partial class MainPage : ContentPage
{
public MainPage()
{
this.InitializeComponent();
this.AllTestViewModel = new RecordingViewModel();
this.BindingContext = AllTestViewModel;
}
public RecordingViewModel AllTestViewModel { get; set; }
}
}
looking at your ViewModel, it looks like there is no Recording member, but you do have a Recordings member.
EDIT
So you are adding your DataContext in the code behind so ignore the Xaml part.
Your View (MainPage.xaml) has a ViewModel(RecordingViewModel.cs). The ViewModel has a member called Recordings (a collection of type Recording). But in your Xaml, you are try to bind to Recording.
Change:
<ListView x:Name="listView" IsVisible="false" ItemsSource="{Binding Recording}">
to:
<ListView x:Name="listView" IsVisible="false" ItemsSource="{Binding Recordings}">
2nd EDIT
The only Labels in your example is the one inside of the ListView yes?
If so, you can access the Recordings children like TestNote by:
What i am doing is passing data through more than 2 pages. I assign viewmodel to next page while i am navigating. In second page i have a listview that is not refreshing/updating after adding a value.
Help me please!!
Here is my code
MyViewModel
public class MyViewModel : INotifyPropertyChanged
{
public string _userName { get; set; }
public List<family> familyList;
public List<family> FamilyList
{
get { return familyList; }
set
{
familyList = value;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
public MyViewModel()
{
_userName = "Mak";
familyList = new List<family>();
}
public void AddMember(string memberName)
{
FamilyList.Add(new family
{
name = memberName,
id = Guid.NewGuid().ToString(),
username=_userName
});
}
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
userdetails.xaml
<cl:BasePage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="familyinfo.userdetails" xmlns:cl="clr-namespace:familyinfo;assembly=familyinfo">
<Label Font="Roboto-Medium" FontSize="14" Text="{Bindinbg _userName}" />
<Button Clicked="Next_Step" HeightRequest="30" HorizontalOptions="FillAndExpand" BorderRadius="12" Text="NEXT" />
</cl:BasePage>
userdetails.xaml.cs
public partial class userdetails : BasePage
{
public MyViewModel _myViewModel { get; set; }
public userdetails()
{
InitializeComponent();
BindingContext = new MyViewModel();
}
void Next_Step(object sender, System.EventArgs e)
{
_myViewModel =(MyViewModel) this.BindingContext;
var familyMember = new FamilyMember();
familyMember.BindingContext = _myViewModel;
Application.Current.MainPage = new NavPage(registerCar);
}
}
FamilyMember.xaml
<cl:BasePage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="familyinfo.FamilyMember" xmlns:cl="clr-namespace:familyinfo;assembly=familyinfo">
<Label Font="Roboto-Medium" FontSize="14" Text="{Bindinbg _userName}" />
<cl:CustomEntry x:Name="txtMemberName" Placeholder="Member Name" FontSize="12" />
<Button Clicked="AddMember" HeightRequest="30" HorizontalOptions="FillAndExpand" BorderRadius="12" Text="Add" />
<ListView ItemsSource="{Binding FamilyList}" VerticalOptions="FillAndExpand" BackgroundColor="Transparent">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.View>
<Grid Padding="20,10,0,0" ColumnSpacing="12" RowSpacing="0" BackgroundColor="Transparent">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto">
</ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto">
</RowDefinition>
</Grid.RowDefinitions>
<Label Grid.Row="0" Text="{Binding name}" Grid.Column="0" Font="Roboto-Medium" FontSize="14" TextColor="#000000" />
</Grid>
</ViewCell.View>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</cl:BasePage>
FamilyMember.xaml.cs
public partial class FamilyMember : BasePage
{
public MyViewModel _myViewModel { get; set; }
public userdetails()
{
InitializeComponent();
}
void AddMember(object sender, System.EventArgs e)
{
_myViewModel = (MyViewModel)this.BindingContext;
_myViewModel.AddMember(txtMemberName.Text);
}
}
I agree with Atul: Using an ObservableCollection is the right way to do it.
A workaround - if you don't have a chance to change that - is to set the ListView's ItemSource to null and back to the list, whenever data changed and the UI needs to update:
void UpdateListView(ListView listView)
{
var itemsSource = listView.ItemsSource;
listView.ItemsSource = null;
listView.ItemsSource = itemsSource;
}
In fact, you must use a collection that implements INotifyCollectionChanged interface (instead of the well known INofifyPropertyChanged). And that's exactly what does ObservableCollection<T> for you. This is why it works like "magic".
I just used ObservableCollection instead of List and it works!!
I am developing an enterprise application using xamarin.forms. It has been few days ListView's Memory leak issue become a nightmare for me. For the sake of simplicity I'll try to explain with sample code.
XAML Page Code - Page with ListView and two Button(Add & Remove)
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:ListViewTest"
x:Class="ListViewTest.MainPage">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="10*" />
<RowDefinition Height="1*"/>
<RowDefinition Height="1*"/>
</Grid.RowDefinitions>
<ListView Grid.Row="0" BackgroundColor="White" x:Name ="ItemsListView">
<ListView.ItemTemplate>
<DataTemplate >
<TextCell TextColor="Black" Text="{Binding ItemText}"
DetailColor="Black" Detail="{Binding ItemDetail}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<Button Grid.Row="1" Text="Add" Clicked="AddItemClicked"/>
<Button Grid.Row="2" Text="Remove" Clicked="RemoveItemClicked"/>
</Grid>
</ContentPage>
C# Code Behind - Just adding and removing objects from collection.
public partial class MainPage : ContentPage
{
ObservableCollection<SampleData> itemsListCollection;
public MainPage()
{
InitializeComponent();
itemsListCollection = new ObservableCollection<SampleData>();
ItemsListView.ItemsSource = itemsListCollection;
}
void AddItemClicked(object sender, EventArgs e)
{
SampleData data = new SampleData();
data.ItemText = "An Item";
data.ItemDetail = "Item - " + (itemsListCollection.Count + 1).ToString();
itemsListCollection.Add(data);
}
void RemoveItemClicked(object sender, EventArgs e)
{
SampleData item = (SampleData)ItemsListView.SelectedItem;
if (item != null)
{
itemsListCollection.Remove(item);
}
}
}
Data class - Just two properties
class SampleData
{
public event PropertyChangedEventHandler PropertyChanged;
private string itemText;
public string ItemText
{
get
{
return itemText;
}
set
{
itemText = value;
NotifyPropertyChanged("ItemText");
}
}
private string itemDetail;
public string ItemDetail
{
get
{
return itemDetail;
}
set
{
itemDetail = value;
NotifyPropertyChanged("ItemDetail");
}
}
private void NotifyPropertyChanged(string propName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propName));
}
}
}
Add Button - Adds item to ListView
Remove Button - Removes item from ListView
Problem -
Add some items to list.
Remove few or all.
All previously added SampleData objects remain in memory even after all the items have
been removed using Remove button.
Image - Memory Snapshot of original application
Image - Detailed Memory Snapshot of sample application