Binding ViewModel field outside of Item Source - xamarin

Hi I have an ItemSource which binds a list of contact
<ListView x:Name="contactsListView" ItemsSource="{Binding contacts}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Horizontal">
<Image Source="{Binding Should be to my View Model instead of Contacts}"></Image>
<Label Text="{Binding FullName}"></Label>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
the Full Name binding works fine. My problem is the Image Source is not included in the Contact model so I need to retrieve that from my view Model How can I do it?
VIEW MODEL
public class ContactsViewModel : INotifyPropertyChanged
{
public ObservableCollection<Contact> contacts { get; set; }
private string _contactImage;
public string ContactImage
{
get => _contactImage; set
{
_contactImage = value;
OnPropertyChanged("ContactImage");
}
}
public ContactsViewModel(List<Contact> _contacts)
{
contacts = new ObservableCollection<Contact>(_contacts);
ContactImage = "arrow.png";
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
CODE BEHIND VIEW
public partial class ContactListPage : TabbedPage
{
public ContactsViewModel vm;
public ContactListPage (List<Contact> _contacts)
{
vm = new ContactsViewModel(_contacts);
BindingContext = vm;
InitializeComponent();
}
}

This is because the scope within a ListView item is different than a level higher. To overcome this, create a reference to a parent control. I see you already named your ListView, so we can use that.
Do it like this: <Image Source="{Binding Path=BindingContext.ContactImage, Source={x:Reference contactsListView}}"></Image>

Related

Updated list does not change on UI when PropertyChanged is called in Xamarin.Forms

I have a bindable StackLayout bound to a List in the ViewModel. When a button is pressed I am adding an element to the list and then invoking PropertyChanged with the name of the list.
I don't understand why the UI does not get updated in this case. I know that I should use an ObservableCollection, and I know how to do it, but I am curious about why the UI does not change if I am invoking PropertyChanged myself.
This is the ViewModel and Model class:
public class Element
{
public string Value { get; set; }
}
public class MainViewModel : INotifyPropertyChanged
{
public List<Element> Elements { get; set; }
public ICommand AddElementCommand { get; private set; }
public event PropertyChangedEventHandler PropertyChanged;
public MainViewModel()
{
AddElementCommand = new Command(AddElement);
Elements = new List<Element>();
Elements.Add(new Element { Value = "test1" });
}
void AddElement()
{
Elements.Add(new Element { Value = "testAgain" });
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Elements"));
}
}
And this is the view:
<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="TestList.MainPage"
x:Name="page">
<StackLayout>
<StackLayout Orientation="Horizontal">
<Label Text="Elements"
FontSize="Large"
HorizontalOptions="FillAndExpand"
VerticalOptions="Center"/>
<Button Command="{Binding AddElementCommand}"
Text="+" FontSize="Title"
VerticalOptions="Center"/>
</StackLayout>
<StackLayout BindableLayout.ItemsSource="{Binding Elements}">
<BindableLayout.ItemTemplate>
<DataTemplate>
<Entry Text="{Binding Value, Mode=TwoWay}" HorizontalOptions="FillAndExpand"/>
</DataTemplate>
</BindableLayout.ItemTemplate>
</StackLayout>
</StackLayout>
</ContentPage>
If we check the source code of ObservableCollection , we will see that it had implemented INotifyCollectionChanged and INotifyPropertyChanged in default while List didn't .
public class ObservableCollection<T> : Collection<T>, INotifyCollectionChanged, INotifyPropertyChanged
public class List<T> : ICollection<T>, IEnumerable<T>, IEnumerable, IList<T>, IReadOnlyCollection<T>, IReadOnlyList<T>, ICollection, IList
If a list will contain the same items for their whole lifetime, but the individual objects within that list will change, then it's enough for just the objects to raise change notifications (typically through INotifyPropertyChanged) and List is sufficient. But if the list will contain different objects from time to time, or if the order changes, then you should use ObservableCollection.
That is why we always suggest users to choose ObservableCollection instead of List .

Xamarin Picker inside ListView ItemDisplayBinding Binding: Property not found

I've a Picker inside a ListView with databinding:
<ListView
ItemsSource="{Binding CursorPrintParametersList}">
<ListView.ItemTemplate>
<DataTemplate x:DataType="models:CursorPrintParameters">
<ViewCell>
<Grid>
<Picker
ItemsSource="{Binding LabelTypes}"
SelectedItem="{Binding SelectedLabelType}"
ItemDisplayBinding="{Binding Description}"
/>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
where CursorPrintParametersList is
ObservableCollection<CursorPrintParameters> CursorPrintParametersList
and
public class CursorPrintParameters : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public List<BaseDto> LabelTypes { get; set; }
private BaseDto selectedLabelType;
public BaseDto SelectedLabelType
{
get => selectedLabelType;
set
{
if (value == null) return;
selectedLabelType = value;
RaisePropertyChanged(nameof(SelectedLabelType));
}
}
}
public class BaseDto
{
public string Code{ get; set; }
public string Description{ get; set; }
}
I'm unable to set the ItemDisplayBinding="{Binding Description}" for the Picker, getting a
Property 'Description' not found on 'CursorPrintParameters'
If i put the picker outside the ListView, everything works fine.
Any help? Thanks
i reproduce your issue in Xamarin.Forms version 3.6.0.34457
and the solution is delete below codes in DataTemplate :
x:DataType="models:CursorPrintParameters"
It is better to upgrade to the latest version if possible, as there may be some API changes
ItemDisplayBinding is the name of the property to use for the Display, not an actual binding expression
ItemDisplayBinding="Description"

Data binding for listview in xamarin

I am trying to populate listview with database table in xamarin forms app
I am getting null pointer exception
Below is XAML for listview
<ListView x:Name="_listView"
ItemsSource="{Binding itemsInList}"
Grid.Column="0"
Grid.Row="0"
SelectedItem="{Binding SelectedItem}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"/>
</Grid.ColumnDefinitions>
<Label Text="{Binding Name}" Grid.Column="0" Grid.Row="0" />
</Grid>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Below is xaml.cs(code behind)
public List <ServiceProvider> itemlist;
public List <ServiceProvider> itemsInList
{
get {return itemlist;}
}
protected override void OnAppearing()
{
base.OnAppearing();
ExpensesDatabase dbcon = new ExpensesDatabase(completePath);
itemlist = dbcon.GetItems(completePath);
// _listView.ItemsSource = itemlist;
}
Below is db file
public class ExpensesDatabase
{
readonly SQLiteConnection database;
public ExpensesDatabase(string dbPath)
{
database = new SQLiteConnection(dbPath);
database.CreateTable < ServiceProvider > ();
}
public List < ServiceProvider > GetItems(string dbPath)
{
return database.Table < ServiceProvider > ().ToList();
}
}
Data is not displayed in listview
If you want the ListView to automatically update as items are added, removed and changed in the underlying list, you'll need to use an ObservableCollection. ObservableCollection is defined in System.Collections.ObjectModel and is just like List, except that it can notify ListView of any changes:
public ObservableCollection<ServiceProvider> itemsInList { get; set; }
Then make sure you have set the right bindingContext and initialized the ObservableCollection:
public MainPage()
{
InitializeComponent();
itemsInList = new ObservableCollection<ServiceProvider>();
BindingContext = this;
}
I write a sample to test and it works on my side, you can have a look at the full code:
public partial class MainPage : ContentPage
{
public ObservableCollection<ServiceProvider> itemsInList { get; set; }
public MainPage()
{
InitializeComponent();
itemsInList = new ObservableCollection<ServiceProvider>();
BindingContext = this;
}
protected override void OnAppearing()
{
base.OnAppearing();
itemsInList.Add(new ServiceProvider() { Name= "a"});
}
}
public class ServiceProvider : INotifyPropertyChanged
{
string name;
public event PropertyChangedEventHandler PropertyChanged;
public ServiceProvider()
{
}
public String Name
{
set
{
if (name != value)
{
name = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Name"));
}
}
}
get
{
return name;
}
}
}
Feel free to ask me any question if you still can't solve it.

