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;
}));
Related
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()
{
}
}
}
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;
}
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.
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.
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>