Playing incoming audio stream on different pages - c#

I am building some Shared Project which is connected with Playing incoming internet radio stream.
Currently I ve got a problem with Playing this stream on different pages.
I made some background task and it works fine I can easily minimize my app but when I am moving to different page where the user will read the RSS feed (Frame.Navigate some DataContext which contains the RSS),the Media Element stop playing.
I try to find some solution myself, but I didn't find any which will be the best for my.
Thank you for your help
public sealed partial class MainPage : Page
{
SystemMediaTransportControls systemControls = SystemMediaTransportControls.GetForCurrentView();
FeedDataSource feedDataSource = (FeedDataSource)App.Current.Resources["feedDataSource"];
FeedData nFeedData = new FeedData();
public MainPage()
{
this.InitializeComponent();
InitializeTransportControls();
}
private void Media_CurrentStateChanged(object sender, RoutedEventArgs e)
{
switch (Media.CurrentState)
{
case MediaElementState.Closed:
systemControls.PlaybackStatus = MediaPlaybackStatus.Closed;
break;
case MediaElementState.Paused:
systemControls.PlaybackStatus = MediaPlaybackStatus.Paused;
break;
case MediaElementState.Playing:
systemControls.PlaybackStatus = MediaPlaybackStatus.Playing;
break;
case MediaElementState.Stopped:
systemControls.PlaybackStatus = MediaPlaybackStatus.Stopped;
break;
default:
break;
}
}
private async void PlayButton_Click(object sender, RoutedEventArgs e)
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
Media.Play();
});
}
private async void StopButton_Click(object sender, RoutedEventArgs e)
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
Media.Stop();
});
}
private async void PauseButton_Click(object sender, RoutedEventArgs e)
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
Media.Pause();
});
}
private void VolumeSlider_ValueChanged(object sender, RangeBaseValueChangedEventArgs e)
{
Media.Volume = e.NewValue;
}
void InitializeTransportControls()
{
// Windows.Media
systemControls.ButtonPressed += systemControls_ButtonPressed;
systemControls.IsPlayEnabled = true;
systemControls.IsPauseEnabled = true;
}
// Handle ButtonPressed for systemControls
void systemControls_ButtonPressed(SystemMediaTransportControls sender, SystemMediaTransportControlsButtonPressedEventArgs args)
{
switch (args.Button)
{
case SystemMediaTransportControlsButton.Pause:
Media.Play();
break;
case SystemMediaTransportControlsButton.Play:
Media.Pause();
break;
default:
break;
}
}
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
if (feedDataSource != null)
{
if (feedDataSource.Feeds.Count == 0)
{
await feedDataSource.GetFeedsAsync();
}
MenuSection.DataContext = feedDataSource.Feeds;
}
}
private void ItemListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
private void Contetnview_ItemClick(object sender, ItemClickEventArgs e)
{
}
private void Contetnview_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var x
= ((GridView)sender).SelectedItem;
var z = ((Grid)x).Tag.ToString();
switch (z)
{
case "1":
Frame.Navigate(typeof(ReadNewsPage), feedDataSource.Feeds[0]);
break;
case "2":
Frame.Navigate(typeof(ReadNewsPage), feedDataSource.Feeds[3]);
break;
case "3":
Frame.Navigate(typeof(ReadNewsPage), feedDataSource.Feeds[2]);
break;
case "4":
Frame.Navigate(typeof(ReadNewsPage), feedDataSource.Feeds[1]);
break;
}
}
}
<Grid x:Name="ThisGris" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<MediaElement x:Name="Media" Source="http://5.201.13.191:80/live" HorizontalAlignment="Left" Height="206" Margin="107,372,0,0" VerticalAlignment="Top" Width="213" AudioCategory="BackgroundCapableMedia" AutoPlay="False" CurrentStateChanged="Media_CurrentStateChanged"/>
<Hub x:Name="MainHubPage" Header="" Margin="0,3,0,-3" >
<Hub.Background>
<ImageBrush />
</Hub.Background>
<HubSection Header="Radio" Width="402" IsHeaderInteractive="True">
<DataTemplate>
<Grid Width="429" Height="565" d:IsLocked="True">
<Button x:Name="PlayButton" Content="Play" HorizontalAlignment="Left" Margin="118,352,0,0" VerticalAlignment="Top" Height="58" Width="83" Click="PlayButton_Click" d:IsLocked="True"/>
<Button x:Name="StopButton" Content="Stop" HorizontalAlignment="Left" Margin="7,352,0,0" VerticalAlignment="Top" Height="58" Click="StopButton_Click" d:IsLocked="True"/>
<Button x:Name="PauseButton" Content="Pause" HorizontalAlignment="Left" Margin="236,352,0,0" VerticalAlignment="Top" Height="58" Click="PauseButton_Click" d:IsLocked="True"/>
<Slider x:Name="VolumeSlider" HorizontalAlignment="Left" Margin="53,295,0,0" VerticalAlignment="Top" Width="267" Minimum="0" Value="50" Maximum="100" ValueChanged="VolumeSlider_ValueChanged" d:IsLocked="True"/>
<TextBlock HorizontalAlignment="Left" Margin="10,129,0,0" TextWrapping="Wrap" FontSize="20" Text="Na antenie :" VerticalAlignment="Top" Height="40" Width="135" d:IsLocked="True"/>
<TextBlock HorizontalAlignment="Left" Margin="10,174,0,0" TextWrapping="Wrap" FontSize="20" Text="Gramy :" VerticalAlignment="Top" Height="42" Width="135" d:IsLocked="True"/>
<TextBlock HorizontalAlignment="Left" Margin="10,216,0,0" FontSize="20" TextWrapping="Wrap" Text="Wkrótce : " VerticalAlignment="Top" Height="42" Width="118" d:IsLocked="True"/>
<TextBlock HorizontalAlignment="Left" Margin="150,216,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Height="42" Width="269" d:IsLocked="True"/>
<TextBlock HorizontalAlignment="Left" Height="40" Margin="150,129,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="269" d:IsLocked="True"/>
<TextBlock HorizontalAlignment="Left" Margin="150,174,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Height="42" Width="293" d:IsLocked="True"/>
</Grid>
</DataTemplate>
</HubSection>
<HubSection x:Name="MenuSection" Width="606" IsHeaderInteractive="True">
<DataTemplate>
<GridView x:Name="Contetnview"
DataContext="{Binding}"
Height="519" Width="606" SelectionChanged="Contetnview_SelectionChanged" >
<Grid x:Name="Dowiadomosci" Height="135" Width="161" Tag="1" DataContext="{Binding }">
<TextBlock Text="Wiadomości"/>
</Grid>
<Grid x:Name="Dodupy" Height="135" Width="161" Tag="2" DataContext="{Binding Path=Feeds[0]}" >
<TextBlock Text="Muzyka"/>
</Grid>
<Grid Height="135" Width="161" Tag="3" DataContext="{Binding Path=Feeds[0]}">
<TextBlock Text="Kultura"/>
</Grid>
<Grid Height="135" Width="161" Tag="4" DataContext="{Binding Source=feedDataSource, Path=Feeds[0]}">
<TextBlock Text="Sport"/>
</Grid>
<Grid Height="135" Width="161" Tag="5">
<TextBlock Text="O nas"/>
</Grid>
<Grid Height="135" Width="161" Tag="6">
<TextBlock Text="Audycja Autorskie"/>
</Grid>
<Grid Height="135" Width="161" Tag="7">
<TextBlock Text="Ekipa"/>
</Grid>
<Grid Height="135" Width="161" >
<TextBlock Text="Ramówka"/>
</Grid>
</GridView>
</DataTemplate>
</HubSection>
<HubSection x:Name="Schedule" Width="606" Header="Ramówka" IsHeaderInteractive="True" DataContext="{Binding Source=feedDataSource, Path=Feeds[0]}">
<DataTemplate>
<GridView x:Name="ScheduleContent" Height="519" Width="606" ItemClick="Contetnview_ItemClick">
<Grid Height="135" Width="161" >
<TextBlock Text="Ramówka"></TextBlock>
</Grid>
</GridView>
</DataTemplate>
</HubSection>
<HubSection x:Name="Team" Width="606" Header="Ekipa" IsHeaderInteractive="True" DataContext="{Binding Source=feedDataSource, Path=Feeds[0]}">
<DataTemplate>
<GridView x:Name="TeamContent" Height="519" Width="606" ItemClick="Contetnview_ItemClick">
<GridView.ItemTemplate>
<DataTemplate>
<Grid Height="135" Width="161" >
<Image>
</Image>
</Grid>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
</DataTemplate>
</HubSection>
<HubSection x:Name="AuthorShow" Width="606" Header="Audycje Autorskie" IsHeaderInteractive="True" DataContext="{Binding Source=feedDataSource, Path=Feeds[0]}">
<DataTemplate>
<GridView x:Name="AuthorShowContent" Height="519" Width="606" ItemClick="Contetnview_ItemClick">
<Grid Height="135" Width="161" >
<Image>
</Image>
</Grid>
</GridView>
</DataTemplate>
</HubSection>
<HubSection x:Name="AboutUs" Width="606" Header="O nas" IsHeaderInteractive="True" DataContext="{Binding Source=feedDataSource, Path=Feeds[0]}">
<DataTemplate>
<Grid x:Name="AboutUSContent" Height="519" Width="606" >
<TextBlock Text="TutajONAS"></TextBlock>
</Grid>
</DataTemplate>
</HubSection>
</Hub>
</Grid>