<ListView> of images - How open URL via TapGestureRecognizer?

How can we open a URL (via TapGestureRecognizer) that is bound to a of images?
My ListView's ItemsSource is _partners (type of List).
The Partner class has two properties - WebUrl and ImageUrl.
<ListView x:Name="partnersListView">
<ListView.ItemTemplate>
<DataTemplate>
<!--<ImageCell ImageSource="{Binding ImageUrl}" Text="{Binding WebUrl}" />-->
<ViewCell>
<Image Source="{Binding ImageUrl}">
<Image.GestureRecognizers>
<TapGestureRecognizer Tapped="Image_TapGestureRecognizer_Tapped" NumberOfTapsRequired="1" CommandParameter="{Binding .}" />
</Image.GestureRecognizers>
</Image>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
The list is showing images only, and I would like the app to navigate to a web site when the user taps the image. However, the following code - unsurprisingly - doesn't work.
private void Image_TapGestureRecognizer_Tapped(object sender, System.EventArgs e)
{
var tappedMenuItem = sender as MenuItem;
var partner = tappedMenuItem.CommandParameter as Partner;
Device.OpenUri(new Uri(partner.WebUrl));
}
Any suggestions, please?
Please note:
I want to keep the TapGestureRecognizer in XAML - not in the code-behind.
Thank you.
Best way to tackle this problem, is to bind the SelectedItem of the ListView to a property on your page.
So in your View
<ListView SelectedItem="{Binding SelectedPartner}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Image Source="{Binding ImageUrl}" />
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
And in the Code Behind
public Partner SelectedPartner
{
set
{
if (value != null)
Device.OpenUri(new System.Uri(value.WebUrl));
}
}
The list is showing images only, and I would like the app to navigate to a web site when the user taps the image. However, the following code - unsurprisingly - doesn't work.
CommandParameter is just for Command, you can't get it from a tap event handler. To accomplish your requirement, you can either use TappedCallback together with TappedCallbackParameter or use Command together with CommandParameter:
Method 1(TapppedCallback and TappedCallbackParameter):
Modify your Partner class to hold an Action<View,object>:
public class Partner
{
public Partner(string weburl, string imageurl)
{
this.WebUrl = weburl;
this.ImageUrl = imageurl;
}
public Partner(string weburl, string imageurl, Action<View, object> callback) : this(weburl, imageurl)
{
this.CallBack = callback;
}
public Action<View, object> CallBack { get; set; }
public string WebUrl { get; set; }
public string ImageUrl { get; set; }
}
In your code-behind, define a TappedCallback function like below and initialize the items source with the this function:
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
List<Partner> list = new List<Partner>
{
new Partner("http://www.url.com","timg.jpg",TappedCallback),
new Partner("http://www.url.com","timg.jpg",TappedCallback),
new Partner("http://www.url.com","timg.jpg",TappedCallback),
new Partner("http://www.url.com","timg.jpg",TappedCallback),
new Partner("http://www.url.com","timg.jpg",TappedCallback),
new Partner("http://www.url.com","timg.jpg",TappedCallback)
};
partnersListView.ItemsSource = list;
}
private void TappedCallback(View sender,object param)
{
var Partner = param as Partner;
Device.OpenUri(new Uri(Partner.WebUrl));
}
}
Use TappedCallback in Xaml:
<ListView x:Name="partnersListView">
<ListView.ItemTemplate>
<DataTemplate>
<!--<ImageCell ImageSource="{Binding ImageUrl}" Text="{Binding WebUrl}" />-->
<ViewCell>
<Image Source="{Binding ImageUrl}">
<Image.GestureRecognizers>
<TapGestureRecognizer TappedCallback="{Binding CallBack}" TappedCallbackParameter="{Binding .}" NumberOfTapsRequired="1" />
</Image.GestureRecognizers>
</Image>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Method 2(Command and CommandParameter):
Define an ICommand in your Partner class and constructor to accept ICommand:
public class Partner
{
public Partner(string weburl, string imageurl)
{
this.WebUrl = weburl;
this.ImageUrl = imageurl;
}
public Partner(string weburl, string imageurl, ICommand command) : this(weburl, imageurl)
{
this.TapCommand = command;
}
public string WebUrl { get; set; }
public string ImageUrl { get; set; }
public ICommand TapCommand { get; set; }
}
Create a MyCommand class to implement the ICommand interface :
public class MyCommand : ICommand
{
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
var Partner = parameter as Partner;
Device.OpenUri(new Uri(Partner.WebUrl));
}
}
In your code-behind initialize your items source with a new MyCommand object:
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
List<Partner> list = new List<Partner>
{
new Partner("http://www.url.com","timg.jpg",new MyCommand()),
new Partner("http://www.url.com","timg.jpg",new MyCommand()),
new Partner("http://www.url.com","timg.jpg",new MyCommand()),
new Partner("http://www.url.com","timg.jpg",new MyCommand()),
new Partner("http://www.url.com","timg.jpg",new MyCommand()),
new Partner("http://www.url.com","timg.jpg",new MyCommand())
};
partnersListView.ItemsSource = list;
}
}
Use Command in Xaml:
<ListView x:Name="partnersListView">
<ListView.ItemTemplate>
<DataTemplate>
<!--<ImageCell ImageSource="{Binding ImageUrl}" Text="{Binding WebUrl}" />-->
<ViewCell>
<Image Source="{Binding ImageUrl}">
<Image.GestureRecognizers>
<TapGestureRecognizer Command="{Binding TapCommand}" CommandParameter="{Binding .}" NumberOfTapsRequired="1" />
</Image.GestureRecognizers>
</Image>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>

