How to play BackgroundCapableMedia with PlayTo on Windows 8? - c#

I have in StandardStyles.xaml next code:
<Style x:Key="RootFrameStyle" TargetType="Frame">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Frame">
<Grid>
<MediaElement x:Name="MediaPlayer" AudioCategory="BackgroundCapableMedia" />
<ContentPresenter />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
and in App.Xaml.cs next code in OnLaunched:
...
rootFrame.Style = Resources["RootFrameStyle"] as Style;
...
in MainPage.xaml.cs code:
PlayToManager playToManager = null;
CoreDispatcher dispatcher = null;
private void LayoutAwarePage_Loaded_1(object sender, RoutedEventArgs e)
{
if (App.Player == null)
{
var rootGrid = VisualTreeHelper.GetChild(Window.Current.Content, 0);
App.Player = (MediaElement)VisualTreeHelper.GetChild(rootGrid, 0);
App.Player.Source = new Uri("http://myserverlink.com/mymp3file.mp3");
App.Player.Play();
}
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
dispatcher = Window.Current.CoreWindow.Dispatcher;
playToManager = PlayToManager.GetForCurrentView();
playToManager.SourceRequested += playToManager_SourceRequested;
}
void playToManager_SourceRequested(PlayToManager sender, PlayToSourceRequestedEventArgs args)
{
var deferral = args.SourceRequest.GetDeferral();
var handler = dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
args.SourceRequest.SetSource(App.Player.PlayToSource);
deferral.Complete();
});
}
And if I click devices in windows 8, in the list of devices for PlayTo no devices.
And if one is to add a MediaElement in MainPage.xaml, the devices in the list.
But I need to MediaElement was of Style File, what would you navigate to another page did not stop play music. What to do?

Related

DataGrid not populating with binding