It seems that reason the music stops is because you are creating the stream in a page, and then moving away from the page which is causing everything you just allocated to go away.
I would recommend trying to create/play your media player object in the App.xaml.cs file.
This should live across page calls.

Related

ListBox WPF Multiselect Not working

I am trying to select multiple options from a listbox. I even tried using Multiple Selection mode but it doesnot work for this specific listbox but works for others. ListBox name is listBox. I am adding the data to that list dynamically in OrderWindow class and i have implemented the selection_changed method but i am unable to select multiple items and i have also binded a list to this listbox.
Here is the code:
namespace ACW2
{
/// <summary>
/// Interaction logic for OrderWindow.xaml
/// </summary>
public partial class OrderWindow : Window
{
List<MenuClass> PizzaInStock = new List<MenuClass>();
List<InvClass> inventory = MainWindow.ItemList;
List<InvClass> pizzatoppings = new List<InvClass>();
List<String> Mainlist = new List<String>();
String addpizzas = "";
double pizzaprice = 0;
private void extratoppingslist(String name)
{
pizzatoppings = new List<InvClass>();
var pizza = MainWindow.MenuList.FirstOrDefault(x => x.Name == name);
List<Ingredient> originaltoppings = pizza.Ingredients;
int originaltoppingsize = pizza.Ingredients.Count;
if (originaltoppingsize >= 5)
{
return;
}
var allpizzatoppings = from a in inventory
where a.Category == "pizza"
select a;
foreach (InvClass item in allpizzatoppings)
{
int exists = 0;
if (originaltoppingsize == 5)
{
break;
}
foreach(Ingredient ing in originaltoppings)
{
if (item.Name.Equals(ing.Name))
{
exists = 1;
break;
}
}
if (exists == 0)
{
pizzatoppings.Add(item);
}
++originaltoppingsize;
}
listBox.ItemsSource = null;
listBox.ItemsSource = pizzatoppings;
}
private void updatepizzaprice()
{
pizzaprice = 0;
if (comboBox1.SelectedItem != null&& comboBox.SelectedItem != null)
{
String pizza = comboBox.SelectedItem.ToString();
String size = comboBox1.SelectedItem.ToString();
extratoppingslist(pizza);
var iteminlists = MainWindow.MenuList.FirstOrDefault(x => (x.Name == pizza) && (x.Size == size));
pizzaprice += (Convert.ToDouble(iteminlists.Price));
List<Ingredient> list = iteminlists.Ingredients;
if (checkBox.IsChecked == true)
{
foreach(Ingredient iss in list)
{
Trace.WriteLine(iss.Name);
}
var item = list.FirstOrDefault(x => x.Name == " dough");
var ingr= inventory.FirstOrDefault(x => x.Name == " dough");
pizzaprice += ((Convert.ToDouble(item.Quantity) * 0.1))*ingr.Price;
var items = list.FirstOrDefault(x => x.Name == " mozzarella");
var ingrs = inventory.FirstOrDefault(x => x.Name == " mozzarella");
pizzaprice += ((Convert.ToDouble(items.Quantity) * 0.15)) * ingrs.Price;
}
List<InvClass> toppings = listBox.SelectedItems.Cast<InvClass>().ToList();
foreach (InvClass top in toppings)
{
var item = inventory.FirstOrDefault(x => x.Name == top.Name);
Trace.WriteLine(top.Name);
if (iteminlists.Size == " regular")
{
pizzaprice += item.Price * 0.25;
}
else if (iteminlists.Size == " large")
{
pizzaprice += item.Price * 0.35;
}
else if (iteminlists.Size == " extra-large")
{
pizzaprice += item.Price * 0.75;
}
}
textBox.Text = "£ " + pizzaprice.ToString();
}
}
private void comboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
updatepizzaprice();
}
private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
updatepizzaprice();
}
private void checkBox_Checked(object sender, RoutedEventArgs e)
{
updatepizzaprice();
}
private void listBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
updatepizzaprice();
}
private void checkBox_unchecked(object sender, RoutedEventArgs e)
{
updatepizzaprice();
}
private void checkbox1_unchecked(object sender, RoutedEventArgs e)
{
updateburgerprice();
}
private void checkbox2_unchecked(object sender, RoutedEventArgs e)
{
updateburgerprice();
}
}
}
Here is the xml code:
<Window x:Class="ACW2.OrderWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:ACW2"
mc:Ignorable="d"
Title="OrderWindow" SizeToContent="WidthAndHeight">
<StackPanel Orientation="Vertical">
<Label x:Name="label10" Content="Create Order" HorizontalAlignment="Left" Margin="5" VerticalAlignment="Top" FontSize="24"/>
<StackPanel Orientation="Horizontal" VerticalAlignment="Top">
<StackPanel Orientation="Vertical" VerticalAlignment="Top">
<Label x:Name="label4_Copy" Content="Order Summary" Margin="5" FontSize="16"/>
<ListBox x:Name="listBox2" Height="160" Margin="5" MinWidth="180"/>
<Button x:Name="button4" Content="Remove Item" Margin="5" Width="75"/>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
<Label x:Name="label13" Content="Ingredient Cost (£)" Margin="5" VerticalAlignment="Top"/>
<TextBox x:Name="textBox4" Height="24" Margin="5" TextWrapping="Wrap" Text="£" Width="80"/>
</StackPanel>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
<Label x:Name="label12" Content="Net Profit (£)" Margin="5"/>
<TextBox x:Name="textBox5" Height="24" Margin="5" TextWrapping="Wrap" Text="£" Width="80"/>
</StackPanel>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
<Label x:Name="label11" Content="Total Price(£)" Margin="5"/>
<TextBox x:Name="textBox1" Height="24" Margin="5" TextWrapping="Wrap" Text="£" Width="80"/>
</StackPanel>
<Button x:Name="button3" Content="Complete Order" Margin="5"/>
</StackPanel>
<StackPanel Orientation="Vertical" VerticalAlignment="Top">
<Label x:Name="label4" Content="1. Pizzas" Margin="5" FontSize="16"/>
<Border BorderBrush="Gray" BorderThickness="1" Margin="5">
<StackPanel Orientation="Vertical">
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
<Label x:Name="label1" Content="Pizza" Margin="5" />
<ComboBox x:Name="comboBox" Margin="5" Width="120" SelectionChanged="comboBox_SelectionChanged"/>
</StackPanel>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
<Label x:Name="label" Content="Size" Margin="5"/>
<ComboBox x:Name="comboBox1" Margin="5" Width="120" SelectionChanged="comboBox1_SelectionChanged"/>
</StackPanel>
<CheckBox x:Name="checkBox" Content="Stuffed Crust" Margin="5" HorizontalAlignment="Center" Checked="checkBox_Checked" Unchecked="checkBox_unchecked"/>
<Label x:Name="label14" Content="Extra Toppings" Margin="5,5,5,0" HorizontalAlignment="Center"/>
<ListBox x:Name="listBox" Height="120" Margin="5,0,5,5" MinWidth="140" HorizontalAlignment="Center" SelectionChanged="listBox_SelectionChanged" SelectionMode="Multiple">
<ListBox.ItemTemplate>
<DataTemplate x:Name="Lists">
<TextBlock>
<Run Text="{Binding Name}"/>
<Run Text=" , "/>
<Run Text="{Binding Price}"/>
</TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
<Label x:Name="label9" Content="Price (£)" Margin="5"/>
<TextBox x:Name="textBox" Height="24" Margin="5" TextWrapping="Wrap" Text="£" VerticalAlignment="Top" Width="80"/>
</StackPanel>
<Button x:Name="button" Content="Add to Order" Margin="5" Width="80" HorizontalAlignment="Right"/>
</StackPanel>
</Border>
</StackPanel>
<StackPanel Orientation="Vertical" VerticalAlignment="Top">
<Label x:Name="label5" Content="2. Burgers" Margin="5" FontSize="16"/>
<Border BorderBrush="Gray" BorderThickness="1" Margin="5">
<StackPanel Orientation="Vertical">
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
<Label x:Name="label2" Content="Burger" HorizontalAlignment="Left" Margin="5" VerticalAlignment="Top"/>
<ComboBox x:Name="comboBox2" HorizontalAlignment="Left" Margin="5" VerticalAlignment="Top" Width="107" SelectionChanged="comboBox2_SelectionChanged"/>
</StackPanel>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
<Label x:Name="label3" Content="Size" Margin="5" VerticalAlignment="Center"/>
<RadioButton x:Name="radioButton" Content="1/4lb" HorizontalAlignment="Left" Margin="5" VerticalAlignment="Center" Checked="radioButton_Checked"/>
<RadioButton x:Name="radioButton1" Content="1/2lb" HorizontalAlignment="Left" Margin="5" VerticalAlignment="Center" Checked="radioButton1_Checked"/>
</StackPanel>
<StackPanel Orientation="Vertical" HorizontalAlignment="Center">
<CheckBox x:Name="checkBox1" Content="Salad" Margin="2" Checked="checkBox1_Checked" Unchecked="checkbox1_unchecked"/>
<CheckBox x:Name="checkBox2" Content="Cheese" Margin="2" Checked="checkBox2_Checked" Unchecked="checkbox2_unchecked"/>
</StackPanel>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
<Label x:Name="label8" Content="Price (£)" HorizontalAlignment="Left" Margin="5" />
<TextBox x:Name="textBox2" Height="24" Margin="5" TextWrapping="Wrap" Text="£" Width="80"/>
</StackPanel>
<Button x:Name="button1" Content="Add to Order" Margin="5" Width="80" HorizontalAlignment="Right" Click="button1_Click"/>
</StackPanel>
</Border>
</StackPanel>
<StackPanel Orientation="Vertical" VerticalAlignment="Top">
<Label x:Name="label6" Content="3. Sundries" Margin="5" FontSize="16"/>
<Border BorderBrush="Gray" BorderThickness="1" Margin="5">
<StackPanel Orientation="Vertical">
<ListBox x:Name="listBox1" Height="120" MinWidth="140" Margin="5" SelectionChanged="listBox1_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate x:Name="Lists11">
<TextBlock Background="{Binding Color}">
<Run Text="{Binding Name}"/>
</TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<StackPanel Orientation="Horizontal">
<Label x:Name="label7" Content="Price (£)" Margin="5" VerticalAlignment="Top"/>
<TextBox x:Name="textBox3" Height="24" Margin="5" TextWrapping="Wrap" Text="£" Width="80"/>
</StackPanel>
<Button x:Name="button2" Content="Add to Order" HorizontalAlignment="Right" Margin="5" Width="80" Click="button2_Click"/>
</StackPanel>
</Border>
</StackPanel>
</StackPanel>
</StackPanel>
</Window>

