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;
//...
}
Related
I have a WPF window that contains nothing but a named DataGrid.
<DataGrid x:Name="DGResultset"/>
I populate it with the contents of a DataTable that gets its own contents from the resultset of a SqlDataReader.
public DataDisplay( DataTable resultSet )
{
InitializeComponent();
DGResultset.ItemsSource = resultSet.DefaultView;
DGResultset.AutoGenerateColumns = true;
}
How can I change the default style of the headers?
You will need to do two things:
Create Styles for your DataGridColumnHeaders
Apply the Header Style while the columns are auto-generating using an 'AutoGeneratingColumn' event handler.
Here's a working example:
Example Output: ('FirstName' and 'LastName' headers look different from 'Age')
MainWindow.xaml
<Window x:Class="LabelListboxTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.Resources>
<Style x:Key="ColumnHeaderStyle1" TargetType="DataGridColumnHeader">
<Setter Property="Margin" Value="5"/>
<Setter Property="Height" Value="30"/>
<Setter Property="Background" Value="LightBlue"/>
<Setter Property="Foreground" Value="Black"/>
<Setter Property="FontSize" Value="18" />
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="CadetBlue"/>
</Trigger>
</Style.Triggers>
</Style>
<Style x:Key="ColumnHeaderStyle2" TargetType="DataGridColumnHeader">
<Setter Property="Margin" Value="5"/>
<Setter Property="Height" Value="30"/>
<Setter Property="Background" Value="DarkGreen"/>
<Setter Property="Foreground" Value="White"/>
<Setter Property="FontSize" Value="18" />
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="MediumVioletRed"/>
<Setter Property="Foreground" Value="Yellow"/>
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
<Grid>
<DataGrid x:Name="DGResultset" AutoGenerateColumns="True" AutoGeneratingColumn="DGResultset_AutoGeneratingColumn" />
</Grid>
</Window>
MainWindow.xaml.cs
using System.Data;
using System.Windows;
using System.Windows.Controls;
namespace LabelListboxTest
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.Loaded += MainWindow_Loaded;
}
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
var resultSet = GetDataset();
DGResultset.ItemsSource = resultSet.DefaultView;
}
private DataTable GetDataset()
{
DataTable dt = new DataTable("MyTable");
dt.Columns.Add("FirstName", typeof(string));
dt.Columns.Add("LastName", typeof(string));
dt.Columns.Add("Age", typeof(int));
for (int i = 0; i < 10; i++)
{
var row = dt.NewRow();
row["FirstName"] = "John";
row["LastName"] = "Doe";
row["Age"] = i;
dt.Rows.Add(row);
}
return dt;
}
private void DGResultset_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
if (e.PropertyName == "FirstName")
{
e.Column.HeaderStyle = (Style)Resources["ColumnHeaderStyle1"];
}
else if (e.PropertyName == "LastName")
{
e.Column.HeaderStyle = (Style)Resources["ColumnHeaderStyle1"];
}
else if (e.PropertyName == "Age")
{
e.Column.HeaderStyle = (Style)Resources["ColumnHeaderStyle2"];
}
}
}
}
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.
I'm populating a DataGrid with sorting and grouping in WPF and I want to implement a progress indicator to the user for them to know that the current query is still running in the background. I'm trying to use the ProgressRing of Mahapps but i don't know how do I implement it. Below is my code.
Code Behind
void InitSongs()
{
this.Dispatcher.Invoke((Action)(() => {
DataTable dtSong = new DataTable();
ICollection<Song> songList = new ObservableCollection<Song>();
using (SqlConnection conn = new SqlConnection(#"Server=.\MSSQL2008R2;Database=MVCDB;Trusted_Connection=True;"))
{
string sqlCmd = "SELECT TOP 1000 * FROM SongDb";
conn.Open();
using (SqlCommand cmd = new SqlCommand(sqlCmd, conn))
{
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = sqlCmd;
cmd.CommandTimeout = 120;
dtSong.Load(cmd.ExecuteReader());
}
}
for (int i = 0; i <= dtSong.Rows.Count - 1; i++)
{
songList.Add(new Song(Convert.ToInt32(dtSong.Rows[i][0]),
dtSong.Rows[i][1].ToString(),
dtSong.Rows[i][2].ToString(),
Convert.ToInt64(dtSong.Rows[i][3]),
dtSong.Rows[i][4].ToString(),
Convert.ToBoolean(dtSong.Rows[i][5])));
}
dgSongs.ItemsSource = songList;
ICollectionView view = CollectionViewSource.GetDefaultView(dgSongs.ItemsSource);
view.SortDescriptions.Add(new SortDescription("Artist", ListSortDirection.Ascending));
//view.SortDescriptions.Add(new SortDescription("Title", ListSortDirection.Ascending));
view.GroupDescriptions.Add(new PropertyGroupDescription("Artist"));
}));
}
private void btnGetSongs_Click(object sender, RoutedEventArgs e)
{
bw.WorkerReportsProgress = true;
bw.WorkerSupportsCancellation = true;
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
progress1.IsActive = true;
progress1.Visibility = System.Windows.Visibility.Visible;
bw.RunWorkerAsync();
}
void bw_DoWork(object sender, DoWorkEventArgs e)
{
InitSongs();
}
void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
progress1.IsActive = false;
progress1.Visibility = Visibility.Collapsed;
}
MainWindow.xaml
<Controls:MetroWindow x:Class="PalletTaggingWpf.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Controls="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
Title="Pallet Tagging" Height="500" Width="500" ShowIconOnTitleBar="True"
WindowStartupLocation="CenterScreen"
GlowBrush="{DynamicResource AccentColorBrush}"
BorderBrush="{DynamicResource AccentColorBrush}"
EnableDWMDropShadow="True"
BorderThickness="1">
<TabControl>
<TabItem Header="Songs">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<StackPanel>
<Button Name="btnGetSongs" Content="Get Songs" Click="btnGetSongs_Click"></Button>
</StackPanel>
<DataGrid Grid.Row="1" Name="dgSongs" ItemsSource="{Binding}">
<DataGrid.GroupStyle>
<GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Path=Name}" />
</StackPanel>
</DataTemplate>
</GroupStyle.HeaderTemplate>
<GroupStyle.ContainerStyle>
<Style TargetType="{x:Type GroupItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GroupItem}">
<Expander IsExpanded="True">
<Expander.Header>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=Name}" />
<TextBlock Text="{Binding Path=ItemCount}"/>
<TextBlock Text="Items"/>
</StackPanel>
</Expander.Header>
<ItemsPresenter />
</Expander>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</GroupStyle.ContainerStyle>
</GroupStyle>
</DataGrid.GroupStyle>
</DataGrid>
</Grid>
</TabItem>
</TabControl>
PS: I'm using VS2010 for this
XAML
<StackPanel>
<Button Name="btnGetSongs" Content="Get Songs" Click="btnGetSongs_Click"></Button>
<ProgressRing x:Name="progress1"/> <!-- Without MahApps -->
</StackPanel>
CS
this.Dispatcher.Invoke((Action)(() => {
progress1.IsActive = true;
progress1.Visibility = Visibility.Visible;
DataTable dtSong = new DataTable();
//All Steps will go as stated
view.GroupDescriptions.Add(new PropertyGroupDescription("Artist"));
progress1.IsActive = false;
progress1.Visibility = Visibility.Collapsed;
}));
MahApps
XAML
<StackPanel>
<Button Name="btnGetSongs" Content="Get Songs" Click="btnGetSongs_Click"></Button>
<Controls:ProgressRing IsActive="False" Visibility="Collapsed" Name="progress1" />
</StackPanel>
CS
this.Dispatcher.Invoke((Action)(() => {
progress1.IsActive = true;
progress1.Visibility = Visibility.Visible;
DataTable dtSong = new DataTable();
//All Steps will go as stated
view.GroupDescriptions.Add(new PropertyGroupDescription("Artist"));
progress1.IsActive = false;
progress1.Visibility = Visibility.Collapsed;
}));
Can I use a XAML file in a ASP.NET project. For example, when I open localhost/tryconnect.aspx, I want to see XAML file. Is it possible?
MainWindows.xaml code:
<Window x:Class="TFSMove.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="http://schemas.microsoft.com/netfx/2009/xaml/presentation"
x:Name="_MainWindow" Width="500" Height="450"
Title="Move TFS Work Items" >
<Window.Resources>
<local:AndConverter x:Key="AndConverter"/>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="350" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Grid Grid.Row="0" Grid.ColumnSpan="3" >
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Label Grid.Row="0" Grid.Column="0" HorizontalAlignment="Right" Margin="5" Content="TFS Server:"/>
<TextBox x:Name="_TFSServer" Grid.Row="0" Grid.Column="1" Margin="5" TextChanged="_TFSServer_TextChanged" >
<TextBox.Resources>
<VisualBrush x:Key="hint" TileMode="None" Opacity="0.4" Stretch="None" AlignmentX="Left">
<VisualBrush.Transform>
<TranslateTransform X="5" Y="0" />
</VisualBrush.Transform>
<VisualBrush.Visual>
<Grid>
<TextBox BorderThickness="0" FontStyle="Italic" Foreground="Black" Text="<Enter the URL to the TFS project server.>"/>
</Grid>
</VisualBrush.Visual>
</VisualBrush>
</TextBox.Resources>
<TextBox.Style>
<Style TargetType="TextBox">
<Style.Triggers>
<Trigger Property="Text" Value="{x:Null}">
<Setter Property="Background" Value="{StaticResource hint}" />
</Trigger>
<Trigger Property="Text" Value="">
<Setter Property="Background" Value="{StaticResource hint}" />
</Trigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
<Button x:Name="_BtnMove" Grid.Row="0" Grid.Column="2" Margin="5" Click="_BtnMoveClick" Content="¡Move!">
<Button.IsEnabled>
<MultiBinding Converter="{StaticResource AndConverter}" Mode="OneWay">
<Binding ElementName="_From_Project" Path="Text" Mode="OneWay"/>
<Binding ElementName="_To_Areas" Path="SelectedItem" Mode="OneWay"/>
<Binding ElementName="_To_Iterations" Path="SelectedItem" Mode="OneWay"/>
</MultiBinding>
</Button.IsEnabled>
</Button>
<Label Grid.Row="1" Grid.Column="0" HorizontalAlignment="Right" Margin="5" >SQL Connection:</Label>
<TextBox x:Name="_SQLConnection" Grid.Row="1" Grid.Column="1" MinWidth="100" Margin="5" >
<TextBox.Resources>
<VisualBrush x:Key="hint" TileMode="None" Opacity="0.4" Stretch="None" AlignmentX="Left">
<VisualBrush.Transform>
<TranslateTransform X="5" Y="0" />
</VisualBrush.Transform>
<VisualBrush.Visual>
<Grid>
<TextBox BorderThickness="0" FontStyle="Italic" Foreground="Black" Text="<Enter the SQL Connection String to the TFL Server SQL database.>"/>
</Grid>
</VisualBrush.Visual>
</VisualBrush>
</TextBox.Resources>
<TextBox.Style>
<Style TargetType="TextBox">
<Style.Triggers>
<Trigger Property="Text" Value="{x:Null}">
<Setter Property="Background" Value="{StaticResource hint}" />
</Trigger>
<Trigger Property="Text" Value="">
<Setter Property="Background" Value="{StaticResource hint}" />
</Trigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
<Button x:Name="_BtnSQL" Grid.Row="1" Grid.Column="2" Margin="5" Click="_BtnSQLTestClick" IsEnabled="{Binding ElementName=_SQLConnection, Path=Text.Length}" >¡Test!</Button>
<Label Grid.Row="2" Grid.Column="0" HorizontalAlignment="Right" Margin="5" >Query:</Label>
<TextBox x:Name="_WorkItemQuery" Grid.Row="2" Grid.Column="1" MinWidth="100" Margin="5" >
<TextBox.Resources>
<VisualBrush x:Key="hint" TileMode="None" Opacity="0.4" Stretch="None" AlignmentX="Left">
<VisualBrush.Transform>
<TranslateTransform X="5" Y="0" />
</VisualBrush.Transform>
<VisualBrush.Visual>
<Grid>
<TextBox BorderThickness="0" FontStyle="Italic" Foreground="Black" Text="<Enter the WorkItem Number or Query for moving.>"/>
</Grid>
</VisualBrush.Visual>
</VisualBrush>
</TextBox.Resources>
<TextBox.Style>
<Style TargetType="TextBox">
<Style.Triggers>
<Trigger Property="Text" Value="{x:Null}">
<Setter Property="Background" Value="{StaticResource hint}" />
</Trigger>
<Trigger Property="Text" Value="">
<Setter Property="Background" Value="{StaticResource hint}" />
</Trigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
<Button x:Name="_BtnQuery" Grid.Row="2" Grid.Column="2" Margin="5" Click="_BtnQueryClick" IsEnabled="{Binding ElementName=_WorkItemQuery, Path=Text.Length}">Search</Button>
</Grid>
<GridSplitter Grid.Column="1" Grid.Row="2" ShowsPreview="True" VerticalAlignment="Stretch" Width="6" HorizontalAlignment="Center" Margin="0,0,0,0" />
<RichTextBox x:Name="_WorkItemDisplay" Grid.Row="2" Grid.Column="0" Margin="5" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto">
<RichTextBox.Resources>
<Style TargetType="{x:Type Paragraph}">
<Setter Property="Margin" Value="0" />
</Style>
</RichTextBox.Resources>
</RichTextBox>
<Grid Grid.Row="1" Grid.Column="2">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition/>
</Grid.RowDefinitions>
<GroupBox Grid.Row="0" FontSize="16" Margin="5,0,5,5">
<GroupBox.Header>From</GroupBox.Header>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition />
</Grid.RowDefinitions>
<TextBlock x:Name="_From_Project" Grid.Row="0" Margin="5,0,5,0" TextWrapping="WrapWithOverflow" />
</Grid>
</GroupBox>
<Rectangle Grid.Row="1" Margin="1" SnapsToDevicePixels="True" Height="1" Width="Auto" Fill="Black" />
<GroupBox Grid.Row="2" FontSize="16" Margin="5,0,5,5">
<GroupBox.Header>To</GroupBox.Header>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition />
</Grid.RowDefinitions>
<Label Grid.Row="0" Margin="5,0,5,0" FontSize="{Binding ElementName=_BtnMove, Path=FontSize}" Content="Project:"/>
<ComboBox x:Name="_To_Projects" Grid.Row="1" Margin="5,0,5,5" FontSize="{Binding ElementName=_BtnMove, Path=FontSize}" SelectionChanged="_To_Projects_SelectionChanged" />
<Label Grid.Row="2" Margin="5,0,5,0" FontSize="{Binding ElementName=_BtnMove, Path=FontSize}" Content="Area:"/>
<ComboBox x:Name="_To_Areas" Grid.Row="3" Margin="5,0,5,5" FontSize="{Binding ElementName=_BtnMove, Path=FontSize}" SelectionChanged="UpdateMoveEnabled" />
<Label Grid.Row="4" Margin="5,0,5,0" FontSize="{Binding ElementName=_BtnMove, Path=FontSize}" Content="Iteration:"/>
<ComboBox x:Name="_To_Iterations" Grid.Row="5" Margin="5,0,5,5" FontSize="{Binding ElementName=_BtnMove, Path=FontSize}" SelectionChanged="UpdateMoveEnabled"/>
</Grid>
</GroupBox>
</Grid>
</Grid>
</Window>
MainWindow.xaml.cs code:
namespace TFSMove
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public static DependencyProperty MoveEnabledProperty = DependencyProperty.Register("MoveEnabled", typeof(bool), typeof(MainWindow), new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
public bool? MoveEnabled
{
get
{
return GetValue(MoveEnabledProperty) as bool?;
}
set { SetValue(MoveEnabledProperty, value); }
}
public static DependencyProperty TFS_ServerProperty = DependencyProperty.Register("TFS_Server", typeof(Uri), typeof(MainWindow), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
private Uri TFS_Server
{
get
{
return
GetValue(TFS_ServerProperty) as Uri;
}
set { SetValue(TFS_ServerProperty, value); }
}
public static DependencyProperty TFS_WorkItemsProperty = DependencyProperty.Register("TFS_WorkItems", typeof(WorkItemCollection), typeof(MainWindow), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
private WorkItemCollection TFS_WorkItems
{
get
{
return GetValue(TFS_WorkItemsProperty) as WorkItemCollection;
}
set { SetValue(TFS_WorkItemsProperty, value); }
}
private DispatcherTimer _tfs_server_text_changed_timer;
public MainWindow()
{
InitializeComponent();
_BtnQuery.IsEnabled = false;
}
private void _TFSServer_TextChanged(object sender, TextChangedEventArgs e)
{
if (_tfs_server_text_changed_timer == null)
{
_tfs_server_text_changed_timer = new DispatcherTimer();
_tfs_server_text_changed_timer.Tag = sender;
_tfs_server_text_changed_timer.Tick += _TFSServer_PostTextChanged;
}
_tfs_server_text_changed_timer.Interval = TimeSpan.FromMilliseconds(750);
_tfs_server_text_changed_timer.Start();
e.Handled = true;
}
private void _TFSServer_PostTextChanged(object sender, EventArgs e)
{
(sender as DispatcherTimer).Stop();
TextBox tb = (sender as DispatcherTimer).Tag as TextBox;
if (sender.Equals(_tfs_server_text_changed_timer))
{
_tfs_server_text_changed_timer.Tag = null;
_tfs_server_text_changed_timer = null;
}
TfsTeamProjectCollection TPC = null;
Uri tfs_server_ = null;
if (Uri.TryCreate(tb.Text, UriKind.Absolute, out tfs_server_))
{
TFS_Server = tfs_server_;
try
{
TPC = new TfsTeamProjectCollection(TFS_Server);
}
catch (Exception ex)
{
Paragraph p = new Paragraph(new Run(ex.InnerException == null ? ex.Message : ex.InnerException.Message));
p.Foreground = Brushes.Red;
_WorkItemDisplay.Document.Blocks.Add(p);
_BtnQuery.IsEnabled = false;
return;
}
}
else
TFS_Server = null;
if (TPC == null)
{
_WorkItemDisplay.AppendText(".");
_BtnQuery.IsEnabled = false;
return;
}
Cursor saved_cursor = this.Cursor;
this.Cursor = Cursors.Wait;
//!?this._To_Projects.SelectedValuePath = "Id";
this._To_Projects.DisplayMemberPath = "Name";
this._To_Projects.ItemsSource = TPC.GetService<WorkItemStore>().Projects;
_WorkItemDisplay.Document.Blocks.Add(new Paragraph(new Run("Connected to: " + tb.Text)));
_BtnQuery.IsEnabled = true;
this.Cursor = saved_cursor;
}
private void _To_Projects_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (_To_Projects.SelectedItem == null)
{
_To_Areas.ItemsSource = null;
_To_Iterations.ItemsSource = null;
}
else
{
Cursor saved_cursor = this.Cursor;
this.Cursor = Cursors.Wait;
//!?_To_Areas.SelectedValuePath = "Id";
_To_Areas.DisplayMemberPath = "Name";
_To_Areas.ItemsSource = (_To_Projects.SelectedItem as Project).AreaRootNodes;
//!?_To_Iterations.SelectedValuePath = "Id";
_To_Iterations.DisplayMemberPath = "Name";
_To_Iterations.ItemsSource = (_To_Projects.SelectedItem as Project).IterationRootNodes;
this.Cursor = saved_cursor;
}
}
private void _BtnQueryClick(object sender, RoutedEventArgs e)
{
StringBuilder wiquery = new StringBuilder(this._WorkItemQuery.Text);
int work_item_number = 0;
if (int.TryParse(this._WorkItemQuery.Text, out work_item_number))
{
wiquery.Clear();
wiquery.Append("SELECT * FROM WorkItems WHERE [System.Id] = '");
wiquery.Append(work_item_number.ToString());
wiquery.Append("'");
}
Cursor saved_cursor = this.Cursor;
this.Cursor = Cursors.Wait;
_WorkItemDisplay.Document.Blocks.Clear();
try
{
TfsTeamProjectCollection TPC = new TfsTeamProjectCollection(TFS_Server);
TPC.EnsureAuthenticated();
TFS_WorkItems = TPC.GetService<WorkItemStore>().Query(wiquery.ToString());
switch (TFS_WorkItems.Count)
{
case 0:
_WorkItemDisplay.Document.Blocks.Add(new Paragraph(new Run("No items were returned from search.")));
_From_Project.Text = string.Empty;
break;
case 1:
{
Table t = new Table();
GridLengthConverter lc = new GridLengthConverter();
t.Columns.Add(new TableColumn() { Width = (GridLength)lc.ConvertFromString("*") });
t.Columns.Add(new TableColumn() { Width = (GridLength)lc.ConvertFromString("3*") });
TableRowGroup rg = new TableRowGroup();
TableRow r = new TableRow();
r.Cells.Add(new TableCell(new Paragraph(new Run(TFS_WorkItems[0].Fields["ID"].Name))));
r.Cells.Add(new TableCell(new Paragraph(new Run(TFS_WorkItems[0].Fields["ID"].Value.ToString()))));
rg.Rows.Add(r);
r = new TableRow();
r.Cells.Add(new TableCell(new Paragraph(new Run(TFS_WorkItems[0].Fields["Title"].Name))));
r.Cells.Add(new TableCell(new Paragraph(new Run(TFS_WorkItems[0].Fields["Title"].Value.ToString()))));
rg.Rows.Add(r);
r = new TableRow();
r.Cells.Add(new TableCell(new Paragraph(new Run(TFS_WorkItems[0].Fields["Area Path"].Name))));
r.Cells.Add(new TableCell(new Paragraph(new Run(TFS_WorkItems[0].Fields["Area Path"].Value.ToString()))));
rg.Rows.Add(r);
r = new TableRow();
r.Cells.Add(new TableCell(new Paragraph(new Run(TFS_WorkItems[0].Fields["Iteration Path"].Name))));
r.Cells.Add(new TableCell(new Paragraph(new Run(TFS_WorkItems[0].Fields["Iteration Path"].Value.ToString()))));
rg.Rows.Add(r);
_From_Project.Text = TFS_WorkItems[0].Fields["Team Project"].Value.ToString();
foreach (Field f in TFS_WorkItems[0].Fields)
{
if (f.Value != null)
{
string value = f.Value.ToString();
if (!string.IsNullOrWhiteSpace(value))
{
r = new TableRow();
r.Cells.Add(new TableCell(new Paragraph(new Run(f.Name))));
r.Cells.Add(new TableCell(new Paragraph(new Run(value))));
rg.Rows.Add(r);
}
}
}
t.RowGroups.Add(rg);
_WorkItemDisplay.Document.Blocks.Add(t);
}
break;
default:
{
Table t = new Table();
GridLengthConverter lc = new GridLengthConverter();
t.Columns.Add(new TableColumn() { Width = (GridLength)lc.ConvertFromString("*") });
t.Columns.Add(new TableColumn() { Width = (GridLength)lc.ConvertFromString("7*") });
TableRowGroup rg = new TableRowGroup();
TableRow r = new TableRow();
r.Cells.Add(new TableCell(new Paragraph(new Run(TFS_WorkItems[0].Fields["ID"].Name)) { FontWeight = FontWeights.Bold }));
r.Cells.Add(new TableCell(new Paragraph(new Run(TFS_WorkItems[0].Fields["Title"].Name)) { FontWeight = FontWeights.Bold }));
rg.Rows.Add(r);
_From_Project.Text = TFS_WorkItems[0].Fields["Team Project"].Value.ToString();
foreach (WorkItem wi in TFS_WorkItems)
{
r = new TableRow();
r.Cells.Add(new TableCell(new Paragraph(new Run(wi.Fields["ID"].Value.ToString()))));
r.Cells.Add(new TableCell(new Paragraph(new Run(wi.Fields["Title"].Value.ToString()))));
rg.Rows.Add(r);
}
t.RowGroups.Add(rg);
_WorkItemDisplay.Document.Blocks.Add(t);
}
break;
}
}
catch (Exception ex)
{
_WorkItemDisplay.Document.Blocks.Add(new Paragraph(new Run(ex.InnerException == null ? ex.Message : ex.InnerException.Message)) { Foreground = Brushes.Red });
_From_Project.Text = string.Empty;
}
this.Cursor = saved_cursor;
}
private void _BtnMoveClick(object sender, RoutedEventArgs e)
{
Cursor saved_cursor = this.Cursor;
this.Cursor = Cursors.Wait;
_WorkItemDisplay.Document.Blocks.Clear();
_From_Project.Text = string.Empty;
SqlConnection conn = null;
try
{
conn = new SqlConnection(_SQLConnection.Text);
conn.Open();
if (TFS_WorkItems.Count == 0)
{
_WorkItemDisplay.Document.Blocks.Add(new Paragraph(new Run("Nothing to move.")) { Foreground = Brushes.Red });
}
else
{
TfsTeamProjectCollection TPC = new TfsTeamProjectCollection(TFS_Server);
TPC.EnsureAuthenticated();
WorkItemStore WIS = TPC.GetService<WorkItemStore>();
StringBuilder sql_command_are = new StringBuilder();
StringBuilder sql_command_latest = new StringBuilder();
StringBuilder sql_command_were = new StringBuilder();
foreach (WorkItem wi in TFS_WorkItems)
{
sql_command_are.Clear();
sql_command_latest.Clear();
sql_command_were.Clear();
sql_command_are.Append("UPDATE [WorkItemsAre] SET AreaID='");
sql_command_latest.Append("UPDATE [WorkItemsLatest] SET AreaID='");
sql_command_were.Append("UPDATE [WorkItemsWere] SET AreaID='");
sql_command_are.Append((_To_Areas.SelectedItem as Node).Id.ToString());
sql_command_latest.Append((_To_Areas.SelectedItem as Node).Id.ToString());
sql_command_were.Append((_To_Areas.SelectedItem as Node).Id.ToString());
sql_command_are.Append("', IterationID='");
sql_command_latest.Append("', IterationID='");
sql_command_were.Append("', IterationID='");
sql_command_are.Append((_To_Iterations.SelectedItem as Node).Id.ToString());
sql_command_latest.Append((_To_Iterations.SelectedItem as Node).Id.ToString());
sql_command_were.Append((_To_Iterations.SelectedItem as Node).Id.ToString());
sql_command_are.Append("' WHERE ID='");
sql_command_latest.Append("' WHERE ID='");
sql_command_were.Append("' WHERE ID='");
sql_command_are.Append(wi.Id.ToString());
sql_command_latest.Append(wi.Id.ToString());
sql_command_were.Append(wi.Id.ToString());
sql_command_are.Append("'");
sql_command_latest.Append("'");
sql_command_were.Append("'");
new SqlCommand(sql_command_are.ToString(), conn).ExecuteNonQuery();
new SqlCommand(sql_command_latest.ToString(), conn).ExecuteNonQuery();
new SqlCommand(sql_command_were.ToString(), conn).ExecuteNonQuery();
_WorkItemDisplay.Document.Blocks.Add(new Paragraph(new Run("Moved " + wi.Id.ToString() + " to " + (_To_Projects.SelectedItem as Project).Name)));
}
}
}
catch (Exception ex)
{
_WorkItemDisplay.Document.Blocks.Add(new Paragraph(new Run(ex.InnerException == null ? ex.Message : ex.InnerException.Message)) { Foreground = Brushes.Red });
_From_Project.Text = string.Empty;
}
finally
{
if (conn != null)
conn.Close();
}
this.Cursor = saved_cursor;
}
private void UpdateMoveEnabled(object sender, SelectionChangedEventArgs e)
{
BindingOperations.GetMultiBindingExpression(_BtnMove, Button.IsEnabledProperty).UpdateTarget();
}
private void _BtnSQLTestClick(object sender, RoutedEventArgs e)
{
Cursor saved_cursor = this.Cursor;
this.Cursor = Cursors.Wait;
_WorkItemDisplay.Document.Blocks.Clear();
try
{
SqlConnection conn = new SqlConnection(_SQLConnection.Text);
conn.Open();
SqlCommand sql_cmd = new SqlCommand("SELECT COUNT(*) FROM [WorkItemsAre]", conn);
int wi_count = (int)sql_cmd.ExecuteScalar();
conn.Close();
_WorkItemDisplay.Document.Blocks.Add(new Paragraph(new Run("Success! " + wi_count.ToString() + " work items counted.")));
}
catch (Exception ex)
{
_WorkItemDisplay.Document.Blocks.Add(new Paragraph(new Run(ex.InnerException == null ? ex.Message : ex.InnerException.Message)) { Foreground = Brushes.Red });
}
this.Cursor = saved_cursor;
}
}
public class AndConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parm, System.Globalization.CultureInfo culture)
{
switch (targetType.Name)
{
case "Boolean":
case "Nullable`1":
{
for (int i = 0; i < values.Count(); i++)
{
if (values[i] == null)
return false;
switch (values[i].GetType().Name)
{
case "Boolean":
case "Nullable`1":
if (values[i] as bool? ?? false)
continue;
return false;
case "String":
case "string":
if (string.IsNullOrWhiteSpace(values[i] as string))
return false;
else if ("0".CompareTo(values[i] as string) == 0 || "false".CompareTo((values[i] as string).ToLower()) == 0)
return false;
break;
case "Node":
if ((values[i] as Node).Id > 0)
continue;
return false;
default:
throw new NotImplementedException("Cannot process input type " + values[i].GetType().Name);
}
}
return true;
}
default:
throw new NotImplementedException("Cannot process output type " + targetType.Name);
}
}
public object[] ConvertBack(object value, Type[] targetTypes, object parm, System.Globalization.CultureInfo culture)
{
object[] ret = new object[targetTypes.Count()];
for (int i = 0; i < targetTypes.Count(); i++)
ret[i] = System.Convert.ChangeType(value, targetTypes[i]);
return ret;
}
}
}
You can use XAML in Silverlight
Questions on stackoverflow about silverlight: https://stackoverflow.com/search?q=siverlight
The structure is equals to WPF but some features are different between they
If you want to run native WPF applications you would need to consider creating a XBAP application like Glen said. Note that XBAP application support in modern day browsers is rare to find today and can be limited.
If you want to use XAML controls/files in your ASP.NET website, you will need to write a Silverlight application first, and then add the control to your website. Note that some browsers are even discontinuing support for Silverlight applications
Reference materials
The best way to use XAML in a web application is to use Silverlight. Using Silverlight is not a great idea for any project at this point.
Extended support for Silverlight ends 10/12/2021, which makes it seem like Silverlight should be around for ahwile, right? Wrong. In order to run a Silverlight application on the web, you'll need a browser that supports it. Chrome won't support Silverlight after September. Firefox is making users jump through hoops if they want to run the Silverlight plugin. And under Windows 10, the user has to be running IE11, Edge won't run Silverlight apps.
XAML on the web is dead.
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?