I am trying to populate a DataGrid with an SQL query, and then be able to filter the datagrid. So far I have this:
XAML
<Window x:Name="ResultsWindow" x:Class="PixsellSheet.PixsellOrders"
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:PixsellSheet"
mc:Ignorable="d" Height="721.175" Width="1549.21" Title="edit" WindowStartupLocation="CenterScreen">
<Grid>
<DataGrid x:Name="Grid" HorizontalAlignment="Stretch" Height="Auto" Margin="20,55,20,40" VerticalAlignment="Stretch" Width="Auto" ItemsSource="{Binding DataGridColletion}">
<DataGrid.Resources>
<ContextMenu x:Key="DataGridColumnHeaderContextMenu">
<MenuItem Header="Filter" Click="MenuItem_Click"/>
</ContextMenu>
<Style TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="ContextMenu" Value="{StaticResource DataGridColumnHeaderContextMenu}"/>
</Style>
</DataGrid.Resources>
</DataGrid>
<Button x:Name="BtnBack" HorizontalAlignment="Left" Margin="20,10,0,0" VerticalAlignment="Top" Width="30" Click="BtnBack_Click" Padding="20,0,5,0">
<Button.Template>
<ControlTemplate TargetType="{x:Type Button}">
<Grid>
<Image Name="Normal" Source="back.png"/>
<Image Name="Pressed" Source="back_pressed.png"/>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsPressed" Value="True">
<Setter TargetName="Normal" Property="Visibility" Value="Hidden"/>
<Setter TargetName="Pressed" Property="Visibility" Value="Visible"/>
</Trigger>
<Trigger Property="IsPressed" Value="False">
<Setter TargetName="Normal" Property="Visibility" Value="Visible"/>
<Setter TargetName="Pressed" Property="Visibility" Value="Hidden"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Button.Template>
</Button>
<TextBox Height="27" Margin="0,10,20,0" TextWrapping="Wrap" VerticalAlignment="Top" HorizontalAlignment="Right" Width="524" Name="FilterBox" Padding="5,0,20,0"/>
<Label Content="Filter:" HorizontalAlignment="Right" Margin="0,10,550,0" VerticalAlignment="Top" Padding="5,0,5,0"/>
<Grid HorizontalAlignment="Left" Height="25" Margin="60,10,0,0" VerticalAlignment="Top" Width="20" />
</Grid>
C#
public partial class PixsellOrders : Window, INotifyPropertyChanged
{
public ICollectionView _dataGridCollection;
private string _filterString;
public ICollectionView DataGridCollection
{
get { return _dataGridCollection; }
set { _dataGridCollection = value; NotifyPropertyChanged("DataGridCollection"); }
}
public PixsellOrders(string windowTitle)
{
InitializeComponent();
string query = "";
ResultsWindow.Title = windowTitle;
Console.WriteLine(windowTitle);
if (windowTitle == "PixSell Orders All")
{
query = "EXEC Reporting.dbo.Pixsell_Orders_All";
}
else if (windowTitle == "PixSell Orders Eday")
{
query = "EXEC Reporting.dbo.Pixsell_Orders_Eday";
}
Console.WriteLine(query);
try
{
DataTable pixsellOrders = SqlConnect(query);
foreach (DataColumn column in pixsellOrders.Columns)
{
column.ReadOnly = true;
if (column.ColumnName == "Person" && windowTitle != "PixSell Orders All")
{
pixsellOrders.Columns["Person"].ReadOnly = false;
}
else if (column.ColumnName == "Sales Notes" && windowTitle != "PixSell Orders All")
{
pixsellOrders.Columns["Sales Notes"].ReadOnly = false;
}
}
DataGridCollection = CollectionViewSource.GetDefaultView(pixsellOrders.AsEnumerable());
DataGridCollection.Filter = new Predicate<object>(Filter);
pixsellOrders.ColumnChanged += new DataColumnChangeEventHandler(Column_Changed);
}
catch (SqlException sqlEr)
{
Console.WriteLine(sqlEr);
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
_dataGridCollection.Refresh();
}
}
public DataTable SqlConnect(string query)
{
SqlConnection ohsql1;
string sqlQuery = query;
ohsql1 = new SqlConnection("Data Source=OHSQL1;Initial Catalog=Reporting;Integrated Security = true");
DataTable table = new DataTable();
try
{
//connect
ohsql1.Open();
//fill datatable with results
SqlDataAdapter a = new SqlDataAdapter(sqlQuery, ohsql1);
//fill table
a.Fill(table);
//kill connection
a.Dispose();
ohsql1.Close();
}
catch (SqlException e)
{
Console.WriteLine("SQL ERROR: " + e);
}
return table;
}
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
_filterString = FilterBox.Text;
if (_filterString == "")
{
Console.WriteLine("no filter");
return;
}
else
{
Console.WriteLine(_filterString);
FilterCollection();
}
}
private void FilterCollection()
{
if (_dataGridCollection != null)
{
_dataGridCollection.Refresh();
}
}
private bool Filter(object obj)
{
if (obj is DataRow data)
{
if (!string.IsNullOrEmpty(_filterString))
{
return data["CUNAME"].ToString().Contains(_filterString);
}
else
{
return true;
}
}
return false;
}
The "CUNAME" column specified is just a test, eventually I want to have it know which column the filter button was pressed on.
The problem I am getting is that the DataGrid is returning empty. When I do Grid.ItemsSource = pixsellOrders.DefaultView (or something to that effect, can't remember the exact syntax) it works fine and populates the grid.
I have tried changing to a List which would definitely be IEnumerable but that wasn't populating the data grid either. Adding AutoGenerateColumns (either to true or false) has no effect. No errors are being shown in the output. Commenting out all the filter parts also has no effect. Removing the Context menu also has no effect. Removing AsEnumerable() has no effect on the grid population but throws and error at DataGridCollection.Filter.
Can anyone see where this is going wrong? And if you can advise how I might go about getting the column name to check (rather than hard coding all columns) that we be really helpful as well)
Thank you in advance
Set the DataContext of the Window to itself:
public PixsellOrders(string windowTitle)
{
InitializeComponent();
DataContext = this;
//...
}