How to get CheckBox "Ticked" inside ListBox on run time

I am creating windows phone 8 application, I have checkbox inside listbox, how do I get checkbox "CHECKED" when I click on checkbox?
I tried my best but not getting the result?
see my code below:
<ListBox x:Name="listBox1" Width="429" Height="621" HorizontalAlignment="Left" Margin="21,43,0,59" VerticalAlignment="Top" ItemsSource="{Binding}" SelectedItem="{Binding}" SelectionChanged="listBox1_SelectionChanged" SelectionMode="Extended">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<StackPanel Orientation="Vertical" Width="440">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding}" TextWrapping="Wrap" Foreground="Black" FontSize="22" Height="30" TextAlignment="Left" Width="Auto" FontWeight="SemiBold"/>
<TextBlock Text="{Binding}" TextWrapping="Wrap" Foreground="Black" FontSize="22" Margin="5" Height="30" TextAlignment="Left" Width="Auto" FontWeight="SemiBold"/>
</StackPanel>
<StackPanel>
<TextBlock Text="Favorite" TextWrapping="Wrap" Foreground="Black" FontSize="22" Height="30" FontWeight="SemiBold" Margin="344,-35,9,0"/>
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding}" TextWrapping="Wrap" Foreground="Black" FontSize="22" Height="Auto" Width="Auto" TextAlignment="Left" FontWeight="SemiBold"/>
</StackPanel>
<CheckBox x:Name="CheckBox1" Height="72" Foreground="Black" IsChecked="False" Margin="353,-40,28,0" BorderBrush="Black" Loaded="CheckBox1_Loaded" Checked="CheckBox1_Checked" Unchecked="CheckBox1_Unchecked"/>
</StackPanel>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Here is my code behind file:
private void CheckBox1_Checked(object sender, RoutedEventArgs e)
{
CheckBox cb = (CheckBox)sender;
cb.IsChecked = true;
}
I tried this on emulator in my listbox and it works fine. The textboxes checked and unchecked without any problem.
<ListBox.BorderBrush>
<SolidColorBrush />
</ListBox.BorderBrush>
<ListBox.ItemTemplate>
<DataTemplate>
<Border BorderBrush="Black" BorderThickness="0,1,0,0" Width="600" Padding="0">
<StackPanel Orientation="Horizontal" Margin="0,0,0,0">
<StackPanel Orientation="Horizontal" Margin="0,0,0,0">
<Image Stretch="UniformToFill" Source="{Binding Image}" Width="130" Height="130" HorizontalAlignment="Center" VerticalAlignment="Center">
<Image.Clip>
<RectangleGeometry RadiusX="15" RadiusY="15" Rect="0,0,130,130" />
</Image.Clip>
</Image>
<--CheckBox x:Name="CheckBox1" Height="72" Foreground="Black" IsChecked="False" BorderBrush="Black"/-->
</StackPanel>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
I got the solution:
private void CheckBox1_Checked(object sender, RoutedEventArgs e)
{
CONTACTS data = (sender as CheckBox).DataContext as CONTACTS;
string contactId = data.contactId;
string isFav = data.isFavourite.ToString();
}
Here is the answer:
private void CheckBox1_Checked(object sender, RoutedEventArgs e)
{
CLASS_NAME item = (sender as CheckBox).DataContext as CLASS_NAME;
string id = item.Id;
string name = item.Name;
}

