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.
Related
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 a textbox ACLBox that I want to display a string upon initialization of the user interface. Upon initializing, the string flashes for a second then disappears. Why?
Here's the xaml code for the textbox:
<Window x:Class="Funnel.ACL"
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:Funnel"
mc:Ignorable="d"
Title="ACL Configuration" Height="300" Width="560" WindowStartupLocation="CenterScreen"
Closing="exitACL"
Background="LightGray" Name="ACLConfiguration">
<Grid>
<DockPanel>
<Grid x:Name="FunnelGrid" DockPanel.Dock="Top" ShowGridLines="False">
<!--Defining Grid-->
<Grid.ColumnDefinitions>
<ColumnDefinition Width="130"/>
<ColumnDefinition Width="40"/>
<ColumnDefinition Width="40"/>
<ColumnDefinition Width="40"/>
<ColumnDefinition Width="40"/>
<ColumnDefinition Width="30"/>
<ColumnDefinition Width="70"/>
<ColumnDefinition Width="75"/>
<ColumnDefinition Width="75"/>
<ColumnDefinition Width="75"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Label x:Name="Config"
Content="ACL CONFIGURATION"
Grid.Row="0"
Grid.Column="0"
Grid.ColumnSpan="9"
HorizontalAlignment="Center"
Foreground="Blue"
FontWeight="Heavy"
FontSize="16">
</Label>
<CheckBox x:Name="aclCheckbox"
FlowDirection="RightToLeft"
Content="ACL ON"
Foreground="Blue"
FontWeight="Heavy"
FontSize="16"
Grid.Row="1"
Grid.Column="0"
Grid.RowSpan="1"
Grid.ColumnSpan="5"
HorizontalAlignment="Center"
Checked="ACL_Check"
Unchecked="ACL_Unchecked"
/>
<Label x:Name="AddIPAddress" Content="Add IP Address" Grid.Row="2" Grid.Column="0" Width="90" Height="30"></Label>
<TextBox x:Name="AddIPTextBox1" Grid.Row="2" Grid.Column="1" Width="35" Height="20" TextChanged="AddIPTextBox1_TextChanged"></TextBox>
<TextBox x:Name="AddIPTextBox2" Grid.Row="2" Grid.Column="2" Width="35" Height="20" TextChanged="AddIPTextBox2_TextChanged"></TextBox>
<TextBox x:Name="AddIPTextBox3" Grid.Row="2" Grid.Column="3" Width="35" Height="20" TextChanged="AddIPTextBox3_TextChanged"></TextBox>
<TextBox x:Name="AddIPTextBox4" Grid.Row="2" Grid.Column="4" Width="35" Height="20" TextChanged="AddIPTextBox4_TextChanged"></TextBox>
<TextBox x:Name="AddErrorBox" Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="2" HorizontalAlignment="Right" BorderThickness="0" Background="LightGray" FontSize="10" Text="{Binding AddErrorText}"/>
<Button x:Name="AddButton" Grid.Row="3" Grid.Column="1" Grid.ColumnSpan="4" HorizontalAlignment="Center" Height="25" Width="50" Click="addClick" FontSize="12" FontWeight="ExtraBold" Background="LightSteelBlue" VerticalAlignment="Top">ADD</Button>
<Label x:Name="DelIPAddress" Content="Remove IP Address" Grid.Row="4" Grid.Column="0" Width="120" Height="30"></Label>
<TextBox x:Name="DeleteIPTextBox1" Grid.Row="4" Grid.Column="1" Width="35" Height="20" TextChanged="DeleteIPTextBox1_TextChanged"></TextBox>
<TextBox x:Name="DeleteIPTextBox2" Grid.Row="4" Grid.Column="2" Width="35" Height="20" TextChanged="DeleteIPTextBox2_TextChanged"></TextBox>
<TextBox x:Name="DeleteIPTextBox3" Grid.Row="4" Grid.Column="3" Width="35" Height="20" TextChanged="DeleteIPTextBox3_TextChanged"></TextBox>
<TextBox x:Name="DeleteIPTextBox4" Grid.Row="4" Grid.Column="4" Width="35" Height="20" TextChanged="DeleteIPTextBox4_TextChanged"></TextBox>
<TextBox x:Name="DelErrorBox" Grid.Row="5" Grid.Column="0" Grid.ColumnSpan="2" HorizontalAlignment="Right" BorderThickness="0" Background="LightGray" FontSize="10" Text="{Binding DelErrorText}"/>
<Button x:Name="DeleteButton" Grid.Row="5" Grid.Column="1" Grid.ColumnSpan="4" HorizontalAlignment="Center" Height="25" Width="50" Click="deleteClick" FontSize="12" FontWeight="ExtraBold" Background="LightSteelBlue" VerticalAlignment="Top">DELETE</Button>
<Button x:Name="DeleteAllButton" Grid.Row="6" Grid.Column="1" Grid.ColumnSpan="4" HorizontalAlignment="Center" Height="25" Width="80" Click="deleteAllClick" FontSize="12" FontWeight="ExtraBold" Background="LightSteelBlue" VerticalAlignment="Top">REMOVE ALL</Button>
<Label x:Name="ACLBoxLabel" Content="Access Control List" Foreground="Blue" Grid.Row="1" Grid.Column="6" Grid.ColumnSpan="3" HorizontalAlignment="Center"></Label>
<TextBox x:Name="ACLBox"
ScrollViewer.HorizontalScrollBarVisibility="Auto"
ScrollViewer.VerticalScrollBarVisibility="Auto"
ScrollViewer.CanContentScroll="True"
Grid.Row="2"
Grid.Column="6"
Grid.RowSpan="4"
Grid.ColumnSpan="4"
HorizontalAlignment="Left"
VerticalAlignment="Center"
Width="220"
Height="150"
FontSize="14"
IsReadOnly="True"
Text="{Binding ACLBoxText}"
TextWrapping="Wrap"
TextAlignment="Center" />
</Grid>
</DockPanel>
</Grid>
Here's the C# code for the string:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace Funnel
{
/// <summary>
/// Interaction logic for ACL.xaml
/// </summary>
public partial class ACL : Window
{
AclManager _manage = new AclManager();
FileController _controller = new FileController();
string addStr1;
string addStr2;
string addStr3;
string addStr4;
bool addError;
string delStr1;
string delStr2;
string delStr3;
string delStr4;
bool delError;
public string aclText;
public event PropertyChangedEventHandler PropertyChanged;
public ACL()
{
InitializeComponent();
if(FunnelGlobals.accessControlList)
{
aclCheckbox.IsChecked = true;
}
aclText = _manage.getAclList();
}
private void exitACL(object sender,System.ComponentModel.CancelEventArgs e)
{
_controller.writeAclFile();
}
private void ACL_Check(object sender, RoutedEventArgs e)
{
FunnelGlobals.accessControlList = true;
aclText = _manage.getAclList();
}
private void ACL_Unchecked(object sender, RoutedEventArgs e)
{
FunnelGlobals.accessControlList = false;
aclText = _manage.getAclList();
}
private void AddIPTextBox1_TextChanged(object sender, TextChangedEventArgs e)
{
AddErrorBox.Text = "";
AddIPTextBox1.Text = AddIPTextBox1.Text;
addStr1 = AddIPTextBox1.Text;
if(!_manage.isDigit(addStr1))
{
Color foreColor = (Color)new ColorConverter().ConvertFrom("red");
Brush errBrush = new SolidColorBrush(foreColor);
AddErrorBox.Foreground = errBrush;
AddErrorBox.Text = "Character NOT Valid";
addError = true;
}
else
{
addError = false;
}
ACLBox.Text = _manage.getAclList();
}
private void AddIPTextBox2_TextChanged(object sender, TextChangedEventArgs e)
{
AddErrorBox.Text = "";
AddIPTextBox2.Text = AddIPTextBox2.Text;
addStr2 = AddIPTextBox2.Text;
if (!_manage.isDigit(addStr2))
{
Color foreColor = (Color)new ColorConverter().ConvertFrom("red");
Brush errBrush = new SolidColorBrush(foreColor);
AddErrorBox.Foreground = errBrush;
AddErrorBox.Text = "Character NOT Valid";
}
aclText = _manage.getAclList();
}
private void AddIPTextBox3_TextChanged(object sender, TextChangedEventArgs e)
{
AddErrorBox.Text = "";
AddIPTextBox3.Text = AddIPTextBox3.Text;
addStr3 = AddIPTextBox3.Text;
if (!_manage.isDigit(addStr3))
{
Color foreColor = (Color)new ColorConverter().ConvertFrom("red");
Brush errBrush = new SolidColorBrush(foreColor);
AddErrorBox.Foreground = errBrush;
AddErrorBox.Text = "Character NOT Valid";
}
aclText = _manage.getAclList();
}
private void AddIPTextBox4_TextChanged(object sender, TextChangedEventArgs e)
{
AddErrorBox.Text = "";
AddIPTextBox4.Text = AddIPTextBox4.Text;
addStr4 = AddIPTextBox4.Text;
if (!_manage.isDigit(addStr4))
{
Color foreColor = (Color)new ColorConverter().ConvertFrom("red");
Brush errBrush = new SolidColorBrush(foreColor);
AddErrorBox.Foreground = errBrush;
AddErrorBox.Text = "Character NOT Valid";
}
aclText = _manage.getAclList();
}
private void addClick(object sender, RoutedEventArgs e)
{
String addStr = addStr1 + "." + addStr2 + "." + addStr3 + "." + addStr4;
if(_manage.isLegit(addStr))
{
FunnelGlobals.aclIPs.Add(addStr);
}
if(addError)
{
Color foreColor = (Color)new ColorConverter().ConvertFrom("red");
Brush errBrush = new SolidColorBrush(foreColor);
AddErrorBox.Foreground = errBrush;
AddErrorBox.Text = "Fix Invalid Characters before Adding";
}
else
{
aclText = _manage.getAclList();
}
}
private void DeleteIPTextBox1_TextChanged(object sender, TextChangedEventArgs e)
{
DelErrorBox.Text = "";
DeleteIPTextBox1.Text = DeleteIPTextBox1.Text;
delStr1 = DeleteIPTextBox1.Text;
if (!_manage.isDigit(delStr1))
{
Color foreColor = (Color)new ColorConverter().ConvertFrom("red");
Brush errBrush = new SolidColorBrush(foreColor);
DelErrorBox.Foreground = errBrush;
DelErrorBox.Text = "Character NOT Valid";
delError = true;
}
else
{
delError = false;
}
}
private void DeleteIPTextBox2_TextChanged(object sender, TextChangedEventArgs e)
{
DelErrorBox.Text = "";
DeleteIPTextBox2.Text = DeleteIPTextBox2.Text;
delStr2 = DeleteIPTextBox2.Text;
if (!_manage.isDigit(delStr2))
{
Color foreColor = (Color)new ColorConverter().ConvertFrom("red");
Brush errBrush = new SolidColorBrush(foreColor);
DelErrorBox.Foreground = errBrush;
DelErrorBox.Text = "Character NOT Valid";
delError = true;
}
else
{
delError = false;
}
}
private void DeleteIPTextBox3_TextChanged(object sender, TextChangedEventArgs e)
{
DelErrorBox.Text = "";
DeleteIPTextBox3.Text = DeleteIPTextBox3.Text;
delStr3 = DeleteIPTextBox3.Text;
if (!_manage.isDigit(delStr3))
{
Color foreColor = (Color)new ColorConverter().ConvertFrom("red");
Brush errBrush = new SolidColorBrush(foreColor);
DelErrorBox.Foreground = errBrush;
DelErrorBox.Text = "Character NOT Valid";
delError = true;
}
else
{
delError = false;
}
}
private void DeleteIPTextBox4_TextChanged(object sender, TextChangedEventArgs e)
{
DelErrorBox.Text = "";
DeleteIPTextBox4.Text = DeleteIPTextBox4.Text;
delStr4 = DeleteIPTextBox4.Text;
if (!_manage.isDigit(delStr4))
{
Color foreColor = (Color)new ColorConverter().ConvertFrom("red");
Brush errBrush = new SolidColorBrush(foreColor);
DelErrorBox.Foreground = errBrush;
DelErrorBox.Text = "Character NOT Valid";
delError = true;
}
else
{
delError = false;
}
}
private void deleteClick(object sender, RoutedEventArgs e)
{
String delStr = delStr1 + "." + delStr2 + "." + delStr3 + "." + delStr4;
FunnelGlobals.aclIPs.Remove(delStr);
if (delError)
{
Color foreColor = (Color)new ColorConverter().ConvertFrom("red");
Brush errBrush = new SolidColorBrush(foreColor);
DelErrorBox.Foreground = errBrush;
DelErrorBox.Text = "Fix Invalid Characters before Removing";
}
else
{
aclText = _manage.getAclList();
}
}
private void deleteAllClick(object sender, RoutedEventArgs e)
{
FunnelGlobals.aclIPs.Clear();
aclText = _manage.getAclList();
}
private void ACLBox_Loaded(object sender, RoutedEventArgs e)
{
ACLBox.Text = _manage.getAclList();
}
public string ACLBoxText
{
get { return aclText; }
set { aclText = value; OnNotifyPropertyChanged("ACLBoxText"); }
}
private void OnNotifyPropertyChanged(string v)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(v));
throw new NotImplementedException();
}
}
}
Upon initializing, the string flashes for a second then disappears. Why?
Probably because you are "overwriting" the value of the ACLBoxText source property, which is initially displayed in the TextBlock, when you set the Text property of the TextBlock in your Loaded event handler.
If the TextBlock is empty once the UI has been loaded you should make sure that the _manage.getAclList() method returns the string that you expect it to return. You could temporarily try to assign the Text property to a "static" value:
private void ACLBox_Loaded(object sender, RoutedEventArgs e)
{
ACLBox.Text = "TEXT";
}
But I agree that it doesn't make much sense to first bind the Text property of the TextBlock to a source property in the XAML markup and then handle the Loaded event of the same TextBlock and set its Text property to a new value in this event handler. But I guess you have your reasons...
Note that binding that you define in the XAML markup will get reset when you programmatically set the Text property in your Loaded handler though.
So you should either don't bind the Text property in the XAML markup, or don't handle the Loaded event and set the Text property programmatically. It's one or the other but not both.
I figured out the problem. This is my first C# project and first time ever using Xaml (wpf) so I misunderstood binding. I bound the text like I did in the primary gui. The text is never getting triggered within this gui so I could only see the text flash because of loaded but then the text binding reset the textbox to nothing. When I changed my text to not be bound then everything works as I wanted. Lesson learned. Binding is only needed when accessing a textbox from within .cs files. It is not needed within xaml.cs. Since my text would only ever be triggered by xaml.cs just setting text the usual way(ie textbox.text = "whatever") does what I need. Thank you everyone for your help. I understand binding much, much better now. Java does things differently. :)
As Ed Plunkett has already mentioned, you should use your ACLBoxText backing variable instead of resetting the control value.
Something like this will work:
private void ACLBox_Loaded(object sender, RoutedEventArgs e)
{
ACLBoxText = _manage.getAclList();
}
Unfortunately, the view doesn't know about changes to backing properties unless you tell it that something changed. You need to implement INotifyPropertyChanged:
private string _aclBoxText;
public string ACLBoxText {
get { return _aclBoxText; }
set {
_aclBoxText = value;
OnNotifyPropertyChanged("ACLBoxText");
}
}
protected void OnNotifyPropertyChanged(string name)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(name));
}
public event PropertyChangedEventHandler PropertyChanged;
I have a wpf application and I want to be able to delete a column from a grid and then have the other columns repositioned themselves (i.e. if the users deletes the first column all other columns move one to the left, if the user deletes the second column all other columns after the second one moves to the left) by the event of clicking a button. Currently I am only able to hide the items in the column, it leaves a white space which I don't want.
private void SetColumnWidthCol1()
{
Col2.Width = new GridLength(150);
Col3.Width = new GridLength(150);
Col4.Width = new GridLength(150);
}
private void SetColumnWidthCol2()
{
Col1.Width = new GridLength(150);
Col3.Width = new GridLength(150);
Col4.Width = new GridLength(150);
}
private void SetColumnWidthCol3()
{
Col1.Width = new GridLength(150);
Col2.Width = new GridLength(150);
Col4.Width = new GridLength(150);
}
private void SetColumnWidthCol4()
{
Col1.Width = new GridLength(150);
Col2.Width = new GridLength(150);
Col3.Width = new GridLength(150);
Col5.Width = new GridLength(150);
Col6.Width = new GridLength(150);
}
private void SetColumnWidthCol5()
{
Col1.Width = new GridLength(150);
Col2.Width = new GridLength(150);
Col3.Width = new GridLength(150);
Col4.Width = new GridLength(150);
Col6.Width = new GridLength(150);
}
private void SetColumnWidthCol6()
{
Col1.Width = new GridLength(150);
Col2.Width = new GridLength(150);
Col3.Width = new GridLength(150);
Col4.Width = new GridLength(150);
Col5.Width = new GridLength(150);
}
private void CloseRock_Click(object sender, RoutedEventArgs e)
{
RockLabel.Visibility = System.Windows.Visibility.Hidden;
CloseRock.Visibility = System.Windows.Visibility.Hidden;
}
private void CloseContacts_Click(object sender, RoutedEventArgs e)
{
ContactsLabel.Visibility = System.Windows.Visibility.Hidden;
CloseContacts.Visibility = System.Windows.Visibility.Hidden;
}
private void CloseFluid_Click(object sender, RoutedEventArgs e)
{
FluidLabel.Visibility = System.Windows.Visibility.Hidden;
CloseFluid.Visibility = System.Windows.Visibility.Hidden;
}
private void CloseRegions_Click(object sender, RoutedEventArgs e)
{
RegionsLabel.Visibility = System.Windows.Visibility.Hidden;
CloseRegions.Visibility = System.Windows.Visibility.Hidden;
}
private void CloseProbabilities_Click(object sender, RoutedEventArgs e)
{
ProbabilitiesLabel.Visibility = System.Windows.Visibility.Hidden;
CloseProbabilities.Visibility = System.Windows.Visibility.Hidden;
}
private void CloseEconomics_Click(object sender, RoutedEventArgs e)
{
EconomicsLabel.Visibility = System.Windows.Visibility.Hidden;
CloseEconomics.Visibility = System.Windows.Visibility.Hidden;
}
}
XAML
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:syncfusion="http://schemas.syncfusion.com/wpf"
x:Class="ItemWrapPanel.MainWindow"
Title="MainWindow" Height="350" Width="1000">
<Window.Resources>
<LinearGradientBrush x:Key="LabelBackground" StartPoint="0,0" EndPoint="0,1">
<GradientStop Color="#FFEFEEEE" Offset="0"/>
<GradientStop Color="#E7E7E7E7" Offset="1"/>
</LinearGradientBrush>
<LinearGradientBrush x:Key="selectedHeaderBackground" StartPoint="0,0" EndPoint="0,1">
<GradientStop Color="#F6CD1D" Offset="0"/>
<GradientStop Color="#EBA32A" Offset="1"/>
</LinearGradientBrush>
</Window.Resources>
<Grid x:Name="MainGrid">
<Grid.RowDefinitions>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition x:Name="Col1"/>
<ColumnDefinition x:Name="Col2"/>
<ColumnDefinition x:Name="Col3"/>
<ColumnDefinition x:Name="Col4"/>
<ColumnDefinition x:Name="Col5"/>
<ColumnDefinition x:Name="Col6"/>
</Grid.ColumnDefinitions>
<Label x:Name="RockLabel"
Background="{StaticResource LabelBackground}"
Content="Rock Properties"
Grid.Row="0"
Grid.Column="0"
MouseUp="RockLabel_MouseDoubleClick"
VerticalAlignment="Top"/>
<Label x:Name="ContactsLabel"
Content="Contacts"
Background="{StaticResource LabelBackground}"
Grid.Column="1"
Grid.Row="0"
MouseUp="ContactsLabel_MouseDoubleClick"
VerticalAlignment="Top"/>
<Label x:Name="FluidLabel"
Content="Fluid Properties"
Background="{StaticResource LabelBackground}"
Grid.Column="2"
Grid.Row="0"
MouseUp="FluidLabel_MouseDoubleClick"
VerticalAlignment="Top"/>
<Label x:Name="RegionsLabel"
Content="Regions"
Background="{StaticResource LabelBackground}"
Grid.Column="3"
Grid.Row="0"
MouseUp="RegionsLabel_MouseDoubleClick"
VerticalAlignment="Top"/>
<Label x:Name="ProbabilitiesLabel"
Content="Probabilities"
Background="{StaticResource LabelBackground}"
Grid.Column="4"
Grid.Row="0"
MouseUp="ProbabiltitesLabel_MouseDoubleClick"
VerticalAlignment="Top"/>
<Label x:Name="EconomicsLabel"
Content="Economics"
Background="{StaticResource LabelBackground}"
Grid.Column="5"
Grid.Row="0"
MouseUp="EconomicsLabel_MouseDoubleClick"
VerticalAlignment="Top"/>
<Button x:Name="Resetbtn" Content="Restore" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Click="Reset_Click" Margin="0,59,0,0"/>
<Button Name="CloseRock" Content="X" HorizontalAlignment="Right" Margin="0,2,0,0" VerticalAlignment="Top" Width="24" Grid.Column="0" Grid.Row="0" Click="CloseRock_Click"/>
<Button Name="CloseContacts" Content="X" HorizontalAlignment="Right" Margin="0,2,2,0" VerticalAlignment="Top" Width="24" Grid.Column="1" Grid.Row="0" Click="CloseContacts_Click"/>
<Button Name="CloseFluid" Content="X" HorizontalAlignment="Right" Margin="0,2,2,0" VerticalAlignment="Top" Width="24" Grid.Column="2" Grid.Row="0" Click="CloseFluid_Click"/>
<Button Name="CloseRegions" Content="X" HorizontalAlignment="Right" Margin="0,2,1,0" VerticalAlignment="Top" Width="24" Grid.Column="3" Grid.Row="0" Click="CloseRegions_Click"/>
<Button Name="CloseProbabilities" Content="X" HorizontalAlignment="Right" Margin="0,2,1,0" VerticalAlignment="Top" Width="24" Grid.Column="4" Grid.Row="0" Click="CloseProbabilities_Click"/>
<Button Name="CloseEconomics" Content="X" HorizontalAlignment="Right" Margin="0,2,1,0" VerticalAlignment="Top" Width="24" Grid.Column="5" Grid.Row="0" Click="CloseEconomics_Click"/>
</Grid>
Instead of Visibility.Hidden make them Visibility.Collapsed.
Like -
private void CloseContacts_Click(object sender, RoutedEventArgs e)
{
ContactsLabel.Visibility = System.Windows.Visibility.Collapsed;
CloseContacts.Visibility = System.Windows.Visibility.Collapsed;
}
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;
}));
After user get the end of longlistselector ItemRealized event fires items add successfully. But the button's tag is empty (for added items), for items that I got first time button's tag isn't null.
This is my xaml DataTemplate:
<DataTemplate x:Key="TitleSongDataTemplate" x:Name="Titledata">
<Border Background="{StaticResource PhoneForegroundBrush}" Margin="0,0,12,12">
<Grid x:Name="GridOfButtons" Background="{StaticResource PhoneForegroundBrush}" >
<Grid Margin="0, -6, -7, 0"
HorizontalAlignment="Right"
VerticalAlignment="Top" Height="81" Width="83">
<Button
Content=""
FontFamily="Segoe UI Symbol"
Style="{StaticResource RoundButton}"
x:Name="AddToMySongsButton"
Tag="{Binding Song}"
Background="{StaticResource PhoneBackgroundBrush}"
Click="AddToMySongsButton_Click"/>
</Grid>
<Grid
VerticalAlignment="Top"
HorizontalAlignment="Left"
Margin="-17,-6,0,0" Height="81" Width="95">
<Button FontFamily="Segoe UI Symbol"
Content=""
Style="{StaticResource RoundButton}" Margin="10,0,0,0"
x:Name="PlayButton"
Background="{StaticResource PhoneBackgroundBrush}"
Tag="{Binding Song}"
Click="PlayButton_Click"/>
</Grid>
<Grid
HorizontalAlignment="Center"
VerticalAlignment="Top"
Margin="69,-7,60,0" Height="82" Width="84">
<Button Style="{StaticResource RoundButton}"
Content=""
FontFamily="Segoe UI Symbol"
x:Name="DownloadButton"
Margin="-5,0,0,0"
Background="{StaticResource PhoneBackgroundBrush}"
Tag="{Binding Song}"
Click="DownloadButton_Click"/>
</Grid>
<StackPanel VerticalAlignment="Bottom">
<TextBlock Text="{Binding Title}" Foreground="{StaticResource PhoneBackgroundBrush}" Margin="6 , 4, 6, 4"/>
<TextBlock Text="{Binding Artist}" Foreground="Gray" Opacity="0.75" Margin="6, 0, 0, 6"/>
</StackPanel>
</Grid>
</Border>
</DataTemplate>
My pivot:
<phone:Pivot x:Name="MainTitle">
<phone:PivotItem Header="Rock">
<Grid>
<phone:LongListSelector x:Name="RockLongList"
GridCellSize="220,150"
LayoutMode="Grid"
ItemTemplate="{StaticResource TitleSongDataTemplate}"
ItemRealized="RockLongList_ItemRealized"/>
<TextBlock x:Name="RockText"
Text="Загрузка..."
FontSize="60"
Opacity="0.5"
Style="{StaticResource LongListSelectorGroupHeaderLetterTileStyle}"
Margin="0,10,10,10"
TextWrapping="Wrap"
HorizontalAlignment="Right"
Width="436"/>
</Grid>
</phone:PivotItem>
Here my infinity scrooling realization:
1.I fired ItemRealized
private void RockLongList_ItemRealized(object sender, ItemRealizationEventArgs e)
{
var nownum = offset + 50;
if (nownum >= usercount)
{
MainTitle.Title = "All songs've downloaded";
}
else
{
SpecialSongs.SongJSON song = e.Container.Content as SpecialSongs.SongJSON;
if (song != null)
{
int myoffset = 2;
// Only if there is no data that is currently getting loaded would be initiate the loading again
if (!isCurrentlyLoading && defaultBindList.Count - defaultBindList.IndexOf(song) <= myoffset)
{
LoadDataFromSource();
}
}
}
}
And finally:
private void LoadDataFromSource()
{
this.Dispatcher.BeginInvoke(() =>
{
MainTitle.Title = "Downloading test...";
});
//progressBar.IsVisible = true;
isCurrentlyLoading = true;
string UsersUri = string.Format("https://api.vk.com/method/audio.get?&count=50&access_token={0}&user_id={1}&version=4.92&offset={2}", AccessToken, uID, offset);
//var query = string.Format(datasourceUrl, currentPage);
WebClient client = new WebClient();
client.DownloadStringCompleted += client_DownloadStringCompleted;
client.DownloadStringAsync(new Uri(UsersUri));
}
private void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
//Here handle exception
using (var reader = new MemoryStream(Encoding.Unicode.GetBytes(e.Result)))
{
SpecialSongs songs = JsonConvert.DeserializeObject<SpecialSongs>(e.Result);
this.Dispatcher.BeginInvoke(() =>
{
foreach (var tracks in songs.songs)
{
rockBindList.Add(tracks);
MainTitle.Title = "Downloaded test...";
}
RockLongList.ItemsSource = rockBindList;
isCurrentlyLoading = false;
//progressBar.IsVisible = false;
});
}
offset += 50;
}
This code shows why i need button's tag property:
private void DownloadButton_Click(object sender, RoutedEventArgs e)
{
try
{
SpecialSongs.SongJSON songdgd = (SpecialSongs.SongJSON)(sender as Button).Tag;
this.Download.Message = songdgd.Artist + "\n" + songdgd.Title;
string StringToSave = "shared/transfers/" + songdgd.Artist + songdgd.Title;
var linktosave = StringToSave.Replace(" ", "");
transferRequest = new BackgroundTransferRequest(new Uri(songdgd.URI, UriKind.RelativeOrAbsolute)) { Method = "GET" };
var uri = new Uri(linktosave, UriKind.Relative);
songdgd.URI = linktosave.Replace("shared/transfers/", "");
var json = JsonConvert.SerializeObject(songdgd);
var name = linktosave.Replace("shared/transfers/", "");
transferRequest.Tag = "json" + json + "json" + "uri" + name + "uri";
transferRequest.TransferPreferences = TransferPreferences.AllowCellularAndBattery;
transferRequest.DownloadLocation = uri;
try
{
BackgroundTransferService.Add(transferRequest);
}
catch
{
MessageBox.Show("Эта песня уже загружается.");
}
}
catch { MessageBox.Show("Error while downloading"); }
}
Thanks.