LongListSelector ItemsSource not working - c#

In my Windows Phone 8.1 store app I am having trouble to show values in LongListSelector. Here is .xaml and .cs files.
Am I missing something?
<controls:LongListSelector Grid.Row="0" Grid.Column="0" VerticalAlignment="Stretch"
DataContext="{Binding ElementName=PageWorld}"
ItemsSource="{Binding Countries}" RenderTransformOrigin="0.5,0.5" BorderBrush="Blue" BorderThickness="2">
<controls:LongListSelector.RenderTransform>
<CompositeTransform/>
</controls:LongListSelector.RenderTransform>
<controls:LongListSelector.ItemTemplate>
<DataTemplate>
<ListBoxItem Margin="0,6,0,6">
<StackPanel>
<TextBlock Text="{Binding Title}" TextWrapping="NoWrap" Foreground="Black"/>
</StackPanel>
</ListBoxItem>
</DataTemplate>
</controls:LongListSelector.ItemTemplate>
</controls:LongListSelector>
In code behing I am binding values as follows.
private ObservableCollection<Country> _countries;
public ObservableCollection<Country> Countries
{
get { return _countries; }
set
{
_countries = value;
OnPropertyChanged();
}
}
public World()
{
InitializeComponent();
navigationHelper = new NavigationHelper(this);
navigationHelper.LoadState += this.NavigationHelper_LoadState;
navigationHelper.SaveState += this.NavigationHelper_SaveState;
Countries = GetCountries();
}
public class Country
{
public string Title { get; set; }
}
private ObservableCollection<Country> GetCountries()
{
ObservableCollection<Country> countries = new ObservableCollection<Country>();
for (int i = 0; i < 100; i++)
{
Country country = new Country();
country.Title = "Name" + i;
countries.Add(country);
}
return countries;
}

Related

Get individual Id for every item in list

I have a list view with one item for this moment.
<ContentPage.Content>
<StackLayout>
<ListView x:Name="MyListView"
CachingStrategy="RecycleElement"
SelectionMode="Single">
<ListView.ItemTemplate>
<DataTemplate>
<TextCell Text="{Binding Text}" Detail="{Binding Detail}" Something to identify item individually ??? />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<Button Text="Commencer" VerticalOptions="End" HorizontalOptions="Center" Clicked="StartProcessButton"/>
</StackLayout>
</ContentPage.Content>
I want to get an id or name or something who can individually get this item in my viewModel.
For example If I have an id system on this item :
void Action() {
if (listView.itemSelected.id == 1) {
then ....
}
}
I'm looking for this kind of thing. I checked google but I didn't found something for me.
You could create a id property.
Contact.cs
public class Contacts
{
private int id;
public int Id
{
get { return id; }
set { id = value; }
}
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private string address;
public string Address
{
get { return address; }
set { address = value; }
}
private string image;
public string Image
{
get { return image; }
set { image = value; }
}
}
MainPage.xaml
<ListView
x:Name="ContactsList"
IsVisible="True"
ItemsSource="{Binding MyList}" ItemSelected="ContactsList_ItemSelected">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Horizontal">
<Image
HeightRequest="50"
Source="{Binding Image}"
WidthRequest="50" />
<Label Text="{Binding Id}" />
<Label Text="{Binding Name}" />
<Label Text="{Binding Address}" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
MainPage.xaml.cs
public partial class MainPage : ContentPage
{
private ObservableCollection<Contacts> myList;
public ObservableCollection<Contacts> MyList
{
get { return myList; }
set { myList = value; }
}
public MainPage()
{
InitializeComponent();
this.BindingContext = this;
MyList = new ObservableCollection<Contacts>();
for (int i = 1; i < 10; i++)
{
MyList.Add(new Contacts() { Id = i, Name = "Student" + i.ToString(), Address = "Address" + i.ToString(), Image = "usa.png" });
}
ContactsList.ItemsSource = MyList;
}
private void ContactsList_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
var item = (Contacts)e.SelectedItem;
if (item.Id == 1)
{
//.......do something you want
DisplayAlert("Id", "the id of item is 1", "Cancel");
}
}
}
In the ContactsList_ItemSelected event, you could get the ID from the e.SelectedItem. I use DisplayAlert to show the result.

WPF XAML can not see checkboxes in ListView

