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.
Related
I have a listview whose data is extracted from sqlite database, as shown below:
I want to check the user click the delete button, then the data on the list is deleted and the data in the sqlite database also deleted.
XAML:
<ListView x:Name="ListTryout" Grid.Row="1" Margin="0,5,0,10" ItemsSource="{Binding Source={StaticResource itemsViewSource}}" DataContext="{Binding SelectedItem, ElementName=itemListView}" IsItemClickEnabled="True" SelectionChanged="ListTryout_SelectionChanged" Background="{x:Null}" SelectionMode="Single">
<ListView.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="auto"/>
</Grid.ColumnDefinitions>
<StackPanel Grid.Column="0" Orientation="Vertical">
<TextBlock Margin="10,10,0,0" FontSize="20" Text="{Binding Judul}" Style="{StaticResource CaptionTextBlockStyle}" VerticalAlignment="Top" HorizontalAlignment="Left"/>
<TextBlock Margin="10,10,0,0" FontSize="17" Text="{Binding JumlahSoal}" VerticalAlignment="Top" HorizontalAlignment="Left" FontWeight="SemiLight"/>
<TextBlock Margin="10,10,0,0" FontSize="17" Text="{Binding Durasi}" VerticalAlignment="Top" HorizontalAlignment="Left" FontWeight="SemiLight" Visibility="Collapsed"/>
<Line X1="0" X2="1" Stretch="Fill" Margin="10,10,10,0" Stroke="#FF4B4B4B"/>
</StackPanel>
<AppBarButton x:Name="deleteItemBtn" Grid.Column="1" Margin="0,0,50,0" Icon="Delete" HorizontalAlignment="Right" Click="deleteItemBtn_Click"/>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Code:
private void ReadTryoutList_Loaded(object sender, RoutedEventArgs e)
{
ReadAllDBName dbName = new ReadAllDBName();
DB_TryoutList = dbName.GetAllDBName();
ListTryout.ItemsSource = DB_TryoutList.OrderByDescending(i => i.ID).ToList();//Binding DB data to LISTBOX and Latest contact ID can Display first.
if(DB_TryoutList.Count == 0)
{
statuskosongStack.Visibility = Visibility.Visible;
ListTryout.Visibility = Visibility.Collapsed;
}
else
{
statuskosongStack.Visibility = Visibility.Collapsed;
ListTryout.Visibility = Visibility.Visible;
}
}
private void deleteItemBtn_Click(object sender, RoutedEventArgs e)
{
Db_Helper.DeleteQuiz(currentquiz.ID);
}
DatabaseHelper class:
public void CreateDatabase(string DB_PATH)
{
if (!CheckFileExists(DB_PATH).Result)
{
using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), DB_PATH))
{
conn.CreateTable<DBName>();
}
}
}
private async Task<bool> CheckFileExists(string fileName)
{
try
{
var store = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync(fileName);
return true;
}
catch
{
return false;
}
}
// Insert the new history in the DBName table.
public void Insert(DBName dBName)
{
using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), App.DB_PATH))
{
conn.RunInTransaction(() =>
{
conn.Insert(dBName);
});
}
}
public DBName ReadName(int quizid)
{
using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), App.DB_PATH))
{
var existingName = conn.Query<DBName>("select * from DBName where ID =" + quizid).FirstOrDefault();
return existingName;
}
}
public ObservableCollection<DBName> ReadAllDBName()
{
try
{
using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), App.DB_PATH))
{
List<DBName> myCollection = conn.Table<DBName>().ToList<DBName>();
ObservableCollection<DBName> DBNameList = new ObservableCollection<DBName>(myCollection);
return DBNameList;
}
}
catch
{
return null;
}
}
public void DeleteQuiz(string ID)
{
using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), App.DB_PATH))
{
var existingquiz = conn.Query<DBName>("delete from DBName where ID ='" + ID + "'").FirstOrDefault();
if (existingquiz != null)
{
conn.RunInTransaction(() =>
{
conn.Delete(existingquiz);
});
}
}
}
I tried it, but the data can not be deleted on listview and also on the sqlite database.
How to handle it?
Set or bind the ItemsSource of the ListView to an ObservableCollection<T> and remove the item from this one, e.g.:
private ObservableCollecton<DBName> _source;
private void ReadTryoutList_Loaded(object sender, RoutedEventArgs e)
{
ReadAllDBName dbName = new ReadAllDBName();
DB_TryoutList = dbName.GetAllDBName();
_source = new ObservableCollecton<DBName>(DB_TryoutList.OrderByDescending(i => i.ID).ToList());
ListTryout.ItemsSource = _source;
if (DB_TryoutList.Count == 0)
{
statuskosongStack.Visibility = Visibility.Visible;
ListTryout.Visibility = Visibility.Collapsed;
}
else
{
statuskosongStack.Visibility = Visibility.Collapsed;
ListTryout.Visibility = Visibility.Visible;
}
}
private void deleteItemBtn_Click(object sender, RoutedEventArgs e)
{
var btn = sender as AppBarButton;
var item = btn.DataContext as DBName;
if (item != null)
{
_source.Remove(item);
Db_Helper.DeleteQuiz(currentquiz.ID);
}
}
I assume that GetAllDBName() are returning an IEnumerable<DBName> and that you are displaying DBNames in the ListView.
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;
//...
}
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.
First of all - please excuse my poor pronunciation.
I'm programming a wpf-validator for a excelsheet and while this programm is getting Infos from google it should show the progress on a progressbar. I've read a lot of articles in the web about multithreading and backgroundworking but I think nothing can really help me.
Here is my GUI
<Window x:Class="DatenValidierung.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="570" Width="825" ResizeMode="NoResize">
<Grid Background="Black">
<Button Foreground="White" Background="Black" Name="exit" Content="Exit" HorizontalAlignment="Left" Margin="714,484,0,0" VerticalAlignment="Top" Width="94" Click="exit_Click" Height="27"/>
<Button Foreground="White" Background="Black" Name="open" Content="Excel öffnen" HorizontalAlignment="Left" Margin="10,460,0,0" VerticalAlignment="Top" Width="88" Click="open_Click" />
<DataGrid Name="dg1" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Height="445" Width="798" AutoGenerateColumns="False" IsReadOnly="True">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding SubCategory}" Header="Kat" Width="90" />
<DataGridTextColumn Binding="{Binding Title}" Header="Title" Width="80" />
<DataGridTextColumn Binding="{Binding InfoText}" Header="Info" Width="80" />
<DataGridTextColumn Binding="{Binding Domain}" Header="Domain" Width="60" />
<DataGridTextColumn Binding="{Binding City}" Header="City" Width="50" />
<DataGridTextColumn Binding="{Binding Zipcode}" Header="Zip" Width="50" />
<DataGridTextColumn Binding="{Binding Longitude}" Header="Long" Width="50" />
<DataGridTextColumn Binding="{Binding Latitude}" Header="Lat" Width="50" />
<DataGridTextColumn Binding="{Binding Telefon}" Header="Tel" Width="50" />
<DataGridTextColumn Binding="{Binding Mail}" Header="Mail" Width="50" />
<DataGridTextColumn Binding="{Binding Address}" Header="Adresse" Width="50" />
</DataGrid.Columns>
</DataGrid>
<Button Content="Hochladen" Background="Black" Foreground="White" Name="upload" Click="upload_Click" HorizontalAlignment="Left" Margin="10,508,0,0" VerticalAlignment="Top" Width="88"/>
<Button Content="google-Daten" Name="check" Background="Black" Foreground="White" HorizontalAlignment="Left" Margin="10,484,0,0" VerticalAlignment="Top" Width="88" Click="check_Click"/>
<ProgressBar Value="{Binding Path=ProgressValue}" HorizontalAlignment="Left" Height="24" Margin="270,460,0,0" VerticalAlignment="Top" Width="200" Name="pb1"/>
<Label Name="progressLabel" Foreground="White" TextBlock.TextAlignment="Center" Content="" HorizontalAlignment="Left" Margin="320,489,0,0" VerticalAlignment="Top" Width="100"/>
</Grid>
</Window>
And here is my CodeBehind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Forms;
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.Navigation;
using System.Windows.Shapes;
using Excel = Microsoft.Office.Interop.Excel;
using System.Data.OleDb;
using System.Data;
using System.Globalization;
using System.ComponentModel;
using System.Threading;
using System.Net;
using System.Xml.Linq;
using DatenValidierung.ServiceReference1;
namespace DatenValidierung
{
public partial class MainWindow : Window
{
int progressCounter = 0;
List<Location> locationList = new List<Location>();
public MainWindow()
{
InitializeComponent();
}
double progressValue;
public double ProgressValue
{
get { return progressValue; }
set
{
if (progressValue != value)
{
progressValue = value;
OnPropertyChanged("ProgressValue");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string property_name)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(property_name));
}
public static DataTable ReadExcelData(string filePath)
{
System.Data.DataTable dtExcel = new System.Data.DataTable();
dtExcel.TableName = "MyExcelData";
bool hasHeaders = false;
string strConn = string.Empty;
string HDR = hasHeaders ? "Yes" : "No";
if (filePath.Substring(filePath.LastIndexOf('.')).ToLower() == ".xlsx")
{
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 12.0;HDR=" + HDR + ";IMEX=0\"";
}
else
{
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=\"Excel 8.0;HDR=" + HDR + ";IMEX=0\"";
}
//string SourceConstr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='MyExcelFilePath';Extended Properties= 'Excel 8.0;HDR=Yes;IMEX=1'";
OleDbConnection con = new OleDbConnection(strConn);
con.Open();
DataTable schemaTable = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
DataRow schemaRow = schemaTable.Rows[0];
string sheet = schemaRow["TABLE_NAME"].ToString();
string query = "SELECT * FROM [" + sheet + "]";
OleDbDataAdapter data = new OleDbDataAdapter(query, con);
data.Fill(dtExcel);
return dtExcel;
}
private void open_Click(object sender, RoutedEventArgs e)
{
var dataFromExcel = new DataTable();
string ausgabeTemp = String.Empty;
OpenFileDialog BrowserFileDialog = new OpenFileDialog();
BrowserFileDialog.Title = "";
BrowserFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
BrowserFileDialog.FilterIndex = 1;
BrowserFileDialog.RestoreDirectory = true;
if (BrowserFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
dataFromExcel = ReadExcelData(BrowserFileDialog.FileName);
}
var liste = dataFromExcel.AsEnumerable().ToList();
int k = 0;
for (int i = 0; i < liste.Count; i++)
{
Location loc = new Location();
loc.SubCategory = liste[k].ItemArray[0].ToString();
loc.City = liste[k].ItemArray[1].ToString();
loc.Zipcode = liste[k].ItemArray[2].ToString();
loc.Address = liste[k].ItemArray[3].ToString();
loc.Telefon = liste[k].ItemArray[4].ToString();
loc.Mail = liste[k].ItemArray[5].ToString();
loc.Domain = liste[k].ItemArray[6].ToString();
loc.SubCategory = liste[k].ItemArray[7].ToString();
loc.InfoText = liste[k].ItemArray[8].ToString();
locationList.Add(loc);
k++;
}
pb1.Maximum = k;
pb1.Minimum = 0;
var fred = new Thread(updateProgressBar);
fred.IsBackground = true;
fred.Start();
FormatList(locationList);
}
public void updateProgressBar()
{
ProgressValue = ((double)progressCounter * 100) / locationList.Count ;
progressLabel.Content = ProgressValue + " / 100";
}
public List<Location> FormatList(List<Location> locationList)
{
var locList = locationList;
locList = FormatLocationForDB(locList);
for (int i = 0; i < locList.Count; i++)
{
if (locList[i].Latitude == 0 || locList[0].Longitude == 0)
{
locList[i] = GetSingleFormatForDB(locList[i]);
}
}
return locList;
}
public List<Location> FormatLocationForDB(object o)
{
progressCounter = 0;
var locList = new List<Location>();
foreach (Location currentLocation in locationList)
{
Thread.Sleep(50);
// System.Threading.Thread.Sleep(200);
string address = currentLocation.Address + ", " + currentLocation.City;
var requestUri = string.Format("http://maps.googleapis.com/maps/api/geocode/xml?address={0}&sensor=false", Uri.EscapeDataString(address));
var request = WebRequest.Create(requestUri);
var response = request.GetResponse();
var xdoc = XDocument.Load(response.GetResponseStream());
try
{
var result = xdoc.Element("GeocodeResponse").Element("result");
var locationElement = result.Element("geometry").Element("location");
currentLocation.Latitude = (float)(locationElement.Element("lat"));
currentLocation.Longitude = (float)(locationElement.Element("lng"));
}
catch (Exception x)
{
}
dg1.Items.Add(currentLocation);
dg1.InvalidateVisual();
progressCounter++;
locList.Add(currentLocation);
}
return locList;
}
public Location GetSingleFormatForDB(Location location)
{
string address = location.Address + ", " + location.City;
var requestUri = string.Format("http://maps.googleapis.com/maps/api/geocode/xml?address={0}&sensor=false", Uri.EscapeDataString(address));
var request = WebRequest.Create(requestUri);
var response = request.GetResponse();
var xdoc = XDocument.Load(response.GetResponseStream());
try
{
var result = xdoc.Element("GeocodeResponse").Element("result");
var locationElement = result.Element("geometry").Element("location");
location.Latitude = (float)(locationElement.Element("lat"));
location.Longitude = (float)(locationElement.Element("lng"));
}
catch (Exception x)
{
}
return location;
}
public static void InsertLocationListToDB(Location location)
{
Service1Client wcf = new Service1Client();
try
{
wcf.ClientCredentials.UserName.UserName = "admin2";
wcf.ClientCredentials.UserName.Password = "123test123!";
wcf.AddLocationFromListAsync(
location.SubCategory,
location.Title,
location.InfoText,
location.Domain,
location.City,
location.Zipcode,
(float)location.Longitude,
(float)location.Latitude,
location.Telefon,
location.Mail,
location.Address
);
}
catch (Exception x)
{
}
}
private void upload_Click(object sender, RoutedEventArgs e)
{
if (locationList.Count > 0 || locationList != null)
{
dg1.Items.Clear();
foreach (Location l in locationList)
{
if (l.Latitude != 0 && l.Longitude != 0)
{
locationList.Remove(l);
}
dg1.Items.Add(l);
}
}
}
private void check_Click(object sender, RoutedEventArgs e)
{
locationList = FormatLocationForDB(locationList);
}
private void exit_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
}
}
I tried to manage the progressbarvalue in the thread but nothing happens at all. The value is still 0 when the programm is finished. Could someone help me? Is there an easy mistake? Or should i try somethink else like the backgroundworker (which looks pretty the same i think).
Thanks for help
private double _progressLabelContent;
public double ProgressLabelContent
{
get {return _progressLabelContent; }
set { _progressLabelContent=value; OnPropertyChanged("ProgressLabelContent"); }
}
public void updateProgressBar()
{
Application.Current.Dispatcher.Invoke(delegate
{
ProgressValue = ((double)progressCounter * 100) / locationList.Count;
ProgressLabelContent = ProgressValue + " / 100";
});
}
xaml
<Label Content={Binding Path=ProgressLabelContent} Foreground="White" TextBlock.TextAlignment="Center" Content="" HorizontalAlignment="Left" Margin="320,489,0,0" VerticalAlignment="Top" Width="100"/>
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?