Picker item source binding from view model - xamarin

I am trying to bind the values for a picker from a model in view model, there I am getting path of the model instead of the values.
<Picker x:Name="LocationPicker"
Title="Location" HeightRequest="40"
HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand"
SelectedItem="{Binding Location}"
ItemsSource="{Binding MaintainRoomTypes}"/>
Here is my view model code:
if (jobDetailsForFitter != null)
{
WindowDetails = new WindowDetailsModel
{
Windows = jobDetailsForFitter.Windows,
Locations = jobDetailsForFitter.Locations,
RoomTypes = jobDetailsForFitter.RoomTypes,
AddFiles = jobDetailsForFitter.AddFiles
};
Locations = jobDetailsForFitter.Locations;
MaintainRoomTypes = jobDetailsForFitter.RoomTypes;
await FitterService.Instance.LoadJobDetailsToLocalStore(jobDetailsForFitter, SelectedJob?.Id ?? 0);
}
how to bind itemsource to get list.
public List<Room> Locations { get; set; }
public List<RoomTypeModel> RoomTypes { get; set; }

You have to define ItemDisplayBinding property to Picker.
For eg:
public class Room
{
public string RoomNumber { private set; get; }
public string RoomName { private set; get; }
}
And you want to display RoomName in Picker
<Picker ItemsSource="{Binding Room}" ItemDisplayBinding="{Binding RoomName}"/>
Hope this will solve your problem.

Related

Binding in Code Behind with Master/Detail Template

I've generated a Master/Detail view app (via Master Detail template of Xamarin, Visual Studio 2019) and I'm trying to perform data binding in Code Behind instead of XAML in the Detail view in order to retrieve and show the "Description" entry:
Therefore I modified my ItemDetailPage.xaml as follows (commented out the section):
<?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="MDDummy.Views.ItemDetailPage"
Title="{Binding Title}">
<!--
<StackLayout Spacing="20" Padding="15">
<Label Text="Text:" FontSize="Medium" />
<Label Text="{Binding Item.Text}" FontSize="Small"/>
<Label Text="Description:" FontSize="Medium" />
<Label Text="{Binding Item.Description}" FontSize="Small"/>
</StackLayout>
-->
</ContentPage>
In the code behind ItemDetailPage.xaml.cs I inserted the following:
namespace MDDummy.Views
{
public partial class ItemDetailPage : ContentPage
{
ItemDetailViewModel viewModel;
public ItemDetailPage(ItemDetailViewModel viewModel)
{
InitializeComponent();
BindingContext = this.viewModel = viewModel;
var layout = new StackLayout
{
Spacing = 40,
Padding = new Thickness(20, 20, 20, 20),
Orientation = StackOrientation.Horizontal
};
var testLabel = new Label();
testLabel.SetBinding(Label.TextProperty, "Description");
testLabel.BindingContext = new {Description = "{Binding Item.Description}"};
layout.Children.Add(testLabel);
Content = layout;
}
}
}
in order to show the "Description" entry via Data Binding. However other than in the xaml file I can't seem to access the related data entry, here "Description" from the Models folder Items.cs
namespace MDDummy2.Models
{
public class Item
{
public string Id { get; set; }
public string Text { get; set; }
public string Description { get; set; }
}
}
and MockDataStore.cs (where the Description entry is located I intend to display in the Detail view).
How can I access the data field, for instance "Description" in code behind in order to show it in the Detail view? Your help is greatly appreciated!
What is the ItemDetailViewModel? You set Label text binding by testLabel.BindingContext = new {Description = "{Binding Item.Description}"};I think it is mistake.
I do one sample about using binding by code behind, you can take a look:
public partial class Page8 : ContentPage
{
private ItemDetailViewModel viewmodel;
public Page8()
{
InitializeComponent();
viewmodel = new ItemDetailViewModel()
{
item = new Item() { Id = "1", Text = "this is item1", Description = "item class description" },
m1 = new model1() {Id="2",Text="this is model1",Description="model1 class description." }
};
var layout = new StackLayout
{
Spacing = 40,
Padding = new Thickness(20, 20, 20, 20),
Orientation = StackOrientation.Horizontal
};
var testLabel = new Label();
testLabel.SetBinding(Label.TextProperty, new Binding("Description",source:viewmodel.item) );
layout.Children.Add(testLabel);
var testLabel1 = new Label();
testLabel1.SetBinding(Label.TextProperty, new Binding("Description",source:viewmodel.m1));
layout.Children.Add(testLabel1);
Content = layout;
this.BindingContext = viewmodel;
}
}
public class Item
{
public string Id { get; set; }
public string Text { get; set; }
public string Description { get; set; }
}
public class model1
{
public string Id { get; set; }
public string Text { get; set; }
public string Description { get; set; }
}
public class ItemDetailViewModel
{
public Item item { get; set; }
public model1 m1 { get; set; }
}

