I want to bind the item source in the List that resides in Pivot Control.How can i bind the itemsouce either in xaml or code.This is my code
<controls:Pivot x:Name="Category_pivot" Foreground="Black" FontSize="22">
<controls:Pivot.HeaderTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" FontSize="45"></TextBlock>
</DataTemplate>
</controls:Pivot.HeaderTemplate>
<controls:Pivot.ItemTemplate>
<DataTemplate>
<ListBox x:Name="d" ItemsSource="{Binding Item}">
<ListBox.ItemTemplate>
<DataTemplate>
<Image x:Name="img" Source="{Binding ImageSource}" ></Image>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</DataTemplate>
</controls:Pivot.ItemTemplate>
</controls:Pivot>
</Grid>
I may have spent too much time on this, but it bothered me...
You used Foreground="Black" in your example, and this means that the header is black so in a OOB project it is black-on-black.
Here is my XAML:
<phone:Pivot x:Name="Category_pivot" FontSize="22">
<phone:Pivot.HeaderTemplate>
<DataTemplate>
<TextBlock Text="{Binding Title}" FontSize="45"></TextBlock>
</DataTemplate>
</phone:Pivot.HeaderTemplate>
<phone:Pivot.ItemTemplate>
<DataTemplate>
<ListBox x:Name="d" ItemsSource="{Binding Items}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding ImageSource}"></TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</DataTemplate>
</phone:Pivot.ItemTemplate>
</phone:Pivot>
And my C#:
public partial class MainPage : PhoneApplicationPage
{
public class Data
{
public string Title { get; set; }
public ObservableCollection<SubData> Items { get; set; }
}
public class SubData
{
public string ImageSource { get; set; }
}
// Constructor
public MainPage()
{
InitializeComponent();
ObservableCollection<Data> list = new ObservableCollection<Data>();
Data d = new Data() { Title = "my page 1" };
d.Items = new ObservableCollection<SubData>();
d.Items.Add(new SubData() { ImageSource = "1" });
d.Items.Add(new SubData() { ImageSource = "2" });
list.Add(d);
d = new Data() { Title = "my page 2" };
d.Items = new ObservableCollection<SubData>();
d.Items.Add(new SubData() { ImageSource = "A" });
d.Items.Add(new SubData() { ImageSource = "B" });
list.Add(d);
Category_pivot.ItemsSource = list;
}
}
Related
I experience an issue when i try to use a command to open a Second View Model V4.0.Beta5.
I followed the Exemple described in N+1 Video series https://www.youtube.com/playlist?list=PLR6WI6W1JdeYSXLbm58jwAKYT7RQR31-W
First ViewModel
public class FirstViewModel
: MvxViewModel
{
private string _hello = "Hello MvvmCross";
public string Hello
{
get { return _hello; }
set
{
_hello = value;
RaisePropertyChanged(() => Hello);
}
}
private Cirrious.MvvmCross.ViewModels.MvxCommand _goSecondViewCommand;
public System.Windows.Input.ICommand GoSecondViewCommand
{
get
{
_goSecondViewCommand = _goSecondViewCommand ??
new Cirrious.MvvmCross.ViewModels.MvxCommand(DoGoSecondView);
return _goSecondViewCommand;
}
}
private void DoGoSecondView()
{
base.ShowViewModel<SecondViewModel>();
}
}
Second View model
public class SecondViewModel :MvxViewModel
{
private string _hello2 = "Hello2 MvvmCross";
public string Hello2
{
get { return _hello2; }
set
{
_hello2 = value;
RaisePropertyChanged(() => Hello2);
}
}
}
First View
<views:MvxWindowsPage
x:Class="TestCommand.UWP.Views.FirstView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:TestCommand.UWP"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:views="using:Cirrious.MvvmCross.WindowsUWP.Views"
mc:Ignorable="d">
<Grid>
<TextBox x:Name="textBox" HorizontalAlignment="Left" Margin="70,92,0,0" TextWrapping="Wrap" Text="FirstView" VerticalAlignment="Top" Width="223"/>
<Button x:Name="button" Command="{Binding GoSecondViewCommand}" Content="Button" HorizontalAlignment="Left" Height="108" Margin="70,346,0,0" VerticalAlignment="Top" Width="223"/>
</Grid>
Second view
<views:MvxWindowsPage
x:Class="TestCommand.UWP.Views.SecondView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:TestCommand.UWP.Views"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:views="using:Cirrious.MvvmCross.WindowsUWP.Views"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="400">
<Grid />
Setup Class:
public class Setup : MvxWindowsSetup
{
public Setup(Frame rootFrame) : base(rootFrame)
{
}
protected override IMvxApplication CreateApp()
{
return new TestCommand.Core.App();
}
}
If you want you can download the solution Here:
https://onedrive.live.com/redir?resid=A5D9789788DE33CB!36079&authkey=!AKs9nsG28iI6nQQ&ithint=file%2czip.
The possible reason is you don't use Setup correctly in your UWP app, here is what I do to make this work:
1) Create two ViewModels in the UWP app: FirstViewModel and SecondViewModel
2) Create a Setup class in Setup.cs file:
public class Setup : MvxWindowsSetup
{
public Setup(Frame rootFrame) : base(rootFrame)
{
}
protected override IMvxApplication CreateApp()
{
return new AppSetup();
}
}
public class AppSetup : MvxApplication
{
public override void Initialize()
{
RegisterAppStart<FirstViewModel>();
}
}
3) FirstView.xaml:
<StackPanel>
<TextBox x:Name="textBox" HorizontalAlignment="Left" Margin="70,92,0,0" TextWrapping="Wrap" Text="FirstView" VerticalAlignment="Top" Width="223"/>
<TextBlock Height="50" Text="{Binding Hello}" />
<Button x:Name="button" Command="{Binding GoSecondViewCommand}" Content="Button" HorizontalAlignment="Left" VerticalAlignment="Top" Width="223" Height="50" />
</StackPanel>
4) SecondView.xaml:
<StackPanel>
<TextBox x:Name="textBox" HorizontalAlignment="Left" Margin="70,92,0,0" TextWrapping="Wrap" Text="SecondView" VerticalAlignment="Top" Width="223"/>
<TextBlock Height="50" Text="{Binding Hello2}" />
</StackPanel>
5) In App.xaml.cs file, make the following changes in OnLaunched method:
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
......
if (rootFrame.Content == null)
{
var setup = new Setup(rootFrame);
setup.Initialize();
var start = Mvx.Resolve<IMvxAppStart>();
start.Start();
}
// Ensure the current window is active
Window.Current.Activate();
}
By the way, the MvvmCross version is 3.5.1
Check the Completed sample on Github
Update for exception in OnNavigationFailed method:
Please comment this line in FirstView and SecondView's code behind:
ViewModel = new FirstViewModel();
ViewModel = new SecondViewModel();
The MvvmCross has set the ViewModel automatically.
i have a listbox with some contact number in listbox now i want to add Show and Hide button to each of contact item in list box when user press Hide button contact will be Hide and when user press Show button contact will be show and vise versa how i can do this in WP8..
i am using following code please help me..
</Grid.ColumnDefinitions>
<StackPanel Orientation="Horizontal" Margin="0, 10, 0, 10">
<Border BorderThickness="0" HorizontalAlignment="Left" VerticalAlignment="Center" BorderBrush="{StaticResource PhoneAccentBrush}" Margin="5, 0, 0, 0">
<Image Source="{Binding ImageUrl, Converter={StaticResource kconverter}}" Width="48" Height="48" Stretch="Fill"/>
</Border>
<TextBlock x:Name="item_name" Text="{Binding Name, Mode=OneWay}" FontSize="{StaticResource PhoneFontSizeLarge}" Margin="10, 0, 0, 0" />
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="0, 10, 0, 10">
<Border BorderThickness="0" HorizontalAlignment="Left" VerticalAlignment="Center" BorderBrush="{StaticResource PhoneAccentBrush}" Margin="355, 0, 0, 0">
<Image Name="onimg" Visibility="Visible" Source="/Assets/Images/blue.button.png" Width="85" Height="20" Tap="Image_TapOn" Stretch="Fill"/>
</Border>
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="0, 10, 0, 10">
<Border BorderThickness="0" HorizontalAlignment="Left" VerticalAlignment="Center" BorderBrush="{StaticResource PhoneAccentBrush}" Margin="355, 0, 0, 0">
<Image Name="offimg" Visibility="Collapsed" Source="/Assets/Images/setting-h.png" Width="85" Height="48" Tap="Image_TapOff" Stretch="Fill"/>
</Border>
</StackPanel>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Hi Use this code Hope so it works for you.
Note : Bind only ObservableCollection to ListBox to Use INotifyPropertyChanged
XAML :
<Grid Grid.Row="1">
<ListBox x:Name="lstContact">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Border Background="#404040"
Height="45"
Width="60"
Tag="{Binding ContactId}"
Tap="_Collapsed">
<TextBlock Text="-"
FontSize="24"
VerticalAlignment="Center"
TextAlignment="Center"
Foreground="White" />
</Border>
<Border Name="BrCount"
Width="160"
Height="45"
BorderBrush="#404040"
BorderThickness="0"
Margin="10,0">
<TextBlock Name="LblCont"
Text="{Binding ContactName}"
FontSize="24"
VerticalAlignment="Center"
TextAlignment="Center"
Foreground="#404040"
Visibility="{Binding _Visibility}" />
</Border>
<Border Background="#404040"
Height="45"
Width="60"
Tag="{Binding ContactId}"
Tap="_Visible">
<TextBlock Text="+"
FontSize="24"
VerticalAlignment="Center"
TextAlignment="Center"
Foreground="White" />
</Border>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
C# :
private ObservableCollection<Contact> _contact = new ObservableCollection<Contact>();
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
_contact = new ObservableCollection<Contact>();
for (int i = 0; i < 10; i++)
{
_contact.Add(new Contact() { ContactId = i, ContactName = "Name " + i, _Visibility = Visibility.Visible });
}
lstContact.ItemsSource = _contact;
}
private void _Collapsed(object sender, System.Windows.Input.GestureEventArgs e)
{
Border bdr = (Border)sender;
_contact.Where(X => X.ContactId == Convert.ToInt32(bdr.Tag.ToString())).First()._Visibility = Visibility.Collapsed;
}
private void _Visible(object sender, System.Windows.Input.GestureEventArgs e)
{
Border bdr = (Border)sender;
_contact.Where(X => X.ContactId == Convert.ToInt32(bdr.Tag.ToString())).First()._Visibility = Visibility.Visible;
}
public class Contact : INotifyPropertyChanged
{
public int ContactId { get; set; }
public string ContactName { get; set; }
public Visibility _visibility;
public Visibility _Visibility
{
get { return _visibility; }
set { SetProperty(ref _visibility, value); }
}
protected void SetProperty<T>(ref T storage, T value, [System.Runtime.CompilerServices.CallerMemberName] String propertyName = null)
{
if (!object.Equals(storage, value))
{
storage = value;
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
protected void RaisePropertyChanged([System.Runtime.CompilerServices.CallerMemberName] String propertyName = null)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
I have parsed the RSS feed http://www.teluguone.com/videosongs/videoSongsXml.php?cat_id=6 and displayed in listbox.When i click on a particular song automatically it should be navigated and start playing.But when i click on a song it is navigating to other page but not playing.It was displaying "An error occured please try again".I am not understanding where the problem is.I have written the following code.No errors and warnings are rising.
please help me.i was trying on this from many days.
Maipage.Xaml:
<phone:PhoneApplicationPage
x:Class="videosongs.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:delay="clr-namespace:Delay;assembly=PhonePerformance"
mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True" Loaded="PhoneApplicationPage_Loaded">
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="Teluguone" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="Videosongs" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<ListBox x:Name="songsList"
SelectionChanged="songsList_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Height="130">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Image delay:LowProfileImageLoader.UriSource="{Binding songpic}"
Grid.Column="0"
Width="97"
Height="125"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Margin="6"/>
<StackPanel Margin="10,15,0,0"
Grid.Column="1"
Height="60"
Orientation="Horizontal"
VerticalAlignment="Top">
<TextBlock Text="{Binding songname}"
FontSize="30" />
</StackPanel>
<StackPanel Margin="0,50,0,0"
Grid.Column="1"
VerticalAlignment="Center">
<TextBlock Grid.Column="1"
Text="{Binding songdescr}"
Style='{StaticResource PhoneTextSubtleStyle}'
/>
<TextBlock Grid.Column="1"
Text="{Binding songdate}"
Style='{StaticResource PhoneTextSubtleStyle}'
/>
</StackPanel>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<ProgressBar x:Name="progress" Foreground="White" />
</Grid>
</Grid>
Mainpage.xaml.cs:
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
}
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
// is there network connection available
if (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
{
MessageBox.Show("No network connection available!");
return;
}
// start loading XML-data
WebClient downloader = new WebClient();
Uri uri = new Uri("http://www.teluguone.com/videosongs/videoSongsXml.php?cat_id=6", UriKind.Absolute);
downloader.DownloadStringCompleted += new DownloadStringCompletedEventHandler(VideosongsDownloaded);
downloader.DownloadStringAsync(uri);
}
void VideosongsDownloaded(object sender, DownloadStringCompletedEventArgs e)
{
try
{
if (e.Result == null || e.Error != null)
{
MessageBox.Show("There was an error downloading the XML-file!");
}
else
{
// Deserialize if download succeeds
XDocument document = XDocument.Parse(e.Result);
XmlSerializer serializer = new XmlSerializer(typeof(Videosongs));
Videosongs videosongs = (Videosongs)serializer.Deserialize(document.CreateReader());
songsList.ItemsSource = videosongs.Collection;
}
}
catch (Exception ex)
{
//MessageBox.Show(ex.InnerException.Message);
MessageBox.Show(ex.ToString());
}
}
// selection in SongsdetailsList is changed
private void songsList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListBox listBox = sender as ListBox;
if (listBox != null && listBox.SelectedItem != null)
{
Songsdetails song = (Songsdetails)listBox.SelectedItem;
System.Diagnostics.Debug.WriteLine(song);
NavigationService.Navigate(new Uri("/Videopage.xaml?songsongcode=" + song.songcode , UriKind.Relative));
}
}
}
}
Songsdetails.cs:
public class Songsdetails
{
[XmlElement("songname")]
public string songname { get; set; }
[XmlElement("songpic")]
public string songpic { get; set; }
[XmlElement("songcode")]
public string songcode { get; set; }
[XmlElement("songdescr")]
public string songdescr { get; set; }
[XmlElement("songtitletags")]
public string songtitletags { get; set; }
[XmlElement("songmetatags")]
public string songmetatags { get; set; }
[XmlElement("songmetadesc")]
public string songmetadesc { get; set; }
[XmlElement("songdate")]
public string songdate { get; set; }
[XmlElement("songurl")]
public string songurl { get; set; }
Videosongs.cs:
[XmlRoot("videosongs")]
public class Videosongs
{
//[XmlElement("publisher")]
//public string publisher { get; set; }
//[XmlElement("publisherurl")]
//public string publisherUrl { get; set; }
[XmlElement("songsdetails")]
public ObservableCollection<Songsdetails> Collection { get; set; }
Videopage.Xaml:
<phone:PhoneApplicationPage
x:Class="videosongs.Videopage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:extended="clr-namespace:MyToolkit.Controls;assembly=MyToolkit.Extended"
mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Landscape"
shell:SystemTray.IsVisible="False">
<StackPanel VerticalAlignment="Top" Height="600" Margin="0,0,0,0">
<TextBlock x:Name="title" TextWrapping="Wrap" VerticalAlignment="Top" Height="40"></TextBlock>
<phone:WebBrowser x:Name="webBrowser" Height="411" IsScriptEnabled="True" Margin="10,0,78,0" />
</StackPanel>
Videopage.Xaml.cs:
namespace videosongs
{
public partial class Videopage : PhoneApplicationPage
{
// Constructor
public Videopage()
{
InitializeComponent();
}
// When page is navigated to set data context to selected item in list
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
if (!NetworkInterface.GetIsNetworkAvailable())
{
MessageBox.Show("An error has occurred! Please verify your internet connection.");
NavigationService.GoBack();
}
else
{
string video = "http://www.youtube.com/embed/+getsongcode()";
System.Diagnostics.Debug.WriteLine(video);
this.webBrowser.Navigate(new Uri(video));
}
}
}
Anybody please help.Any help would be appreciated.
Many Thanks in advance.
I've made a JumpList (by following this tutorial) linked with a LongListSelector, but I can't redirect the user when he taps on an item of the list. I used to do it well with a simple LongListSelector as this one :
<phone:LongListSelector x:Name="lls_Songs" SelectionChanged=lls_Songs_SelectionChanged>
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<StackPanel Margin="5,5,5,5">
<TextBlock Text="{Binding Name}" FontSize="30"/>
<TextBlock Text="{Binding Duration}" FontSize="20" Opacity="0.75"/>
</StackPanel>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
But now I use this code...
<phone:LongListSelector
x:Name="lls_songs"
Margin="12,35,12,0"
Visibility="Visible"
JumpListStyle="{StaticResource JumpListStyle}"
Background="Transparent"
GroupHeaderTemplate="{StaticResource lls_SongsHeaderTemplate}"
ItemTemplate="{StaticResource lls_SongsTemplate}"
LayoutMode="List"
IsGroupingEnabled="true"
SelectionChanged="lls_songs_SelectionChanged"
HideEmptyGroups ="true"/>
...linked with this code :
<DataTemplate x:Key="lls_SongsTemplate">
<StackPanel VerticalAlignment="Top" Orientation="Horizontal" Margin="5,5,5,5">
<StackPanel Orientation="Vertical">
<toolkit:ContextMenuService.ContextMenu>
<toolkit:ContextMenu>
<toolkit:MenuItem Header="détails"/>
<toolkit:MenuItem Header="ajouter à la lecture"/>
</toolkit:ContextMenu>
</toolkit:ContextMenuService.ContextMenu>
<TextBlock Text="{Binding songName}" FontSize="30" />
<TextBlock Text="{Binding songArtist}" FontSize="20" Opacity="0.75"/>
</StackPanel>
</StackPanel>
</DataTemplate>
here is the lls_Songs_SelectionChanged method :
private void lls_songs_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Song _selectedSong = lls_songs.SelectedItem as Song;
MediaPlayer.Play(_selectedSong);
}
and finaly how I create my songs list :
MediaLibrary _library = new MediaLibrary();
List<MusicInfo> MusicInfoList = new List<MusicInfo>();
int so = _library.Songs.Count;
int _so = 0;
while(_so < so)
{
Song _song = null;
_song = _library.Songs[_so];
MusicInfoList.Add(new MusicInfo(_song.Name, _song.Artist.ToString()));
_so = _so + 1;
}
linked with this class:
public string songName { get; set; }
public string songArtist { get; set; }
public MusicInfo(string _songName, string _songArtist)
{
this.songName = _songName;
this.songArtist = _songArtist;
}
and the jumplist :
private void SortingSongsListsAZ()
{
List<AlphaKeyGroup<MusicInfo>> DataSource = AlphaKeyGroup<MusicInfo>.CreateGroups(MusicInfoList,
System.Threading.Thread.CurrentThread.CurrentUICulture,
(MusicInfo s) => { return s.songName; }, true);
lls_songs.ItemsSource = DataSource;
}
And when I tap on an item of the list, I get this error : "This method does not accept null for this parameter". I don't understand why, anyone would help me ?
Share or check your lls_songs items source binding and code. from your code it appears that
Song _selectedSong = lls_songs.SelectedItem as Song;
_selectedSong is null.
in debug mode see what is the value of SelectedItem. is it Song type or something else?
According to your update, it seems that lls_songs.SelectedItem is of type MusicInfo instead of Song. Fixing your type-casting should remove the error I believe :
MusicInfo _selectedSong = lls_songs.SelectedItem as MusicInfo;
Or better yet this way :
MusicInfo _selectedSong = (MusicInfo)lls_songs.SelectedItem;
This is the class where I'm trying to load the data
PAGE2 XAML
<xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DataContext="{d:DesignData SampleData/MainViewModelSampleData.xaml}"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True">
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--TitlePanel contains the name of the application and page title-->
<StackPanel Grid.Row="0" Margin="12,17,0,28">
<TextBlock Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock Text="page name" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Margin="0,10,0,0" Grid.Row="1">
<phone:LongListSelector x:Name="MainLongListSelector" Margin="10,2,0,0" ItemsSource="{Binding Items2}" SelectionChanged="MainLongListSelector_SelectionChanged">
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<StackPanel Margin="0,0,0,17" Height="154">
<TextBlock Text="{Binding LineOne}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}" FontSize="20" Margin="0,0,0,538" Height="150"/>
</StackPanel>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
</Grid>
</Grid>
</phone:PhoneApplicationPage>
MainViewModel
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using Package_Tracker_P.Resources;
using System.Collections.Generic;
using Windows.Storage;
using System.IO;
using System.Threading.Tasks;
using System.Windows;
using System.Text.RegularExpressions;
namespace Package_Tracker_P.ViewModels
{
public class MainViewModel : INotifyPropertyChanged
{
public static List<Car> carlist = new List<Car>();
public MainViewModel()
{
this.Items = new ObservableCollection<ItemViewModel>();
this.Items2 = new ObservableCollection<ItemViewModel>();
}
/// <summary>
/// A collection for ItemViewModel objects.
/// </summary>
public ObservableCollection<ItemViewModel> Items { get; private set; }
public ObservableCollection<ItemViewModel> Items2 { get; private set; }
private string _sampleProperty = "Sample Runtime Property Value";
/// <summary>
/// Sample ViewModel property; this property is used in the view to display its value using a Binding
/// </summary>
/// <returns></returns>
public string SampleProperty
{
get
{
return _sampleProperty;
}
set
{
if (value != _sampleProperty)
{
_sampleProperty = value;
NotifyPropertyChanged("SampleProperty");
}
}
}
/// <summary>
/// Sample property that returns a localized string
/// </summary>
public string LocalizedSampleProperty
{
get
{
return AppResources.SampleProperty;
}
}
public bool IsDataLoaded
{
get;
private set;
}
/// <summary>
/// Creates and adds a few ItemViewModel objects into the Items collection.
/// </summary>
public async void LoadData(Car toyota)
{
// Sample data; replace with real data
carlist.Add(toyota);
this.Items.Add(new ItemViewModel() { ID = (Items.Count.ToString()), LineOne = toyota.status, LineTwo = "", LineThree = "" });
this.IsDataLoaded = true;
//await openfile();
await IO.WriteToFile();
}
public async void LoadData()
{
try
{
stuff();
}
catch (Exception ex)
{
MessageBox.Show("Error Loading Data");
}
}
public void stuff()
{
this.Items2.Add(new ItemViewModel() { ID = (Items2.Count.ToString()), LineOne = "Auto Detect", LineTwo = "", LineThree = "" });
this.IsDataLoaded = true;
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (null != handler)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
The problem is is not loading the data for PAGE2. It is loading it for the main page using items1. While the app is loading it calls LoadData() and that call stuff() which is adding data to items2. It is correctly
binded in the xaml file for PAGE TWO in the textblock. Am I missing something?
i think the main problem with this code is that you have not set the datacontext of the page 2
like if you are using MVVM light then
DataContext = {Binding MainViewModel,Source="{StaticResource Locator}}"