I'm working on a small WPF project,
for now it contains one window which should display as much checkboxes are many values in lists are.
For testing purposes, before I get values from database I tried something like this:
public class StatusOption
{
public string name { get; set; }
public bool IsSelected { get; set; }
}
public void GetSerialNumbers()
{
List<StatusOption> serialNumbers = new List<StatusOption>();
for(int i = 0; i<10;i++)
{
StatusOption x = new StatusOption();
x.name = "Random name" + i;
x.IsSelected = false;
serialNumbers.Add(x);
}
}
And my xaml looks like this:
<ListBox x:Name="SerialNumbersListBox"
AllowDrop="True"
Grid.ColumnSpan="2"
Grid.Row="2"
ItemsSource="{Binding GetSerialNumbers}">
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox Content="{Binding serialNumbers}"
IsChecked="{Binding IsSelected}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
But unfortunatelly nothing is displayed below textbox...
But for now everything is empty, and I can not find out why..
Thanks guys
Cheers
You could not bind a method. Please use property instead.
<ListBox HorizontalAlignment="Left" Height="171" Margin="334,96,0,0" VerticalAlignment="Top" Width="248" AllowDrop="True" x:Name="SerialNumbersListBox"
ItemsSource="{Binding SerialNumbers}">
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox Content="{Binding name}"
IsChecked="{Binding IsSelected}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
public class SerialNumbersListBoxViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public class StatusOption
{
public string name { get; set; }
public bool IsSelected { get; set; }
}
private ObservableCollection<StatusOption> _SerialNumbers;
public ObservableCollection<StatusOption> SerialNumbers
{
get
{
return _SerialNumbers;
}
set
{
if (value != _SerialNumbers)
{
_SerialNumbers = value;
OnPropertyChanged(nameof(SerialNumbers));
}
}
}
public void GetSerialNumbers()
{
if (_SerialNumbers == null)
_SerialNumbers = new ObservableCollection<StatusOption>();
for (int i = 0; i < 10; i++)
{
StatusOption x = new StatusOption();
x.name = "Random name" + i;
x.IsSelected = false;
_SerialNumbers.Add(x);
}
}
protected void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public SerialNumbersListBoxViewModel()
{
GetSerialNumbers();
}
}
You can refer this link for more details
Regard!
You cannot bind to methods, you can only bind to Properties or DependencyProperties.
So you need to create a Property for your serialNumbers. You should also implement INotifyPropertyChanged, so that the ListBox can know when your property changed.
public List<object> SerialNumbers
{
get => this._serialNumbersProperty;
set
{
if (!List<object>.Equals(value, this._serialNumbersProperty))
{
this._serialNumbersProperty = value;
OnPropertyChanged(nameof(this.SerialNumbers));
}
}
}
<ListBox x:Name="SerialNumbersListBox"
AllowDrop="True"
Grid.ColumnSpan="2"
Grid.Row="2"
ItemsSource="{Binding SerialNumbers}">
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox Content="{Binding name}"
IsChecked="{Binding IsSelected}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

Get data from selected item in ListView

I have the following C# code that generate an items for list view:
//function that generated items for list view
results = //An array
foreach (var item in results)
{
var nameStr = item.FirstName + " " + item.LastName;
var descriptionStr = item.Email;
IconTextGrid.Items.Add(new { Name = nameStr, Description = descriptionStr });
}
And the XAML:
<Page.Resources>
<DataTemplate x:Key="IconTextDataTemplate">
<StackPanel Orientation="Horizontal" Width="220" Height="60" Background="#FF7CC6FF">
<StackPanel Orientation="Vertical" VerticalAlignment="Center">
<TextBlock Text="{Binding Name}" Margin="10,0,0,0" Width="170" Height="20" TextTrimming="WordEllipsis"/>
<TextBlock Text="{Binding Description}" Margin="10,0,0,0" Width="170" Height="20" TextTrimming="WordEllipsis"/>
</StackPanel>
</StackPanel>
</DataTemplate>
</Page.Resources>
<ListView x:Name="IconTextGrid" SelectionMode="Multiple" ItemTemplate="{StaticResource IconTextDataTemplate}" Height="400" Grid.Row="5" Margin="40,20,40,10" HorizontalAlignment="Stretch" Foreground="White" SelectionChanged="IconTextGrid_SelectionChanged">
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<ItemsWrapGrid MaximumRowsOrColumns="6"/>
</ItemsPanelTemplate>
</ListView.ItemsPanel>
</ListView>
and:
private void SendRequests_Click(object sender, RoutedEventArgs e)
{
string emailAdress;
for (int i = 0; i < IconTextGrid.SelectedItems.Count; i++)
{
//I need to get the description of the selected items
}
}
My question is how Ican get the value of the Description field in the item that generated?
Thanks
You can create custom type like this:
class MyType
{
string Name { get; set; }
string Description { get; set; }
}
Then change your code to:
IconTextGrid.Items.Add(new MyType{ Name = nameStr, Description = descriptionStr });
And now you can get description:
for (int i = 0; i < IconTextGrid.SelectedItems.Count; i++)
{
var item = (MyType)IconTextGrid.SelectedItems[i];
string description = item.Description;
}
You are using an anonymous type ofr the items in your listbox:
IconTextGrid.Items.Add(new { Name = nameStr, Description = descriptionStr });
You should declare a class:
public class MyItem
{
public string Name { get; set; }
public string Description { get; set; }
}
and use this class instead:
IconTextGrid.Items.Add(new MyItem { Name = nameStr, Description = descriptionStr });
The you can get SelectedItem and cast it to MyItem.