How to modify specific ListView items to post back to db - MVVM

I have ListView with Button showing status A(Absent), P(Present) and L(Late) for each item. On Button click status Text getting changed P to A, A to L.
When changing status of any item, I have to change AttendanceId, AttendanceTypeStatusCD, AttendanceTypeStatusId fields for for the same record. This I have to do for multiple records. I need to update my ListView's source StudentList according to action performed and post modified data to db.
<ListView x:Name="list1" ItemsSource="{Binding StudentList}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout>
<Image Source="other.png" />
<Label Text="{Binding StudentName}" />
<Button x:Name="mybtn"
BindingContext="{Binding Source={x:Reference list1}, Path=BindingContext}"
Command="{Binding BtnTextCommand}"
CommandParameter="{Binding Source={x:Reference mybtn}}"
Text="{Binding AttendanceTypeStatusId, Converter={x:StaticResource IDToStringConverter}}" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
This is my model class
public class Student
{
public int? StudentId { get; set; }
public string StudentName { get; set; }
public int? AttendanceTypeStatusId { get; set; }
public string ClassLevelCd { get; set; }
public int? StudentDailyAttendanceId { get; set; }
public int? AbsentReasonId { get; set; }
public string AttendanceTypeStatusCD { get; set; }
public string Name { get; set; }
public string LoggedInUser { get; set; }
public string ImageValue { get; set; }
public string FirstName { get; set; }
}
This is the method in ViewModel in to change specific item text
public void SetBtnText(object sender)
{
var view = sender as Xamarin.Forms.Button;
if (view.Text == "P")
{
view.Text = "A";
AbsentReasonId = "3001";
AttendanceTypeStatusCD= "Absent";
AttendanceTypeStatusId = "3002";
}
else if (view.Text == "A")
{
view.Text = "L";
AbsentReasonId= "2001";
AttendanceTypeStatusCD = "Late";
AttendanceTypeStatusId = "2002";
}
else
{
view.Text = "P";
AbsentReasonId = "4001";
AttendanceTypeStatusCD = "Present";
AttendanceTypeStatusId = "4002";
}
}
//Above used properties
private string _absentReasonId;
public string AbsentReasonId
{
get { return _absentReasonId; }
set { SetProperty(ref _absentReasonId, value); }
}
private string _attendanceTypeStatusCD;
public string AttendanceTypeStatusCD
{
get { return _attendanceTypeStatusCD; }
set { SetProperty(ref _attendanceTypeStatusCD, value); }
}
private int _attendanceTypeStatusId;
public int AttendanceTypeStatusId
{
get{return _attendanceTypeStatusId;}
set { SetProperty(ref _attendanceTypeStatusId, value); }
}
The above process is not working, SutdentList source not getting changed, How can I do that using MVVM?
Student list screenshot

Xamarin Forms Bind Array element inside listView

