I am creating a window, in which click on save communicate with database and save data in database. I want to show progress image on click on save until data is not saved in database. I have set the visibility of image to true but still that progress image is not visible.
I have done following code...
In xml file..
<TextBox x:Name="txt_Comment" VerticalScrollBarVisibility="Auto" TextWrapping="Wrap" AcceptsReturn="True" MaxLength="5000" Margin="2,2,2,0"></TextBox>
<WrapPanel Grid.Row="1" HorizontalAlignment="Center" Margin="10,-15,0,0" VerticalAlignment="Center">
<Button x:Name="btn_Ok" Margin="0,0,0,0" HorizontalAlignment="Center" VerticalAlignment="Center" Click="btn_Save_Click" Height="25" Width="55">Save</Button>
<Button x:Name="btn_Cancel" Margin="10,0,0,0" HorizontalAlignment="Center" VerticalAlignment="Center" Height="25" Width="55" Content="Cancel" Click="btn_Cancel_Click" >
</Button>
</WrapPanel>
<Grid Grid.RowSpan="2" Background="Black" Opacity="0.25" Name="LoadingAdorner" Visibility="Hidden"/>
<Border Width="400" Grid.RowSpan="2" Opacity="1" Height="180" Visibility="Hidden" HorizontalAlignment="Center" VerticalAlignment="Center" CornerRadius="2" x:Name="loaderBorder">
<Border.Background>
<LinearGradientBrush EndPoint="1,1" StartPoint="0,0" >
<GradientStop Color="#EBF6FA" Offset="0.3"/>
<GradientStop Color="#b7d9e5" Offset="1.0"/>
</LinearGradientBrush>
</Border.Background>
<Border.Effect>
<DropShadowEffect BlurRadius="5" Color="#FFB0B0B0" ShadowDepth="3" />
</Border.Effect>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="30"/>
<RowDefinition/>
<RowDefinition Height="95"/>
</Grid.RowDefinitions>
<Controls:LoadingAnimation Grid.Row="1" HorizontalAlignment="Center" FontWeight="Bold" LoadingText="Loading..." VerticalAlignment="Center" />
<TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" FontWeight="Bold" FontFamily="Arial" Foreground="#647883" FontSize="14" Grid.Row="2" Text="Saving..."></TextBlock>
</Grid>
</Border>
</Grid>
In code behind page..
BackgroundWorker worker = new BackgroundWorker { WorkerSupportsCancellation = true };
worker.DoWork += delegate(object sender1, DoWorkEventArgs e1)
{
CurrentDispatcher.Invoke(
new Action(() =>
{
if (!string.IsNullOrEmpty(txt_Comment.Text))
{
LoadingAdorner.Visibility = Visibility.Visible;
loaderBorder.Visibility = Visibility.Visible;
using (Entities DB = new Entities(settings.LinqConnection))
{
if (txt_Comment.Text.Length > 1000)
{//In this case loading image is visible
MessageBox.Show("Comment is too large.", "Alert !", MessageBoxButton.OK, MessageBoxImage.Warning);
return;
}
var comment = DB.Table1.Create();//Here loading image is not visible.
comment.value = txt_Comment.Text;
comment.Date = DateTime.Now;
comment.ModifiedBy = settings.CurrentUID;
DB.Table1.Add(comment);
DB.SaveChanges();
}
}
}),
DispatcherPriority.Normal);
};
worker.RunWorkerCompleted += delegate(object s, RunWorkerCompletedEventArgs args)
{
this.DialogResult = true;
this.Close();
LoadingAdorner.Visibility = Visibility.Collapsed;
loaderBorder.Visibility = Visibility.Collapsed;
};
worker.RunWorkerAsync();
When messagebox is visible than loading image is visible, but when data is saving in database then loading image is not visible.
This is how i would have done in such situation :
Create delegate to update your visibility and corresponding method
Wrap your anonymous function in a function compatible with doWork event
Create a new delegate and call the update method using dispatcher.BeginInvoke() when you need to update visibility.
private delegate void UpdateVisibilityDelegate(Visibility visibility);
private void UpdateVisiblity(Visibility visibility)
{
//LoadingAdorner.Visibility = visibility;
//loaderBorder.Visibility = visibility;
}
private void Worker_DoWork(object sender, DoWorkEventArgs e)
{
// Your Action() code here
// Change the visibility using this method
Dispatcher.CurrentDispatcher.BeginInvoke(new UpdateVisibilityDelegate(this.UpdateVisiblity), Visibility.Visible);
}
Move your using block out of CurrentDispatcher.Invoke() and put after this call.
BackgroundWorker worker = new BackgroundWorker { WorkerSupportsCancellation = true };
worker.DoWork += delegate(object sender1, DoWorkEventArgs e1)
{
CurrentDispatcher.Invoke(
new Action(() =>
{
if (!string.IsNullOrEmpty(txt_Comment.Text))
{
LoadingAdorner.Visibility = Visibility.Visible;
loaderBorder.Visibility = Visibility.Visible;
}
}),
DispatcherPriority.Normal);
using (Entities DB = new Entities(settings.LinqConnection))
{
if (txt_Comment.Text.Length > 1000)
{//In this case loading image is visible
MessageBox.Show("Comment is too large.", "Alert !", MessageBoxButton.OK, MessageBoxImage.Warning);
return;
}
var comment = DB.Table1.Create();//Here loading image is not visible.
comment.value = txt_Comment.Text;
comment.Date = DateTime.Now;
comment.ModifiedBy = settings.CurrentUID;
DB.Table1.Add(comment);
DB.SaveChanges();
}
};
so this code works for me:
private void Button_Click(object sender, RoutedEventArgs e)
{
var worker = new BackgroundWorker { WorkerSupportsCancellation = true };
worker.DoWork += delegate (object sender1, DoWorkEventArgs e1)
{
Dispatcher.Invoke(
new Action(() =>{testCtl.Visibility = Visibility.Visible;}),
System.Windows.Threading.DispatcherPriority.Normal);
Task.Delay(3000).Wait();
};
worker.RunWorkerCompleted += delegate (object s, RunWorkerCompletedEventArgs args)
{
testCtl.Visibility = Visibility.Collapsed;
};
worker.RunWorkerAsync();
}
Related
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 am trying to make an auction application for my course.
namespace Auction
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
GetData("SELECT * FROM Produs");
btnLogout.Visibility = System.Windows.Visibility.Hidden;
btnAdd.Visibility = System.Windows.Visibility.Hidden;
btnBid.Visibility = System.Windows.Visibility.Hidden;
tb.Visibility = System.Windows.Visibility.Hidden;
}
private void GetData(string SelectCommand)
{
SqlConnection conn = new SqlConnection(#"Data Source=ISAAC;Initial Catalog=licitatie;Integrated Security=True");
conn.Open();
SqlCommand cmd = new SqlCommand(SelectCommand);
cmd.Connection = conn;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("prod");
sda.Fill(dt);
myGrid.DataContext = dt;
}
private void btnLogin_Click(object sender, RoutedEventArgs e)
{
Login login = new Login();
login.Show();
Close();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Countdown(30, TimeSpan.FromSeconds(1), cur => tb.Text = cur.ToString());
}
void Countdown(int count, TimeSpan interval, Action<int> ts)
{
var dt = new System.Windows.Threading.DispatcherTimer();
dt.Interval = interval;
dt.Tick += (_, a) =>
{
if (count-- == 0)
{
MessageBox.Show("You have won this product!");
dt.Stop();
}
else
ts(count);
};
ts(count);
dt.Start();
}
private void btnLogout_Click(object sender, RoutedEventArgs e)
{
MainWindow main = new MainWindow();
main.Show();
Close();
MessageBox.Show("You are not logged. Please log in to bid", "Failed",
MessageBoxButton.OK, MessageBoxImage.Information);
}
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
Register reg = new Register();
reg.Show();
Close();
}
private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var grid = sender as DataGrid;
var selected = grid.SelectedItem;
if (selected == grid.SelectedItem)
{
btnBid.Visibility = System.Windows.Visibility.Visible;
}
}
private void UpdateColumn()
{
}
}
}
This is main page you need to login. I read data from database. The problem is when I press bid button many times it is just resetting, but in background is working on. What do I need to do?
<Window x:Class="Auction.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="500" Width="800">
<Grid Margin="0,148,0,3" Name="myGrid" Background="#FF00286E">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="29*"/>
<ColumnDefinition Width="15*"/>
<ColumnDefinition Width="0*"/>
</Grid.ColumnDefinitions>
<Grid HorizontalAlignment="Left" Height="66" Margin="0,-68,0,0" VerticalAlignment="Top"
Width="792" Background="#FF00286E" Grid.ColumnSpan="2">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="12*"/>
<ColumnDefinition Width="13*"/>
</Grid.ColumnDefinitions>
<Button Content="Login" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Bottom"
Width="102" Height="35" Name="btnLogin" Click="btnLogin_Click">
<Button.Template>
<ControlTemplate TargetType="Button">
<TextBlock TextDecorations="Underline" Margin="0,0,0,-19" FontSize="24"
FontFamily="Verdana" FontWeight="Bold" FontStyle="Italic">
<ContentPresenter />
</TextBlock>
</ControlTemplate>
</Button.Template>
</Button>
<Button Content="Logout" Grid.Column="1" HorizontalAlignment="Left" Margin="300,10,0,0" VerticalAlignment="Bottom"
Width="102" Height="35" Name="btnLogout" Click="btnLogout_Click">
<Button.Template>
<ControlTemplate TargetType="Button">
<TextBlock TextDecorations="Underline" Margin="0,0,0,-19" FontSize="24"
FontFamily="Verdana" FontWeight="Bold" FontStyle="Italic">
<ContentPresenter />
</TextBlock>
</ControlTemplate>
</Button.Template>
</Button>
</Grid>
<Grid HorizontalAlignment="Left" Height="78" Margin="0,-146,0,0" VerticalAlignment="Top" Width="792"
Grid.ColumnSpan="2" Background="#FF98BFD4">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="769*"/>
<ColumnDefinition Width="31*"/>
</Grid.ColumnDefinitions>
<Label Content="Welcome to Auction Application. Please Login to bid!" HorizontalAlignment="Center" Margin="44,28,0,0" VerticalAlignment="Top"
Height="40" Width="748" BorderThickness="3" FontSize="18" FontWeight="Bold" FontFamily="Verdana" Background="#FF98BFD4" Grid.ColumnSpan="2"/>
</Grid>
<Button Content="Bid" Grid.Column="1" HorizontalAlignment="Left" Margin="10,10,0,0"
VerticalAlignment="Top" Width="103" Height="29" FontSize="20" FontFamily="Verdana" FontStyle="Italic"
FontWeight="ExtraBold" Click="Button_Click" Name="btnBid"/>
<Button Content="Add User" Grid.Column="1" HorizontalAlignment="Left" Margin="10,255,0,0"
VerticalAlignment="Top" Width="103" Height="31" Name="btnAdd" Click="btnAdd_Click"/>
<DataGrid HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top"
Height="298" Width="502" Name="dataGrid1" ItemsSource="{Binding}"
SelectionChanged="DataGrid_SelectionChanged" AlternatingRowBackground="Coral">
</DataGrid>
<TextBox Grid.Column="1" HorizontalAlignment="Left" Height="48" Margin="10,119,0,0" TextWrapping="Wrap"
VerticalAlignment="Top" Width="144" Name="tb" FontSize="20" FontWeight="Bold" FontStyle="Italic" IsReadOnly="True"/>
</Grid>
</Window>
If I understand correctly, each time the user clicks the Bid button, you need to reset the timer. However, the previous timer continues. I haven't pasted your code into a project to test, but it appears to me that you need to make the dispatch timer a class field or property like this:
private DispatchTimer _dt = new System.Windows.Threading.DispatcherTimer();
Inside the event handler for Bid, stop the current _dt first followed by instantiating the new timer:
_dt.Stop();
_dt = new System.Windows.Threading.DispatcherTimer();
Try this change:
namespace Auction
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
//Class level field:
private DispatchTimer _dt = new System.Windows.Threading.DispatcherTimer();
public MainWindow()
{
InitializeComponent();
GetData("SELECT * FROM Produs");
btnLogout.Visibility = System.Windows.Visibility.Hidden;
btnAdd.Visibility = System.Windows.Visibility.Hidden;
btnBid.Visibility = System.Windows.Visibility.Hidden;
tb.Visibility = System.Windows.Visibility.Hidden;
}
private void GetData(string SelectCommand)
{
SqlConnection conn = new SqlConnection(#"Data Source=ISAAC;Initial Catalog=licitatie;Integrated Security=True");
conn.Open();
SqlCommand cmd = new SqlCommand(SelectCommand);
cmd.Connection = conn;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("prod");
sda.Fill(dt);
myGrid.DataContext = dt;
}
private void btnLogin_Click(object sender, RoutedEventArgs e)
{
Login login = new Login();
login.Show();
Close();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Countdown(30, TimeSpan.FromSeconds(1), cur => tb.Text = cur.ToString());
}
void Countdown(int count, TimeSpan interval, Action<int> ts)
{
this._dt.Stop();
this._dt = new System.Windows.Threading.DispatcherTimer();
this._dt.Interval = interval;
this._dt.Tick += (_, a) =>
{
if (count-- == 0)
{
MessageBox.Show("You have won this product!");
this._dt.Stop();
}
else
ts(count);
};
ts(count);
this._dt.Start();
}
private void btnLogout_Click(object sender, RoutedEventArgs e)
{
MainWindow main = new MainWindow();
main.Show();
Close();
MessageBox.Show("You are not logged. Please log in to bid", "Failed",
MessageBoxButton.OK, MessageBoxImage.Information);
}
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
Register reg = new Register();
reg.Show();
Close();
}
private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var grid = sender as DataGrid;
var selected = grid.SelectedItem;
if (selected == grid.SelectedItem)
{
btnBid.Visibility = System.Windows.Visibility.Visible;
}
}
private void UpdateColumn()
{
}
}
}
Similar questions may exists, but none of them seems to be helpful. So I'll try to explain a more specific case, and see if anyone can help me.
I have an application that has a label with a gradient background. I created the gradient background using XAML, my program changes the background fine, but I want the background to change back to "normal" after the user clicks the reset button. How can I do this as still new to wpf? The code in XAML "LinearGradientBrush x:Key="headerBackground" is what I want to access in code behind
<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="600">
<Window.Resources>
**<LinearGradientBrush x:Key="headerBackground" 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 x:Name="Row1"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition x:Name="Col1"/>
<ColumnDefinition x:Name="Col2"/>
<ColumnDefinition x:Name="Col3"/>
</Grid.ColumnDefinitions>
<Label x:Name="Label1"
Content="Rock Properties"
Grid.Row="0"
Grid.Column="0"
MouseDoubleClick="Label1_MouseDoubleClick"
Background="{DynamicResource headerBackground}"
VerticalAlignment="Top"/>
<Label x:Name="Label2"
Content="Contacts"
Grid.Column="1"
Grid.Row="0"
Background="{DynamicResource headerBackground}"
MouseDoubleClick="Label2_MouseDoubleClick"
Margin="0,0,0,282"
VerticalAlignment="Top"/>
<Label x:Name="Label3"
Content="Fluid Properties"
Grid.Column="2"
Background="{DynamicResource headerBackground}"
Grid.Row="0"
MouseDoubleClick="Label3_MouseDoubleClick"
Margin="0,0,0,282"
VerticalAlignment="Top"/>
<Button x:Name="Resetbtn" Content="Reset" HorizontalAlignment="Left" Margin="0,70,0,0" VerticalAlignment="Top" Width="75" Click="Reset_Click" Background="{DynamicResource selectedHeaderBackground}"/>
<Button Name="CloseRock" Content="X" HorizontalAlignment="Left" Margin="173,4,0,0" VerticalAlignment="Top" Width="24" Grid.Column="0"/>
<Button Name="CloseContacts" Content="X" HorizontalAlignment="Left" Margin="174,2,0,0" VerticalAlignment="Top" Width="24" Grid.Column="1"/>
<Button Name="CloseFluid" Content="X" HorizontalAlignment="Left" Margin="173,2,0,0" VerticalAlignment="Top" Width="24" Grid.Column="2"/>
</Grid>
C#
private ColumnDefinition SelectedColumn;
private Color selectedHeaderBackground = (Color)ColorConverter.ConvertFromString("#EBA32A");
public MainWindow()
{
InitializeComponent();
}
private void Label1_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
SelectedColumn = Col1;
SetCol1Header();
SetColumnWidth();
SetColumnWidthCol1();
}
private void Label2_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
SelectedColumn = Col2;
SetCol2Header();
SetColumnWidth();
SetColumnWidthCol2();
}
private void Label3_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
SelectedColumn = Col3;
SetCol3Header();
SetColumnWidth();
SetColumnWidthCol3();
}
public void SetColumnWidth()
{
SelectedColumn.Width = new GridLength(1, GridUnitType.Star);
}
private void Reset_Click(object sender, RoutedEventArgs e)
{
ResetHeaderBackground();
ResetColumnWidth();
ResetColumns();
}
private void ResetColumns()
{
Label1.Visibility = System.Windows.Visibility.Visible;
}
private void ResetColumnWidth()
{
Col1.Width = new GridLength(1, GridUnitType.Star);
Col2.Width = new GridLength(1, GridUnitType.Star);
Col3.Width = new GridLength(1, GridUnitType.Star);
}
private void ResetHeaderBackground()
{
//Label3.Background = new SolidColorBrush(HeaderBackground);
//Label2.Background = new SolidColorBrush(HeaderBackground);
//Label1.Background = new SolidColorBrush(HeaderBackground);
}
private void MinimiseRock_Click(object sender, RoutedEventArgs e)
{
MinimiseWindow();
}
private void MinimiseContacts_Click(object sender, RoutedEventArgs e)
{
MinimiseWindow();
}
private void MinimiseFluid_Click(object sender, RoutedEventArgs e)
{
MinimiseWindow();
}
private void MinimiseWindow()
{
this.WindowState = WindowState.Minimized;
}
private void SetCol1Header()
{
Label1.Background = new SolidColorBrush(selectedHeaderBackground);
}
private void SetCol2Header()
{
Label2.Background = new SolidColorBrush(selectedHeaderBackground);
}
private void SetCol3Header()
{
Label3.Background = new SolidColorBrush(selectedHeaderBackground);
}
private void SetColumnWidthCol1()
{
Col2.Width = new GridLength(150);
Col3.Width = new GridLength(150);
}
private void SetColumnWidthCol2()
{
Col1.Width = new GridLength(150);
Col3.Width = new GridLength(150);
}
private void SetColumnWidthCol3()
{
Col1.Width = new GridLength(150);
Col2.Width = new GridLength(150);
}
}
You can access the Resources of your Window by invoking FindResource providing the key you have set for your Brush (and eventually cast it to LinearGradientBrush).
this.Label1.Background = (LinearGradientBrush)this.FindResource("headerBackground")
cheeers.
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 working with windows phone 8 apps and want to add augmented reality feature and I'm using GART, but I experiencing the same issue
in there and even there is a solution by Igor Ralic by adding canvas.zindex to 1, I'm still experiencing the same issue (the items in world view flicker and disappear), so maybe there is anybody in here that having much better solution? I'm using mvvm patern to work with this AR
Here is my approach with mvvm
This is my mainviewmodel
private ObservableCollection<ARItem> _ardisplayLocation = null;
public ObservableCollection<ARItem> ardisplayLocation
{
get { return _ardisplayLocation; }
set { this.SetProperty(ref this._ardisplayLocation, value); }
}
private void UpdateTransport()
{
try
{
myMessage = "Loading web server data...";
WebClient client = new WebClient();
Uri uri = new Uri(transportURL1 + latitude + "%2C" + longitude + transportURL2, UriKind.Absolute);
client.DownloadStringCompleted += (s, e) =>
{
MainPage mainpage = new MainPage();
mainpage.RefreshButton();
if (e.Error == null)
{
RootObject result = JsonConvert.DeserializeObject<RootObject>(e.Result);
hereRestProperty = new ObservableCollection<Item>(result.results.items);
for (int i = 0; i < hereRestProperty.Count; i++)
{
ardisplayLocation.Add(new CityPlace()
{
GeoLocation = new GeoCoordinate(hereRestProperty[i].coordinate.Latitude,hereRestProperty[i].coordinate.Longitude),
Content = hereRestProperty[i].title,
Description = hereRestProperty[i].vicinity
});
}
}
else
{
isFailed = Visibility.Visible;
myMessage = "Failed to load web server data, please refresh";
}
isBusy = false;
};
client.DownloadStringAsync(uri);
}
catch (Exception)
{
isBusy = false;
isFailed = Visibility.Visible;
myMessage = "Something wrong happen, please refresh";
}
}
and here is my ArDisplay.xaml.cs
private MainViewModel mvm { get { return this.DataContext as MainViewModel; } }
public ArDisplay()
{
InitializeComponent();
DataContext = App.ViewModel;
}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
ardisplay.StartServices();
ardisplay.ARItems = mvm.ardisplayLocation;
base.OnNavigatedTo(e);
}
protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
{
ardisplay.StopServices();
base.OnNavigatedFrom(e);
}
and my xaml
<gart:ARDisplay Name="ardisplay" AttitudeRefreshRate="50" MovementThreshold="10">
<gart:VideoPreview x:Name="videoPreview" Canvas.ZIndex="1"/>
<gart:WorldView x:Name="worldView" Canvas.ZIndex="1" ItemTemplate="{StaticResource CityItemTemplate}" MinItemScale="0.1" MaxItemScale="1.0" FarClippingPlane="300.0" NearClippingPlane="1.0"/>
<gart:HeadingIndicator x:Name="headingIndicator" Canvas.ZIndex="1" Width="300" Height="300" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</gart:ARDisplay>
and my data template
<DataTemplate x:Key="CityItemTemplate">
<Border BorderBrush="Black" BorderThickness="4" CornerRadius="8" Background="#FF003847" Width="320">
<StackPanel Margin="4">
<TextBlock x:Name="NameBlock" TextWrapping="NoWrap" Text="{Binding Content}" FontSize="38" VerticalAlignment="Center" Margin="0,0,4,0" Grid.Column="1" TextTrimming="WordEllipsis"/>
<TextBlock x:Name="DescriptionBlock" TextWrapping="Wrap" Text="{Binding Description}" FontSize="24" VerticalAlignment="Center" Margin="0,0,4,0" Grid.Column="1" TextTrimming="WordEllipsis" MaxHeight="168"/>
</StackPanel>
</Border>
</DataTemplate>
Canvas.ZIndex was missing from your DataTemplate
<DataTemplate x:Key="CityItemTemplate">
<Border BorderBrush="Black" BorderThickness="4" CornerRadius="8" Background="#FF003847" Width="320" Canvas.ZIndex="2">
<StackPanel Margin="4">
<TextBlock x:Name="NameBlock" TextWrapping="NoWrap" Text="{Binding Content}" FontSize="38" VerticalAlignment="Center" Margin="0,0,4,0" Grid.Column="1" TextTrimming="WordEllipsis"/>
<TextBlock x:Name="DescriptionBlock" TextWrapping="Wrap" Text="{Binding Description}" FontSize="24" VerticalAlignment="Center" Margin="0,0,4,0" Grid.Column="1" TextTrimming="WordEllipsis" MaxHeight="168"/>
</StackPanel>
</Border>
</DataTemplate>