ListView Xamarin not Binding when adding item

I Am working with a ListView Control in XF application. My XAML Code looks like this.
<ListView ItemsSource="{Binding RechargeList}" HasUnevenRows="True" VerticalOptions="FillAndExpand">
<ListView.ItemTemplate>
<DataTemplate>
<TextCell Text="{Binding Path=SelectedParkingID}" TextColor="Red" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
While my code behind looks like
private ObservableCollection<Recharge> _RechargeList = new ObservableCollection<Recharge>();
public ObservableCollection<Recharge> RechargeList
{
get
{
return _RechargeList;
}
set
{
SetProperty(ref _RechargeList, value);
}
}
And I add Items to Collection in DelegateCommand Event
RechargeList.Add(new Recharge() { SelectedParkingIDParkingID = ParkingID, RechargeAmount = double.Parse(RechargeAmount), BalanceAmount = 10 });
However, the Listview fails to refresh. Could some one help me ?
Looks like you have a typo
<TextCell Text="{Binding Path=SelectedParkingID}" TextColor="Red" />
Should be
<TextCell Text="{Binding Path=SelectedParkingIDParkingID }" TextColor="Red" />
based on what your model looks like. If you try to bind to a property that doesn't exist, it fails softly. So you're adding an item, but the TextCell doesn't render since it has no content.
Please try to implement INotifyPropertyChanged interface in your class.
public class Data : INotifyPropertyChanged
{
// boiler-plate
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
protected bool SetField<T>(ref T field, T value, string propertyName)
{
if (EqualityComparer<T>.Default.Equals(field, value)) return false;
field = value;
OnPropertyChanged(propertyName);
return true;
}
// props
private string name;
public string Name
{
get { return name; }
set { SetField(ref name, value, "Name"); }
}
}
Each property is then just something like:
private string name;
public string Name
{
get { return name; }
set { SetField(ref name, value, "Name"); }
}

Resources