Implementing Virtual File Drop in WPF using VirtualFileDataObject

I'm using the solution from this project: http://dlaa.me/blog/post/9913083#comment-2930777923
I wanted to make my WPF program able to process the virtual file dropped into it, but I'm stuck with reading the relevant data from the MemoryStream, what I receive from DragEventArgs e.Data.GetData().
I've read many posts. the closest were:
https://blogs.msdn.microsoft.com/delay/2009/11/04/creating-something-from-nothing-asynchronously-developer-friendly-virtual-file-implementation-for-net-improved/#10040454
https://www.codeproject.com/Articles/23139/Transferring-Virtual-Files-to-Windows-Explorer-in
and the above mentioned, of course
and many others to drag&drop local files, that obviously don't help
But all of them handle the from-my-app-to-filesystem case only.
Without any fancy mvvm stuff...
where I don't get any further is the
private void Label_Drop(object sender, DragEventArgs e){...}
method in my code behind:
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows;
using System.Windows.Input;
using Delay;
using System.Runtime.Serialization.Formatters.Binary;
namespace VirtualFileDataObjectDemo
{
public partial class Window1 : Window
{
private static TextWriterTraceListener traceListener;
private string logPath;
private string filePath;
// From Windows SDK header files
private const string CFSTR_INETURLA = "UniformResourceLocator";
public Window1()
{
//logPath = Path.Combine(#"d:\Temp", #"Log\TextWriterOutput.log");
logPath = Path.Combine(Directory.GetCurrentDirectory(), #"Log\TextWriterOutput.log");
filePath = Path.Combine(Directory.GetCurrentDirectory(), #"Log");
traceListener = new TextWriterTraceListener(logPath, "traceListener");
InitializeComponent();
// Attach to interesting events
Text.MouseLeftButtonDown += new MouseButtonEventHandler(Text_MouseButtonDown);
Text.MouseRightButtonDown += new MouseButtonEventHandler(Text_MouseButtonDown);
TextUrl.MouseLeftButtonDown += new MouseButtonEventHandler(TextUrl_MouseButtonDown);
TextUrl.MouseRightButtonDown += new MouseButtonEventHandler(TextUrl_MouseButtonDown);
VirtualFile.MouseLeftButtonDown += new MouseButtonEventHandler(VirtualFile_MouseButtonDown);
VirtualFile.MouseRightButtonDown += new MouseButtonEventHandler(VirtualFile_MouseButtonDown);
MoreVirtualFiles.MouseLeftButtonDown += new MouseButtonEventHandler(TextUrlVirtualFile_MouseButtonDown);
MoreVirtualFiles.MouseRightButtonDown += new MouseButtonEventHandler(TextUrlVirtualFile_MouseButtonDown);
}
private void Text_MouseButtonDown(object sender, MouseButtonEventArgs e) //TEXT
{
var virtualFileDataObject = new VirtualFileDataObject();
// Provide simple text (in the form of a NULL-terminated ANSI string)
virtualFileDataObject.SetData(
(short)(DataFormats.GetDataFormat(DataFormats.Text).Id),
Encoding.Default.GetBytes("This is some sample text\0"));
DoDragDropOrClipboardSetDataObject(e.ChangedButton, Text, virtualFileDataObject, DragDropEffects.Copy);
}
private void TextUrl_MouseButtonDown(object sender, MouseButtonEventArgs e) //WEBADDRESS
{
var virtualFileDataObject = new VirtualFileDataObject();
// Provide simple text and an URL in priority order
// (both in the form of a NULL-terminated ANSI string)
virtualFileDataObject.SetData(
(short)(DataFormats.GetDataFormat(CFSTR_INETURLA).Id),
Encoding.Default.GetBytes("http://blogs.msdn.com/delay/\0"));
virtualFileDataObject.SetData(
(short)(DataFormats.GetDataFormat(DataFormats.Text).Id),
Encoding.Default.GetBytes("http://blogs.msdn.com/delay/\0"));
DoDragDropOrClipboardSetDataObject(e.ChangedButton, TextUrl, virtualFileDataObject, DragDropEffects.Copy);
}
private void VirtualFile_MouseButtonDown(object sender, MouseButtonEventArgs e) //VIRTUALFILE
{
var virtualFileDataObject = new VirtualFileDataObject(
null,
(vfdo) =>
{
if (DragDropEffects.Move == vfdo.PerformedDropEffect)
{
// Hide the element that was moved (or cut)
// BeginInvoke ensures UI operations happen on the right thread
Dispatcher.BeginInvoke((Action)(() => VirtualFile.Visibility = Visibility.Hidden));
}
});
// Provide a virtual file (generated on demand) containing the letters 'a'-'z'
virtualFileDataObject.SetData(new VirtualFileDataObject.FileDescriptor[]
{
new VirtualFileDataObject.FileDescriptor
{
Name = "Alphabet.txt",
Length = 26,
ChangeTimeUtc = DateTime.Now.AddDays(-1),
StreamContents = stream =>
{
var contents = Enumerable.Range('a', 26).Select(i => (byte)i).ToArray();
stream.Write(contents, 0, contents.Length);
}
},
});
DoDragDropOrClipboardSetDataObject(e.ChangedButton, TextUrl, virtualFileDataObject, DragDropEffects.Move | DragDropEffects.Copy);
}
private void TextUrlVirtualFile_MouseButtonDown(object sender, MouseButtonEventArgs e) //ALL THREE TOGETHER
{
var virtualFileDataObject = new VirtualFileDataObject(
// BeginInvoke ensures UI operations happen on the right thread
(vfdo) => Dispatcher.BeginInvoke((Action)(() => BusyScreen.Visibility = Visibility.Visible)),
(vfdo) => Dispatcher.BeginInvoke((Action)(() => BusyScreen.Visibility = Visibility.Collapsed)));
virtualFileDataObject.SetData(new VirtualFileDataObject.FileDescriptor[]
{
new VirtualFileDataObject.FileDescriptor
{
Name = "Example.xml",
StreamContents = stream =>
{
using(var webClient = new WebClient())
{
var data = webClient.DownloadData("https://www.w3schools.com/xml/note.xml");
stream.Write(data, 0, data.Length);
}
}
},
new VirtualFileDataObject.FileDescriptor
{
Name = "Example2.xml",
StreamContents = stream =>
{
using(var webClient = new WebClient())
{
var data = webClient.DownloadData("https://www.w3schools.com/xml/cd_catalog.xml");
stream.Write(data, 0, data.Length);
}
}
},
new VirtualFileDataObject.FileDescriptor
{
Name = "Example3.xml",
StreamContents = stream =>
{
using(var webClient = new WebClient())
{
var data = webClient.DownloadData("https://www.w3schools.com/xml/plant_catalog.xml");
stream.Write(data, 0, data.Length);
}
}
},
});
DoDragDropOrClipboardSetDataObject(e.ChangedButton, MoreVirtualFiles, virtualFileDataObject, DragDropEffects.Move | DragDropEffects.Copy);
}
private static void DoDragDropOrClipboardSetDataObject(MouseButton button, DependencyObject dragSource, VirtualFileDataObject virtualFileDataObject, DragDropEffects allowedEffects)
{
try
{
if (button == MouseButton.Left)
{
// Left button is used to start a drag/drop operation
VirtualFileDataObject.DoDragDrop(dragSource, virtualFileDataObject, allowedEffects);
}
else if (button == MouseButton.Right)
{
// Right button is used to copy to the clipboard
// Communicate the preferred behavior to the destination
virtualFileDataObject.PreferredDropEffect = allowedEffects;
Clipboard.SetDataObject(virtualFileDataObject);
}
}
catch (COMException ce)
{
traceListener.WriteLine("COM Exception");
traceListener.WriteLine(ce);
traceListener.WriteLine(ce.Message);
traceListener.WriteLine(ce.InnerException);
// Failure; no way to recover
}
}
private void Label_Drop(object sender, DragEventArgs e)
{
try
{
dropLabel.Content = "";
string[] retrievedFormats = e.Data.GetFormats();
foreach (string retFormat in retrievedFormats)
{
object retrievedData = e.Data.GetData(retFormat);
dropLabel.Content = dropLabel.Content + Environment.NewLine + retrievedData.ToString() + " - " + retFormat;
}
}
catch (Exception ex)
{
traceListener.WriteLine("-------------");
traceListener.WriteLine(ex + Environment.NewLine);
traceListener.WriteLine(ex.Message + Environment.NewLine);
traceListener.WriteLine(ex.StackTrace + Environment.NewLine);
traceListener.WriteLine("-------------");
traceListener.Flush();
}
}
private void Label_DragEnter(object sender, DragEventArgs e)
{
e.Effects = DragDropEffects.Copy;
}
}
}
and the XAML:
<Window x:Class="VirtualFileDataObjectDemo.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="VirtualFileDataObjectDemo"
Height="800"
Width="800">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<UniformGrid
Rows="5"
Background="#ffdddddd"
TextElement.FontSize="22"
TextElement.FontWeight="Bold">
<UniformGrid.Resources>
<Style TargetType="{x:Type Label}">
<Setter Property="Background" Value="Orange"/>
<Setter Property="Foreground" Value="White"/>
<Setter Property="BorderBrush" Value="Black"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
<Setter Property="VerticalContentAlignment" Value="Center"/>
<Setter Property="Margin" Value="10"/>
</Style>
</UniformGrid.Resources>
<ContentControl
Content="Drag an item or right-click to copy it:"
FontSize="18"
VerticalAlignment="Center"
Margin="20"/>
<Label
x:Name="Text"
Content="Text only"/>
<Label
x:Name="TextUrl"
Content="Text and URL"/>
<Label
x:Name="VirtualFile">
<DockPanel>
<ContentControl
Content="Virtual file"
DockPanel.Dock="Left"
VerticalAlignment="Center"/>
<ContentControl
Content="[Drag moves; paste cuts]"
FontSize="14"
HorizontalAlignment="Right"
VerticalAlignment="Center"/>
</DockPanel>
</Label>
<Label
x:Name="MoreVirtualFiles"
Content="More virtual files"/>
</UniformGrid>
<Grid
x:Name="BusyScreen"
Background="LightGray"
Visibility="Collapsed">
<StackPanel
VerticalAlignment="Center"
Margin="50">
<Viewbox>
<TextBlock Text="Busy..."/>
</Viewbox>
<ProgressBar IsIndeterminate="True" Height="20"/>
</StackPanel>
</Grid>
<Label Name="dropLabel" Grid.Row="1" Content="Drop Area" MinHeight="50" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" FontSize="20" AllowDrop="True" Drop="Label_Drop" DragEnter="Label_DragEnter"/>
</Grid>
</Window>
The VirtualFileDataObject can be downloaded from here:
http://dlaa.me/Samples/VirtualFileDataObjectDemo/VirtualFileDataObjectDemo.zip
Thanks to James Barrass.
His solution in this topic here:
Dropped zip file causes e.Data.GetData("FileContents") to throw an exception
solved my problem.

Changing content of button removes style WPF

Changing the content image of a button makes it ignore any previously defined layout properties.
What I suspect is the fact that upon changing this.Content in the Button click event, it modifies:
<Button>
Everything found between these tags.
</Button>
And as my Style is inside those tags, it overrides it.
Here is the code for record:
private void ChangeImageFile(object sender, RoutedEventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Image Files|*.png;*.jpeg;*.tiff;*.gif;*.bmp;*.jpg";
ofd.FilterIndex = 1;
ofd.Multiselect = false;
bool? ok = ofd.ShowDialog();
if(ok == true)
{
Image loaded = new Image();
loaded.Source = new BitmapImage(new Uri(ofd.FileName));
loaded.Height = 100;
this.Content = loaded;
}
}
 
<Button x:Name="BookCover" Click="ChangeImageFile">
<Button.Content>
<Image Source="Images/NewBook.png"/>
</Button.Content>
<Button.Style>
<Style TargetType="{x:Type Button}">
... LONG STYLE ...
</Style>
</Button.Style>
</Button>
When you're using this.Content, this refers to the current window and not to the button. You either need to access the button by Name or cast the sender.
By Name:
BookCover.Content = loaded;
Cast the sender:
Button btn = (sender as Button);
if(btn != null)
btn.Content = loaded;

Bug in PopupMenu when background work is begin done?

I am building a Universal App and I think I have found a bug in the Windows Phone 8.1 PopupMenu control. I have been able to reproduce it with a small piece of code. It works fine on Windows 8 but not on Windows Phone 8.1.
Whenever I create a PopupMenu from within a button click it doesn't return from ShowFromSelectionAsync() when there is a background task running ? Why ?
The same code works on Windows 8.
I my application a lot of background work is being done, so the control doesn't work correctly on Phone anymore. Any suggestions how to fix this ?
I have a MainPage.xaml:
<Page
x:Class="PopupMenuBugPhone.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:PopupMenuBugPhone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<StackPanel>
<Button Content="Test Bug" Click="Button_Click" />
</StackPanel>
</Grid>
</Page>
MainPage.xaml.cs:
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
var frameworkElement = sender as FrameworkElement;
var task = SimulateBackgroundWork(); // COMMENT THIS TO MAKE IT WORK ON PHONE!!!
var menu = new PopupMenu();
var сmdOption1 = new UICommand("Option1");
var cmdOption2 = new UICommand("Option2");
menu.Commands.Add(сmdOption1);
menu.Commands.Add(cmdOption2);
// We don't want to obscure content, so pass in a rectangle representing the sender of the context menu event.
var chosenCommand = await menu.ShowForSelectionAsync(frameworkElement.GetElementRect());
if (chosenCommand == null) // The command is null if no command was invoked.
{
await new MessageDialog("No choice").ShowAsync();
}
else
{
await new MessageDialog("Choice: " + chosenCommand.Label).ShowAsync();
}
await task; // COMMENT THIS TO MAKE IT WORK ON PHONE!!!
}
private Task SimulateBackgroundWork()
{
var t = Task.Run(() =>
{
var dt = DateTime.Now;
// Do some dummy processing loop
while (DateTime.Now < dt.AddSeconds(300))
{
;
}
});
return t;
}
}
How about using a MenuFlyout?
Let's say you defined it in code-behind of the page, along with the TaskCompletionSource to wrap it to make showing awaitable:
MenuFlyout flyout = new MenuFlyout();
TaskCompletionSource<string> tcs;
Then on button click you could do this:
private async void Button_Click(object sender, RoutedEventArgs e)
{
var frameworkElement = sender as FrameworkElement;
var task = SimulateBackgroundWork();
flyout.Closed += flyout_Closed;
var mf1 = new MenuFlyoutItem { Text = "Option1" };
var mf2 = new MenuFlyoutItem { Text = "Option2" };
mf1.Click += mf_Click;
mf2.Click += mf_Click;
flyout.Items.Clear();
flyout.Items.Add(mf1);
flyout.Items.Add(mf2);
await ShowMenuFlyout(sender as FrameworkElement);
await task;
}
ShowMenuFlyout is awaitable and implemented like this:
public Task<string> ShowMenuFlyout(FrameworkElement sender)
{
tcs = new TaskCompletionSource<string>();
flyout.ShowAt(sender as FrameworkElement);
return tcs.Task;
}
And event handlers would simply do this:
async void mf_Click(object sender, RoutedEventArgs e)
{
flyout.Closed -= flyout_Closed;
await new MessageDialog("Choice: " + (sender as MenuFlyoutItem).Text).ShowAsync();
tcs.SetResult((sender as MenuFlyoutItem).Text);
}
async void flyout_Closed(object sender, object e)
{
flyout.Closed -= flyout_Closed;
await new MessageDialog("No choice").ShowAsync();
tcs.SetResult("No choice");
}
This works on both platforms. Of course, this is just proof of concept, you might want a null check here or there, but it works.