longListSelector get index

I have longListSelector:
<DataTemplate x:Key="AddrBookItemTemplate" >
<StackPanel VerticalAlignment="Top">
<Grid Background="#3FCDCDCD" Margin="3,3,3,3">
<Image Source ="{Binding UrlImage}" Height="100" Width="100" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0,0,0,0" Stretch="Fill"/>
<TextBlock Text="{Binding Title}" TextWrapping="Wrap" Margin="110,0,0,0" Foreground="Black" FontFamily="Portable User Interface"/>
</Grid>
</StackPanel>
</DataTemplate>
</phone:PhoneApplicationPage.Resources>
<phone:LongListSelector
x:Name="AddrBook"
Background="Transparent"
ItemTemplate="{StaticResource AddrBookItemTemplate}"
IsGroupingEnabled="true"
HideEmptyGroups ="true"
SelectionChanged="AddrBook_SelectionChanged"
/>
Preview - name of my class
How can i get index of PressedItem?
What should i write here -
private void AddrBook_SelectionChanged(object sender, SelectionChangedEventArgs e)
{ }
you should write
var longlistselector = (sender as LongListSelector);
int index = longlistselector.DataSource.IndexOf(longlistselector.SelectedItem);

LongListSelector + Selected Item - How to read each individual properties? (WP8, Azure Database)