WPF Update Listbox Databinding

I'm new to WPF and am working on Databinding a Listbox from a xml file, everything loads correctly when the program starts, however I'm having trouble making the listbox update after I insert a new record. Everything that I've read is pointing to use a ObservableCollection which I am, but I can't figure out how to get the Listbox to refresh. I have tried calling a update to the ItemsSource but it still doesn't seem to work. Ideally I would like to just have a Refresh button that A user can click to update the listbox. Does anyone have any suggestions on a calling a update to the list box
Thanks Michael
public class ContactList
{
string contactFile = #"U:\Peridot\Users\" + Program.getUser.ToString() + ".xml";
public ContactList()
{
}
public ContactList(string contactFullName, string contactCellNumber,string contactBusinessNumber, string contactExtension, string contactEmail, string contactStatus,string contactAuralinkStatus, string contactAuralinkID)
{
this.ContactFullName = contactFullName;
this.ContactCellNumber = contactCellNumber;
this.ContactBusinessNumber = contactBusinessNumber;
this.ContactExtension = contactExtension;
this.ContactEmail = contactEmail;
this.ContactStatus = contactStatus;
this.ContactAuralinkStatus = contactAuralinkStatus;
this.ContactAuralinkID = contactAuralinkID;
}
private string ContactFullName;
public string PropContactFullName
{
get { return ContactFullName; }
set { ContactFullName = value; }
}
private string ContactCellNumber;
public string PropContactCellNumber
{
get { return ContactCellNumber; }
set { ContactCellNumber = value; }
}
private string ContactBusinessNumber;
public string PropContactBusinessNumber
{
get { return ContactBusinessNumber; }
set { ContactBusinessNumber = value; }
}
private string ContactEmail;
public string PropContactEmail
{
get { return ContactEmail; }
set { ContactEmail = value; }
}
private string ContactStatus;
public string PropContactStatus
{
get { return ContactStatus; }
set { ContactStatus = value; }
}
private string ContactAuralinkStatus;
public string PropContactAuralinkStatus
{
get { return ContactAuralinkStatus; }
set { ContactAuralinkStatus = value; }
}
public string ContactAuralinkID;
public string PropContactAuralinkID
{
get { return ContactAuralinkID; }
set { ContactAuralinkID = value; }
}
private string ContactExtension;
public string PropContactExtension
{
get { return ContactExtension; }
set { ContactExtension = value; }
}
}
public class Contacts : System.Collections.ObjectModel.ObservableCollection<ContactList>
{
string contactFile = #"U:\Peridot\Users\" + Program.getUser.ToString() + ".xml";
//Added this
public event NotifyCollectionChangedEventHandler CollectionChanged;
protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
if (CollectionChanged != null)
{
CollectionChanged(this, e);
}
}
public Contacts(): base()
{
getContactFile();
XDocument doc = XDocument.Load(contactFile);
var contacts = from r in doc.Descendants("Contact")
select new
{
FullName = r.Element("FullName").Value,
CellNumber = r.Element("CellNumber").Value,
BusinessNumber = r.Element("BusinessNumber").Value,
Extension = r.Element("Extension").Value,
Email = r.Element("Email").Value,
AuralinkID = r.Element("AuralinkID").Value
};
foreach (var r in contacts)
{
Add(new ContactList(r.FullName,r.CellNumber , r.BusinessNumber,r.Extension, r.Email, "", "",r.AuralinkID));
}
}
private void getContactFile()
{
if (!File.Exists(contactFile))
{
new XDocument(
new XElement("Contacts"
)
)
.Save(contactFile);
}
}
}
private void addContactICON_MouseDown(object sender, MouseButtonEventArgs e)
{
if (!doesContactExist())
{
try
{
XDocument doc = XDocument.Load(#"U:\Peridot\Users\" + Program.getUser.ToString() + ".xml");
XElement contact = new XElement("Contact");
contact.Add(new XElement("ContactID", contactID.ToString()));
contact.Add(new XElement("FullName", contactNameLBL.Content.ToString()));
contact.Add(new XElement("CellNumber", c1.Content.ToString()));
contact.Add(new XElement("BusinessNumber", businessPhoneIcon.ToolTip.ToString()));
contact.Add(new XElement("Extension", c3.Content.ToString()));
contact.Add(new XElement("Email", emailIcon.ToolTip.ToString()));
contact.Add(new XElement("AuralinkID", videoIcon.ToolTip.ToString()));
doc.Element("Contacts").Add(contact);
doc.Save(#"U:\Peridot\Users\" + Program.getUser.ToString() + ".xml");
MessageBox.Show(contactNameLBL.Content.ToString() + " has been added to your contacts.");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
else
MessageBox.Show("Contact Already Exists");
}
XAML
<StackPanel>
<StackPanel.Resources>
<local:Contacts x:Key="contactListobj"></local:Contacts>
</StackPanel.Resources>
<ListBox x:Name="contactList" Width="305" Margin="5,3,0,0" VerticalAlignment="Top" HorizontalAlignment="Left" ItemsSource="{Binding Source={StaticResource contactListobj}}" Height="450" IsSynchronizedWithCurrentItem="True">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" >
<TextBlock Text="{Binding PropContactFullName}" ToolTip="{Binding PropContactFullName}" Height="35" Width="175" FontSize="12"/>
<TextBlock x:Name="contactEmailLBL" Text="{Binding PropContactEmail}" ToolTip="{Binding PropContactEmail}" Cursor="Hand" Width="30" Height="35" MouseLeftButtonUp="contactEmailLBL_MouseLeftButtonUp" Foreground="{x:Null}" FontSize="1">
<TextBlock.Background>
<ImageBrush Stretch="Uniform" ImageSource="Images/emailICON.png"/>
</TextBlock.Background>
</TextBlock>
<TextBlock x:Name="cellNumberLBL" Text="{Binding PropContactCellNumber}" ToolTip="{Binding PropContactCellNumber}" Cursor="Hand" MouseLeftButtonUp="cellNumberLBL_MouseLeftButtonUp" Width="30" Height="35" Foreground="{x:Null}" FontSize="1">
<TextBlock.Background>
<ImageBrush Stretch="Uniform" ImageSource="Images/mobilePhoneICON.png"/>
</TextBlock.Background>
</TextBlock>
<TextBlock x:Name="businessNumberLBL" Text="{Binding PropContactBusinessNumber}" ToolTip="{Binding PropContactBusinessNumber}" Cursor="Hand" Width="30" Height="35" MouseLeftButtonUp="businessNumberLBL_MouseLeftButtonUp" Foreground="{x:Null}" FontSize="1">
<TextBlock.Background>
<ImageBrush Stretch="Uniform" ImageSource="Images/BusinessPhoneICON.png"/>
</TextBlock.Background>
</TextBlock>
<TextBlock x:Name="auralinkLBL" Text="{Binding PropContactAuralinkID}" ToolTip="{Binding PropContactAuralinkID}" Cursor="Hand" Width="30" Height="35" Foreground="{x:Null}" FontSize="1" MouseLeftButtonUp="auralinkLBL_MouseLeftButtonUp">
<TextBlock.Background>
<ImageBrush Stretch="Uniform" ImageSource="Images/VideoICON.png"/>
</TextBlock.Background>
</TextBlock>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
From what I can tell based on the source code for ObservableCollection, the problem is most likely that the Add method you are using to add ContactList objects to your ObservableCollection is part of the Collection class that ObservableCollection inherits from. This does not fire the CollectionChanged event on the ObservableCollection so your binding is never notified that the collection has changed. Try calling the OnCollectionChanged protected method after you add each item to the collection.

How to set the longitude and latitude from ViewModel in bing maps in windows phone 7

I want to give the longitude and latitude from ViewModel.
Now i am using like:-
private void button1_Click(object sender, RoutedEventArgs e)
{
Pushpin p = new Pushpin();
p.Background = new SolidColorBrush(Colors.Yellow);
p.Foreground = new SolidColorBrush(Colors.Black);
p.Location = new GeoCoordinate(double.Parse(longitude.Text), double.Parse(latitude.Text));//Longitude and Latitude
p.Content = "I'm here";//To show the place where it is located
map1.Children.Add(p);
map1.SetView(new GeoCoordinate(double.Parse(longitude.Text), double.Parse(latitude.Text), 200), 9);
}
My Xaml is:-
<Grid x:Name="MapPageUIContainer" Grid.Row="1" Margin="2,0,2,0">
<my:Map CopyrightVisibility="Collapsed" LogoVisibility="Collapsed" CredentialsProvider="" Mode="AerialWithLabels" Height="543" HorizontalAlignment="Left" Name="map1" VerticalAlignment="Top" Width="480" Margin="2,100,0,0" />
<Border BorderBrush="Silver" BorderThickness="1" Height="100" HorizontalAlignment="Left" Margin="0,0,0,0" Name="border1" VerticalAlignment="Top" Width="476" Background="#FFA3A371">
<TextBlock Text="Map Example" HorizontalAlignment="Center" FontSize="32" FontWeight="Bold" VerticalAlignment="Center" />
</Border>
<TextBox Height="72" HorizontalAlignment="Left" Margin="6,627,0,0" Name="longitude" Text="" VerticalAlignment="Top" Width="200" />
<TextBox Height="72" HorizontalAlignment="Left" Margin="260,627,0,0" Name="latitude" Text="" VerticalAlignment="Top" Width="200" />
<Button Content="Set" HorizontalAlignment="Left" Margin="190,690,0,0" Name="button1" VerticalAlignment="Top" Click="button1_Click" />
</Grid>
Here i want to give the Pushpin, longitude, latitude from view model. Please let me know how to achieve this?
Thanks in advance..
I have try like this..
public class MapPageViewModel : ReactiveObject
{
public static string _longitude;
public string longitude
{
get { return _longitude; }
set { this.RaiseAndSetIfChanged(x => x.longitude, value); }
}
public static string _latitude;
public string latitude
{
get { return _latitude; }
set { this.RaiseAndSetIfChanged(x => x.latitude, value); }
}
public ReactiveAsyncCommand setButton { get; set; }
public MapPageViewModel()
{
setButton = new ReactiveAsyncCommand();
setButton.Subscribe(x => {
Pushpin p = new Pushpin();
p.Background = new SolidColorBrush(Colors.Yellow);
p.Foreground = new SolidColorBrush(Colors.Black);
p.Location = new GeoCoordinate(double.Parse(longitude), double.Parse(latitude));
p.Content = "I'm here";//To show the place where it is located
//map1.Children.Add(p);
//map1.SetView(new GeoCoordinate(double.Parse(longitude), double.Parse(latitude), 200), 9);
});
}
}
But i don't know how to set map1.Children.Add() and map1.SetView and how to bind these values in Map?
Hi Clemens. I have tried your instruction. But it showing error.
And also i have try this:-
public MapPageViewModel()
{
PushpinItems = new ObservableCollection<PushpinItem>();
PushpinItem pp = new PushpinItem();
setButton = new ReactiveAsyncCommand();
setButton.Subscribe(x => {
pp.Location = new GeoCoordinate(double.Parse(longitude), double.Parse(latitude));
pp.Text = "I'm here";
PushpinItems.Add(pp);
});
}
But here run time error happening. Please let me know where i did mistake.
In a proper MVVM approach you would usually have a MapItemsControl with an ItemTemplate for the Pushpin, and bind that to an ObservableCollection of pushpin data items in your view model:
public class PushpinItem
{
public GeoCoordinate Location { get; set; }
public string Text { get; set; }
}
public class MapPageViewModel : ReactiveObject
{
public ObservableCollection<PushpinItem> PushpinItems { get; set; }
...
public MapPageViewModel()
{
PushpinItems = new ObservableCollection<PushpinItem>();
setButton = new ReactiveAsyncCommand();
setButton.Subscribe(x =>
{
PushpinItems.Add(new PushpinItem
{
Location = new GeoCoordinate(...),
Text = ...
});
});
}
}
XAML:
<map:Map ...>
<map:MapItemsControl ItemsSource="{Binding PushpinItems}">
<map:MapItemsControl.ItemTemplate>
<DataTemplate>
<map:Pushpin Location="{Binding Location}" Content="{Binding Text}"
Background="Yellow" Foreground="Black"/>
</DataTemplate>
</map:MapItemsControl.ItemTemplate>
</map:MapItemsControl>
</map:Map>
SetView From ViewModel
#Clemens and this link is very helpful to me..!! Thanks for Both of them..!!

Categories

Resources