Change image of a button that is on an element of a LongListSelector

I have this longListSelector:
<phone:LongListSelector
x:Name="ListaMensajesTablon"
ItemsSource="{Binding Mensajes}"
ItemTemplate="{StaticResource MensajesTablonDataTemplate}"
SelectionChanged="MensajeTablonSelected"/>
With this ItemTemplate:
<DataTemplate x:Key="MensajesTablonDataTemplate">
<Grid>
<Button MaxHeight="85" MaxWidth="95" MinHeight="85" MinWidth="95" Grid.Column="1" HorizontalAlignment="Right" VerticalAlignment="Center" Click="Button_Click" BorderBrush="Transparent">
<Button.Content>
<Image x:Name="imagenFav" MaxHeight="75" MaxWidth="75" MinHeight="75" MinWidth="75"
Source="{Binding userFav, Converter={StaticResource BoolToHeart}}" VerticalAlignment="Center" HorizontalAlignment="Center"/>
</Button.Content>
</Button>
</Grid>
</DataTemplate>
This code-behind:
private void Button_Click(object sender, RoutedEventArgs e)
{
botonFavPulsado = true;
botonAmor = (Button)sender;
}
private void MensajeTablonSelected(object sender, SelectionChangedEventArgs e)
{
if(botonFavPulsado)
{
var myItem = ((LongListSelector)sender).SelectedItem as MensajeTablon;
if(botonAmor!=null)
{
if (myItem.userFav)
{
botonAmor.Content = new Image
{
Source = new BitmapImage(new Uri("icons/heart.red.png", UriKind.Relative))
};
}
else
{
botonAmor.Content = new Image
{
Source = new BitmapImage(new Uri("icons/heart.white.png", UriKind.Relative))
};
}
}
botonFavPulsado = false;
}
}
I want to do is that when you press a button that is inside an element of LongListSelector change the picture . The first time I press the button enters in the function Button_Click and then enters in the function MensajeTablonSelected function and change the image (good). The problem is the second time I press the same button is entering in the function Button_Click function and does not enter in the function MensajeTablonSelected
Resume : ToggleButton in LongItemSelector working the first time but not the second one
Problem solved:
private void MensajeTablonSelected(object sender, SelectionChangedEventArgs e)
{
if (((LongListSelector)sender).SelectedItem != null)
if(botonFavPulsado)
{
var myItem = ((LongListSelector)sender).SelectedItem as MensajeTablon;
if(botonAmor!=null)
{
if (myItem.userFav)
{
botonAmor.Content = new Image
{
Source = new BitmapImage(new Uri("icons/heart.red.png", UriKind.Relative))
};
}
else
{
botonAmor.Content = new Image
{
Source = new BitmapImage(new Uri("icons/heart.white.png", UriKind.Relative))
};
}
}
botonFavPulsado = false;
//Unselect ITEM
((LongListSelector)sender).SelectedItem = null;
}
}
This solution have a problem, the function MensajeTablonSelected is called again.

Categories