I have a LongListSelector, that store data from my Azure SQL Database.
This is my C# code:
private async void RefreshTodoItemsToday()
{
try
{
coll = await todoTable
.Where(todoItem => todoItem.TpEvt == "today")
.ToCollectionAsync();
}
catch (MobileServiceInvalidOperationException e)
{
MessageBox.Show(e.Message, "Error loading items", MessageBoxButton.OK);
}
ListItemstoday.ItemsSource = coll;
}
And this is my XAML:
<phone:LongListSelector Name="ListItemsToday">
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Name="TxtEvt" Text="{Binding Text}" TextWrapping="Wrap" Foreground="Gray" TextAlignment="Center" FontSize="30" Padding="30">
</TextBlock>
<Line X1="0" Y1="10" X2="240" Y2="10" Stroke="SkyBlue" HorizontalAlignment="Center" VerticalAlignment="Center" Height="21"/>
</StackPanel>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
The registers are stored in my LongListSelector - it is working fine.
Now this is my doubt: How can i read the properties for each register in my LongListSelector? For each register, i have fields such as "Id", "TypeEvent", "Hour", "Date", etc.
So, how can i read each individual value, according by the SelectedItem in LongListSelector?
For example, if i wish to see in a MessageBox the ID from a Selected Item...how can i do this in code?
I tried the following:
var tmp1 = (TodoItem)ListItemsToday.SelectedItem;
var tmp2 = tmp1.Id;
MessageBox.Show(tmp2.ToString());
When i try to cast this code, this is the error i got:
*System.NullReferenceException: Object reference not set to an instance of an object.
at Project.MainPage.ContextMenuRemove_Click(Object sender, EventArgs e)*
Someone can help'me, please?
Thank you friends.
React to selection changed:
<phone:LongListSelector Name="ListItemsToday" SelectionChanged="ListItemsToday_SelectionChanged">
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Name="TxtEvt" Text="{Binding Text}" TextWrapping="Wrap" Foreground="Gray" TextAlignment="Center" FontSize="30" Padding="30">
</TextBlock>
<Line X1="0" Y1="10" X2="240" Y2="10" Stroke="SkyBlue" HorizontalAlignment="Center" VerticalAlignment="Center" Height="21"/>
</StackPanel>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
with this
private void ListItemsToday_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var item = ListItemsToday.SelectedItem as TodoItem;
MessageBox.Show(item.Text);
}
Or react to tap event in data template
<phone:LongListSelector Name="ListItemsToday" >
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<StackPanel Tap="ListItemsToday_Tap">
<TextBlock Name="TxtEvt" Text="{Binding Text}" TextWrapping="Wrap" Foreground="Gray" TextAlignment="Center" FontSize="30" Padding="30">
</TextBlock>
<Line X1="0" Y1="10" X2="240" Y2="10" Stroke="SkyBlue" HorizontalAlignment="Center" VerticalAlignment="Center" Height="21"/>
</StackPanel>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
like this:
private void ListItemsToday_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
var item = (sender as FrameworkElement).DataContext as TodoItem;
MessageBox.Show(item.Text);
}

How to do validation for Combobox value to match the database value?