need to ask you a hand with this one.
I'm currently developing a Xamarin Forms solution using MVVM and i'm in a new situation right now.
I've got a listView with items made by this class
public class City
{
public int Key { get; set; }
public string Value { get; set; }
public List<string> Words{ get; } = new List<string> { "One", "Two", "Three" };
}
What I want to achieve is to display a label text created using the Words list elements indicized by Key. Something like
Words[Key]
Example
<ListView
ItemsSource="{Binding Cities}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout
HorizontalOptions="FillAndExpand"
VerticalOptions="StartAndExpand">
<Label Text="{Binding Words[Key]}"
FontSize="18"
TextColor="Black"
VerticalOptions="StartAndExpand" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
The label text binding doesn't work, but tecnically is what i need to achieve. For example, if i use Words[0] it will work and returns 'One'
My ViewModel is pretty simple.
public class TestViewModel : INotifyPropertyChanged
{
public ObservableCollection<City> Cities { get; set; }
public TestViewModel()
{
Cities = GetCities();
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string name = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
public ObservableCollection<City> GetCities()
{
return new ObservableCollection<City>
{
new City {Key = 1, Value = "Mumbai"},
new City {Key = 2, Value = "New York"},
new City {Key = 3, Value = "Milan"},
new City {Key = 4, Value = "Rome"}
};
}
}
Do i need to create a property for indexing? In my opinion the problem is that i'm inside a list and already have an index to use.
Thanks for help guys
You can modify your model :
public class City
{
public int Key { get; set; }
public string Value { get; set; }
public List<string> Words { get; } = new List<string> { "One", "Two", "Three" };
public string myValue
{
get
{
return Words[Key];
}
set {}
}
}
And in your .xmal, just set Text="{Binding myValue}" and it will display a list element value of Words.

Trying to get the value of a picker's selectedItem within a listview (MVVM)

Need some direction/help here guys. Similar to a basic contacts app - I'm building a customer entry screen and need a drop down for contact types (phone, email, etc). I figured out how to populate the picker(s) by explicitly defining the path and source but I can't seem to get SelectedItem to do anything. My expectation is set the default value of the picker with whats in the record and also be able to change that value.
<ListView x:Name="ContactListView" ItemsSource="{Binding Customer.ContactList}" >
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.View>
<StackLayout>
<Picker
ItemsSource="{Binding Path=BindingContext.ContactTypes, Source={x:Reference ContactListView} }"
ItemDisplayBinding="{Binding TypeName}"
SelectedItem="{Binding TypeName, Mode=TwoWay}"
/>
<Entry Text="{Binding Value}" />
</StackLayout>
</ViewCell.View>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
The ViewModel attached to this page is a Customer object which has a nested contact list in it (defined at the list view). Below is a basic version of the Customer Class that I'm using on the page with its relationship to ContactTypes.
public class Customer
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string AddressLine { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Country { get; set; }
public List<Contact> ContactList { get; set; }
}
public class ContactType
{
public string TypeName { get; set; }
public int SortOrderId { get; set; }
}
public class Contact : ContactType
{
public int Id { get; set; }
public string Value { get; set; }
}
When the Page ViewModel loads, I store a list of possible ContactTypes (one time) that the user can choose from and it's shared in each picker as the item source. The list of possible ContactTypes from the database are stored in a local variable - here's the static representation of it:
public IList<ContactType> ContactTypes { get; } = new List<ContactType>
{
new ContactType(){ TypeName = "Home Phone", SortOrderId = 1 },
new ContactType(){ TypeName = "Cell Phone", SortOrderId = 2 },
new ContactType(){ TypeName = "Work Phone", SortOrderId = 3 },
new ContactType(){ TypeName = "Email", SortOrderId = 4 },
new ContactType(){ TypeName = "Fax", SortOrderId = 5 }
};
I need the picker to show the options from ContactTypes, and when an Item is Selected, it updates the TypeName property of the current record iteration in ContactList.

Binding custom class to listbox from custom class

I have these classes:
public class MovieExt
{
public string Title { get; set; }
public string Year { get; set; }
public List<string> Genres { get; set; }
public List<Actor> Actors { get; set; }
....
}
public class Actor
{
public string Name { get; set; }
public string Birth { get; set; }
public string Biography { get; set; }
public string Url { get; set; }
}
and this is my method in my page:
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
object obj;
if (PhoneApplicationService.Current.State.TryGetValue("movie", out obj))
{
MovieExt movie = (MovieExt)obj;
this.DataContext = movie;
this.imgPoster.Source = new BitmapImage(new Uri(movie.PosterUrl, UriKind.Absolute));
}
base.OnNavigatedTo(e);
}
and in page I am binding properties like this:
<ListBox Grid.Row="4" Grid.Column="1"
Margin="5,5,5,5"
ItemsSource="{Binding Path=Actors }"
x:Name="listStars"/>
For everything it´s working (genres and others). Everything else is string. But for actors I want to bind in list name and after clicking on the actor I want to go to url. How can I bind name property from actor? Thanks
First of all, you need to create OnSelectedItemChanged event on your ListBox to handle clicks on your Actors.
Then you need to get your clicked item. You can do this in several ways. The simplest way is listBox.SelectedItem property.
And then your can get your Url with (listBox.SelectedItem as Actor).Url
Also, when you go back from details page, SelectedItem will be not null and click on the same item not fired event in second time. So, set SelectedItem to null when click is handled
UPD: to properly bind Actor class to ListBox you need to create ItemTemplate:
<ListBox ...>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text={Binding Name} />
<TextBlock Text={Binding Birth} />
<TextBlock Text={Binding Biography} />
<TextBlock Text={Binding Url} />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
You can override the ToString() method in the Actor class to display something friendly, like the name.
public override string ToString()
{
return Name;
}
This is useful when binding objects to comboboxes and dropdowns.

Resources