I'm create an module which is a Editing Bill module which will enable the user to edit the available in the database. I'm facing one validation problem which is that when the user don't want to edit the bill & click on the "Cancel" button will back to the listview to continue select another record. Here is my problem come as when the user didn't make any modification & accidentally click on the "Status" combo from "UNPAID" to "PAID" then directly quite. When re select the record then the record status value will become "PAID" instead of "UNPAID" which is the actual value.
How can I do so that when every time the user don't make any modification & return back to the listview will set back the default value for the combobox.
Thank you all for viewing this question & hope to receive reply :)
I will attach my code so that easily to refer:
XAML File
<Window x:Class="HouseWivesSavior.HomecareModule.EditBillRemainder"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="EditBillRemainder" Height="600" Width="800" Loaded="Window_Loaded">
<Window.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FFFFFFFF" Offset="0"/>
<GradientStop Color="#FFFF00FF" Offset="1"/>
</LinearGradientBrush>
</Window.Background>
<Window.Resources>
<DataTemplate x:Key="MyDataTemplate">
<Border BorderBrush="#FF000000" BorderThickness="1,1,0,1" Margin="-6,-2,-6,-2">
<StackPanel Margin="6,2,6,2">
<TextBlock Text="{Binding Path=BillName}"/>
</StackPanel>
</Border>
</DataTemplate>
<DataTemplate x:Key="MyDataTemplate2">
<Border BorderBrush="#FF000000" BorderThickness="1,1,0,1" Margin="-6,-2,-6,-2">
<StackPanel Margin="6,2,6,2">
<TextBlock Text="{Binding Path=BillDescription}"/>
</StackPanel>
</Border>
</DataTemplate>
<DataTemplate x:Key="MyDataTemplate3">
<Border BorderBrush="#FF000000" BorderThickness="1,1,0,1" Margin="-6,-2,-6,-2">
<StackPanel Margin="6,2,6,2">
<TextBlock Text="{Binding Path=BillAmount}"/>
</StackPanel>
</Border>
</DataTemplate>
<DataTemplate x:Key="MyDataTemplate4">
<Border BorderBrush="#FF000000" BorderThickness="1,1,1,1" Margin="-6,-2,-6,-2">
<StackPanel Margin="6,2,6,2">
<TextBlock Text="{Binding Path=BillDueDate, StringFormat='dd-MM-yyyy'}"/>
</StackPanel>
</Border>
</DataTemplate>
<Style x:Key="MyItemContainerStyle" TargetType="{x:Type ListViewItem}">
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
<Setter Property="VerticalContentAlignment" Value="Stretch" />
<!--<EventSetter Event="PreviewMouseLeftButtonDown" Handler="ListViewItem_PreviewMouseLeftButtonDown" />-->
</Style>
<!--DatePickerTextBoxFormat-->
<Style TargetType="{x:Type DatePickerTextBox}">
<Setter Property="Control.Template">
<Setter.Value>
<ControlTemplate>
<TextBox x:Name="PART_TextBox" Text="{Binding Path=SelectedDate, StringFormat='dd-MM-yyyy', RelativeSource={RelativeSource AncestorType={x:Type DatePicker}}}" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid>
<ListView Name="lvwBooks" Background="White" ItemsSource="{Binding}" Margin="131,130,4,6" ItemContainerStyle="{DynamicResource MyItemContainerStyle}">
<ListView.View>
<GridView>
<GridViewColumn Header="Bill Name" Width="100" CellTemplate="{DynamicResource MyDataTemplate}"/>
<GridViewColumn Header="Description" Width="250" CellTemplate="{DynamicResource MyDataTemplate2}"/>
<GridViewColumn Header="Amount" Width="160" CellTemplate="{DynamicResource MyDataTemplate3}"/>
<GridViewColumn Header="Due Date" Width="100" CellTemplate="{DynamicResource MyDataTemplate4}"/>
<GridViewColumn Header="Edit">
<GridViewColumn.CellTemplate>
<DataTemplate>
<UserControl>
<Hyperlink Click="InputBox_Click">Edit
<Hyperlink.Style>
<Style TargetType="{x:Type Hyperlink}">
<Setter Property="Hyperlink.IsEnabled" Value="False" />
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType={x:Type ListViewItem}}, Path=IsSelected}" Value="True">
<Setter Property="Hyperlink.IsEnabled" Value="True" />
</DataTrigger>
</Style.Triggers>
</Style>
</Hyperlink.Style>
</Hyperlink>
</UserControl>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
<!-- It's important that this is in the end of the XAML as it needs to be on top of everything else! -->
<Grid x:Name="InputBox" Visibility="Collapsed">
<Grid Background="Black" Opacity="0.5" />
<Border
MinWidth="250"
Background="Orange"
BorderBrush="Black"
BorderThickness="1"
CornerRadius="0,40,0,40"
HorizontalAlignment="Center"
VerticalAlignment="Center" Height="493" Margin="130,30,120,38" Width="528">
<Canvas Height="446" Width="524">
<GroupBox Header="General Information" Height="141" HorizontalAlignment="Left" Margin="193,52,0,0" Name="groupBox1" VerticalAlignment="Top" Width="495" Canvas.Left="-173" Canvas.Top="-67">
<Canvas Background="WhiteSmoke" Opacity="1">
<GridSplitter Background="#FFBCBCBC" HorizontalAlignment="Left" Margin="207,13,0,140" ResizeBehavior="PreviousAndNext" Width="2" Height="50" Canvas.Left="-3" Canvas.Top="48" />
<TextBlock Height="23" HorizontalAlignment="Left" Margin="6,6,0,0" Name="textBlock1" Text="Bill Name" VerticalAlignment="Top" />
<TextBlock Height="23" HorizontalAlignment="Left" Margin="215,65,0,0" Name="textBlock4" Text="Due Date" VerticalAlignment="Top" Grid.ColumnSpan="2" />
<GridSplitter HorizontalAlignment="Left" ResizeBehavior="PreviousAndNext"
Width="1" Background="#FFBCBCBC" Margin="206,63,0,9" />
<DatePicker Height="25" HorizontalAlignment="Right" Margin="0,80,157,0" Name="BillDueDatedatePicker" VerticalAlignment="Top" Width="115" Grid.ColumnSpan="2" Canvas.Left="215" Canvas.Top="6" Text="{Binding Path=BillDueDate, StringFormat='dd-MM-yyyy'}" DataContext="{Binding ElementName=lvwBooks, Path=SelectedItem}" SelectedDateFormat="Short"/>
<TextBox Height="23" HorizontalAlignment="Left" Margin="7,29,0,0" Name="BillNameTxtBox" VerticalAlignment="Top" Width="458" Grid.ColumnSpan="2" DataContext="{Binding ElementName=lvwBooks, Path=SelectedItem}" Text="{Binding Path=BillName}"/>
<TextBlock Height="23" HorizontalAlignment="Left" Margin="7,63,0,0" Name="textBlock8" Text="Bill Type" VerticalAlignment="Top" />
<ComboBox Height="23" HorizontalAlignment="Left" Margin="8,81,0,0" Name="BillTypeCboBox" VerticalAlignment="Top" Width="193" Canvas.Left="-5" Canvas.Top="8" Text="{Binding Path=BillTypes}" DataContext="{Binding ElementName=lvwBooks, Path=SelectedItem}">
<ComboBoxItem Content="Water" />
<ComboBoxItem Content="Electricity" />
<ComboBoxItem Content="Gas" />
<ComboBoxItem Content="Internet/broadband"/>
<ComboBoxItem Content="Others"/>
</ComboBox>
<TextBox Canvas.Left="62" Canvas.Top="3" Height="23" Name="textBox1" Width="120" Visibility="Visible" DataContext="{Binding ElementName=lvwBooks, Path=SelectedItem}" Text="{Binding Path=BillNo}"/>
</Canvas>
</GroupBox>
<GroupBox Header="Payment Information" Height="339" HorizontalAlignment="Left" Margin="193,202,0,0" Name="groupBox2" VerticalAlignment="Top" Width="495" Canvas.Left="-174" Canvas.Top="-81">
<Canvas Background="WhiteSmoke" Height="303" Visibility="Visible">
<TextBlock Height="23" HorizontalAlignment="Left" Margin="7,17,0,0" Name="textBlock6" Text="Amount Due" VerticalAlignment="Top" />
<TextBlock Height="23" HorizontalAlignment="Left" Margin="7,75,0,0" Name="textBlock7" Text="Description" VerticalAlignment="Top" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="81,14,0,0" Name="BillAmountTxtBox" VerticalAlignment="Top" Width="120" DataContext="{Binding ElementName=lvwBooks, Path=SelectedItem}" Text="{Binding Path=BillAmount}"/>
<TextBox Height="148" HorizontalAlignment="Left" Margin="4,96,0,0" Name="BillDescriptionTxtBox" VerticalAlignment="Top" Width="471" VerticalScrollBarVisibility="Visible" SpellCheck.IsEnabled="True" TextWrapping="Wrap" AcceptsReturn="True" Text="{Binding Path=BillDescription}" DataContext="{Binding ElementName=lvwBooks, Path=SelectedItem}"/>
<TextBlock Height="23" HorizontalAlignment="Left" Margin="6,46,0,0" Name="textBlock9" Text="Status" VerticalAlignment="Top" />
<ComboBox Height="23" HorizontalAlignment="Left" Margin="81,46,0,0" Name="BillStatusCboBox" VerticalAlignment="Top" Width="120" SelectionChanged="comboBox3_SelectionChanged" Text="{Binding Path=BillStatus}" DataContext="{Binding ElementName=lvwBooks, Path=SelectedItem}" >
<ComboBoxItem Content="UNPAID" />
<ComboBoxItem Content="PAID" />
</ComboBox>
<TextBlock Height="23" HorizontalAlignment="Left" Margin="215,14,0,0" Name="textBlock10" Text="Bill is Paid:" VerticalAlignment="Top" />
<DatePicker Text="{Binding Path=BillPaidDate}" Height="25" HorizontalAlignment="Left" Margin="212,37,0,0" Name="BillPaidDatedatePicker" VerticalAlignment="Top" Width="115" IsEnabled="false" DataContext="{Binding ElementName=lvwBooks, Path=SelectedItem}"/>
<GridSplitter Background="#FFBCBCBC" HorizontalAlignment="Left" Margin="205,14,0,228" ResizeBehavior="PreviousAndNext" Width="2" />
<Separator Height="26" HorizontalAlignment="Left" Margin="7,250,0,0" Name="separator1" VerticalAlignment="Top" Width="470" />
<Button Content="Done" Height="23" HorizontalAlignment="Left" Margin="322,267,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="YesButton_Click" />
<Button Content="Cancel" Height="23" HorizontalAlignment="Left" Margin="402,266,0,0" Name="button2" VerticalAlignment="Top" Width="75" Click="NoButton_Click" />
<GridSplitter Background="#FFBCBCBC" HorizontalAlignment="Left" Margin="207,13,0,140" ResizeBehavior="PreviousAndNext" Width="0" />
</Canvas>
</GroupBox>
</Canvas>
</Border>
</Grid>
</Grid>
</Window>
Code Behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
namespace HouseWivesSavior.HomecareModule
{
/// <summary>
/// Interaction logic for EditBillRemainder.xaml
/// </summary>
public partial class EditBillRemainder : Window
{
public EditBillRemainder()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
ShowData();
}
private void InputBox_Click(object sender, RoutedEventArgs e)
{
// CoolButton Clicked! Let's show our InputBox.
InputBox.Visibility = System.Windows.Visibility.Visible;
}
private void NoButton_Click(object sender, RoutedEventArgs e)
{
//ShowData();
// NoButton Clicked! Let's hide our InputBox.
InputBox.Visibility = System.Windows.Visibility.Collapsed;
}
private void ListViewItem_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
var item = sender as ListViewItem;
if (item != null && item.IsSelected)
{
}
}
//Design
private void comboBox3_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
////The logic for this will be stanger but in order to cope iwht the SelectionChange behavior.
//string s1 = BillStatusCboBox.SelectionBoxItem.ToString();
//// MessageBox.Show(s1);
//if (s1.Equals("UNPAID"))
//{
// BillPaidDatedatePicker.IsEnabled = true;
// BillPaidDatedatePicker.Text = DateTime.Now.ToString("d/MM/yyyy");
//}
//if (s1.Equals("PAID"))
//{
// BillPaidDatedatePicker.IsEnabled = false;
// //BillStatusCboBox.SelectedIndex = 0;
//}
ComboBoxItem currentItem = ((System.Windows.Controls.ComboBoxItem)BillStatusCboBox.SelectedItem);
if (currentItem.Content.Equals("PAID"))
{
BillPaidDatedatePicker.IsEnabled = true;
// BuilderupdateButton.Visibility = Visibility.Visible;
}
else {
BillPaidDatedatePicker.IsEnabled = false;
}
}
//Database
public void ShowData()
{
SqlConnection conn;
string connStr = ConfigurationManager.ConnectionStrings["house"].ConnectionString;
conn = new SqlConnection(connStr);
//SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True");
conn.Open();
SqlCommand comm = new SqlCommand("Select * from bill ORDER BY BillDueDate", conn);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(comm);
da.Fill(dt);
lvwBooks.DataContext = dt.DefaultView;
}
private void YesButton_Click(object sender, RoutedEventArgs e)
{
Update();
// YesButton Clicked! Let's hide our InputBox and handle the input text.
InputBox.Visibility = System.Windows.Visibility.Collapsed;
}
public void Update() {
SqlConnection conn;
SqlCommand cmdInsert;
String strUpdate;
string connStr = ConfigurationManager.ConnectionStrings["house"].ConnectionString;
conn = new SqlConnection(connStr);
strUpdate = "UPDATE bill SET BillName=#BillName, BillTypes=#BillTypes, BillDueDate=#BillDueDate, BillAmount=#BillAmount, BillStatus=#BillStatus, BillPaidDate=#BillPaidDate, BillDescription=#BillDescription WHERE BillNo='" + textBox1.Text + "' ";
cmdInsert = new SqlCommand(strUpdate, conn);
cmdInsert.Parameters.AddWithValue("#BillName", BillNameTxtBox.Text);
cmdInsert.Parameters.AddWithValue("#BillTypes", BillTypeCboBox.Text);
cmdInsert.Parameters.AddWithValue("#BillDueDate", DateTime.Parse(BillDueDatedatePicker.Text));
cmdInsert.Parameters.AddWithValue("#BillAmount", BillAmountTxtBox.Text);
cmdInsert.Parameters.AddWithValue("#BillStatus", BillStatusCboBox.Text);
//MessageBox.Show(BillPaidDatedatePicker.Text);
if (BillPaidDatedatePicker.Text.Equals(""))
{
cmdInsert.Parameters.AddWithValue("#BillPaidDate", "");
}
else {
cmdInsert.Parameters.AddWithValue("#BillPaidDate", DateTime.Parse(BillPaidDatedatePicker.Text));
}
// cmdInsert.Parameters.AddWithValue("#BillPaidDate", DateTime.Parse(empty));
cmdInsert.Parameters.AddWithValue("#BillDescription", BillDescriptionTxtBox.Text);
try
{
conn.Open();
int result = cmdInsert.ExecuteNonQuery();
if (result == 1)
{
MessageBox.Show("Bill Edited!!!");
}
}
catch (SqlException ex)
{
MessageBox.Show(ex.ToString());
}
finally {
conn.Close();
}
}
}
}
For this case it would be better to user IDataErrorInfo interface instead of using ValiationRule since IDataErrorInfo will be handled inside ViewModel where you also have all the necessary database statements.
Here is a link to a tutorial explaining how to do validation with IDataErrorInfo.
http://codeblitz.wordpress.com/2009/05/08/wpf-validation-made-easy-with-idataerrorinfo/
Have fun :)
I solved it by like this:
Code-Behind:
The problem that I faced is NullReferenceException then I used a try..catch to catch the "NullReferenceException"
private void comboBox3_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ComboBoxItem currentItem = ((System.Windows.Controls.ComboBoxItem)BillStatusCboBox.SelectedItem);
try
{
if (currentItem.Content.Equals("PAID"))
{
BillPaidDatedatePicker.IsEnabled = true;
// BuilderupdateButton.Visibility = Visibility.Visible;
}
else
{
BillPaidDatedatePicker.IsEnabled = false;
}
}
catch (NullReferenceException ex){ // At here which you can see.
//I purposely set it to do nothing when catch it.
}
Then when the user accidentally click on the "UPAID" to "PAID" & directly click on the cancel button will invoke "NoButton_Click" which will try to reload & select the value from the database:
private void NoButton_Click(object sender, RoutedEventArgs e)
{
ShowData(); // Invoke & select from database again.
// NoButton Clicked! Let's hide our InputBox.
InputBox.Visibility = System.Windows.Visibility.Collapsed;
}
I know by this way solving my problem will be quite inefficient but get the job done :) Which is fine to me.

Categories