I am trying to add a scroll viewer to stackpanels - "gradpaneldesc" , "undergrapaneldesc" and "certficatedesc" which are inside another parent stackpanel- "mainpanel" respectively, but I am unable to achieve this as its showing me scrollviewer perhaps but there is no actual scrollbar,not realizing where is the mistake. Any help will be highly appreciated.
XAML
<UserControl x:Class="ISTE.Views.CoursesView"XAML
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:ISTE.Views"
mc:Ignorable="d"
d:DesignHeight="600" d:DesignWidth="1300">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="400"/>
<ColumnDefinition Width="400"/>
<ColumnDefinition Width="400"/>
</Grid.ColumnDefinitions>
<Image Source="/Images/degree.jpg"
Stretch="Fill"
Height="250"
Grid.ColumnSpan="3"/>
<StackPanel x:Name="mainpanel1" Grid.Column="0">
<Button x:Name="Graduate" IsDefault="True" Click="Graduate_Click" >
<Button.Background>
<LinearGradientBrush EndPoint="0.5,1" MappingMode="RelativeToBoundingBox" StartPoint="0.5,0">
<GradientStop Color="#FF235DF0" Offset="0"/>
<GradientStop Color="#FFE7EBF5" Offset="1"/>
<GradientStop Color="#FF9EB6F3" Offset="0.632"/>
</LinearGradientBrush>
</Button.Background> Graduate
</Button>
<StackPanel x:Name="gradpanel" Height="200px"></StackPanel>
<Border x:Name="myBorder2">
<ScrollViewer>
<StackPanel x:Name="gradpaneldesc" Height="200px"></StackPanel>
</ScrollViewer>
</Border>
</StackPanel>
<StackPanel x:Name="mainpanel2" Grid.Column="1">
<Button x:Name="UnderGraduate" IsDefault="True" Click="UnderGraduate_Click" >
<Button.Background>
<LinearGradientBrush EndPoint="0.5,1" MappingMode="RelativeToBoundingBox" StartPoint="0.5,0">
<GradientStop Color="#FF235DF0" Offset="0"/>
<GradientStop Color="#FFE7EBF5" Offset="1"/>
<GradientStop Color="#FF9EB6F3" Offset="0.632"/>
</LinearGradientBrush>
</Button.Background> Undergraduate</Button>
<StackPanel x:Name="undergradpanel" Height="200px"></StackPanel>
<Border x:Name="myBorder1">
<ScrollViewer>
<StackPanel x:Name="undergradpaneldesc" Height="200px"></StackPanel>
</ScrollViewer>
</Border>
</StackPanel>
<StackPanel Grid.Column="2">
<Button x:Name="Certifications" IsDefault="True" Click="Certifications_Click" >
<Button.Background>
<LinearGradientBrush EndPoint="0.5,1" MappingMode="RelativeToBoundingBox" StartPoint="0.5,0">
<GradientStop Color="#FF235DF0" Offset="0"/>
<GradientStop Color="#FFE7EBF5" Offset="1"/>
<GradientStop Color="#FF9EB6F3" Offset="0.632"/>
</LinearGradientBrush>
</Button.Background> Certifications</Button>
<StackPanel x:Name="certpanel" Height="200px"></StackPanel>
<Border x:Name="myBorder3">
<ScrollViewer>
<StackPanel x:Name="certificatedesc" Height="200px"></StackPanel>
</ScrollViewer>
</Border>
</StackPanel>
</Grid>
CS
using ISTE.Models;
using ISTE.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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.Navigation;
using System.Windows.Shapes;
namespace ISTE.Views
{
/// <summary>
/// Interaction logic for CoursesView.xaml
/// </summary>
public partial class CoursesView : UserControl
{
CoursesVM vm;
public CoursesView()
{
InitializeComponent();
vm = new CoursesVM();
this.DataContext = vm;
vm.GetData();
}
bool flag=false;
bool flag1=false;
private void UnderGraduate_Click(object sender1, RoutedEventArgs e1)
{
if (flag1 == false)
{
foreach (Undergraduate grad in vm.ItemData.undergraduate)
{
var textb = new Button();
undergradpanel.Children.Add(textb);
textb.Content = grad.degreeName;
textb.Click += new RoutedEventHandler(ugdegreeEventHandler);
Console.WriteLine("graddegrees \t" + grad.degreeName);
}
}
flag1 = true;
}
void ugdegreeEventHandler(object sender2, RoutedEventArgs e2)
{
// Console.WriteLine("hi select");
var b = sender2 as Button;
// var textb2 = new TextBlock();
// textb2.Text
myBorder1.Background = Brushes.SkyBlue;
myBorder1.BorderBrush = Brushes.Blue;
myBorder1.BorderThickness = new Thickness(2);
myBorder1.CornerRadius = new CornerRadius(8);
myBorder1.Padding = new Thickness(6);
var degreeselected = b.Content.ToString();
if (undergradpaneldesc.Children.Count < 1)
{
var textb2 = new TextBlock();
textb2.Name = "textblock";
undergradpaneldesc.Children.Add(textb2);
foreach (Undergraduate grad in vm.ItemData.undergraduate)
{
if (grad.degreeName == degreeselected)
{
textb2.TextDecorations = TextDecorations.Underline;
textb2.Text = grad.description+"\n\n";
textb2.TextWrapping = TextWrapping.Wrap;
return;
}
}
}
else
{
foreach (Undergraduate grad in vm.ItemData.undergraduate)
{
if (grad.degreeName == degreeselected)
{
foreach (TextBlock ch in undergradpaneldesc.Children)
{
ch.Text = "";
ch.TextDecorations = TextDecorations.Underline;
ch.Text = grad.description+"\n\n";
ch.TextWrapping = TextWrapping.Wrap;
return;
}
}
}
}
}
private void Graduate_Click(object sender, RoutedEventArgs e)
{
if (flag == false)
{
foreach (Graduate grad in vm.ItemData.graduate)
{
var textb = new Button();
gradpanel.Children.Add(textb);
textb.Content = grad.degreeName;
textb.IsDefault = true;
textb.Click += new RoutedEventHandler(degreeEventHandler);
Console.WriteLine("graddegrees \t" + grad.degreeName);
}
}
flag = true;
}
void degreeEventHandler(object sender, RoutedEventArgs e)
{
// Console.WriteLine("hi select");
var b = sender as Button;
// var textb2 = new TextBlock();
// textb2.Text
var degreeselected = b.Content.ToString();
myBorder2.Background = Brushes.SkyBlue;
myBorder2.BorderBrush = Brushes.Black;
myBorder2.BorderThickness = new Thickness(2);
myBorder2.CornerRadius = new CornerRadius(8);
myBorder2.Padding = new Thickness(6);
if (gradpaneldesc.Children.Count<1)
{
var textb1 = new TextBlock();
textb1.Name = "textblock1";
gradpaneldesc.Children.Add(textb1);
foreach (Graduate grad in vm.ItemData.graduate)
{
if (grad.degreeName == degreeselected)
{
if (grad.degreeName != "graduate advanced certificates")
{
textb1.Text = grad.description;
textb1.TextDecorations = TextDecorations.Underline;
foreach (var conc in grad.concentrations)
{
textb1.Text += conc + "\n\n";
}
textb1.TextWrapping = TextWrapping.Wrap;
return;
}
else
{
textb1.TextDecorations = TextDecorations.Underline;
foreach (var conc in grad.availableCertificates)
{
textb1.Text += conc + "\n\n";
}
textb1.TextWrapping = TextWrapping.Wrap;
return;
}
}
}
}
else
{
foreach (Graduate grad in vm.ItemData.graduate)
{
if (grad.degreeName == degreeselected)
{
if (grad.degreeName != "graduate advanced certificates")
{
foreach (TextBlock ch in gradpaneldesc.Children)
{
ch.Text = "";
ch.Text = grad.description + "\n\n";
ch.TextDecorations = TextDecorations.Underline;
foreach (var conc in grad.concentrations)
{
ch.Text += conc + "\n";
}
ch.TextWrapping = TextWrapping.Wrap;
return;
}
}
else
{
foreach (TextBlock ch in gradpaneldesc.Children)
{
ch.Text = "";
ch.TextDecorations = TextDecorations.Underline;
foreach (var conc in grad.availableCertificates)
{
ch.Text += conc + "\n";
}
ch.TextWrapping = TextWrapping.Wrap;
return;
}
}
}
}
}
}
private void Certifications_Click(object sender, RoutedEventArgs e)
{
var textb3 = new TextBlock();
textb3.Name = "textblock3";
certificatedesc.Children.Add(textb3);
textb3.TextDecorations = TextDecorations.Underline;
myBorder3.Background = Brushes.SkyBlue;
myBorder3.BorderBrush = Brushes.Black;
myBorder3.BorderThickness = new Thickness(2);
myBorder3.CornerRadius = new CornerRadius(8);
myBorder3.Padding = new Thickness(6);
foreach (Graduate grad in vm.ItemData.graduate)
{
if (grad.degreeName == "graduate advanced certificates")
{
textb3.Text = grad.description;
textb3.TextDecorations = TextDecorations.Underline;
foreach (var conc in grad.availableCertificates)
{
textb3.Text += conc + "\n\n";
}
textb3.TextWrapping = TextWrapping.Wrap;
return;
}
}
}
}
}
You need to specify the height of the ScrollViewer not the StackPanel, because otherwise the StackPanel won't extend beyond the bounds of the ScrollViewer and the scroll bar won't display.
<Border x:Name="myBorder2">
<ScrollViewer Height="200px">
<StackPanel x:Name="gradpaneldesc">
</StackPanel>
</ScrollViewer>
</Border>
Related
So today i started my WPF .net framework project again.
But it start of with a problem
Error CS0234 The type or namespace name 'Pages' does not exist in the namespace.
But this is strange because yesterday i had no problem, and if i try to start it anyway ignoring the error it will start normally en everything works.
So how can i stop getting this error message? because the program works. And the folder Pages exists
ZendersPage.xaml
<Page x:Class="Kraeken_en_Krønen_HKS_FO.ZendersPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:Kraeken_en_Krønen_HKS_FO"
mc:Ignorable="d"
d:DesignHeight="720" d:DesignWidth="1080"
Title="ZendersPage"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
TextElement.Foreground="{DynamicResource MaterialDesignBody}"
TextElement.FontWeight="Regular"
TextElement.FontSize="13"
TextOptions.TextFormattingMode="Ideal"
TextOptions.TextRenderingMode="Auto"
Background="#FF3F3F46"
FontFamily="{DynamicResource MaterialDesignFont}">
<Grid Background="#FF3F3F46">
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<Grid Grid.Row="0">
<StackPanel Margin="10,10,10,0">
<materialDesign:Card Background="#FF3F3F46">
<StackPanel Orientation="Vertical">
<Label Content="Zender toevoegen" FontSize="20px" Foreground="White" Margin="10,0,0,0"/>
<Label Content="Zender" Foreground="White" FontSize="20px" Margin="10,20,0,0"/>
<TextBox Foreground="White" FontSize="20px" Background="#FF62626A" Height="30px" Margin="10,0,0,0" x:Name="NewZenderNaam"/>
<Label Content="Omschrijving" Foreground="White" FontSize="20px" Margin="10,20,0,0"/>
<TextBox Foreground="White" FontSize="20px" Background="#FF62626A" Height="30px" Margin="10,0,0,0" x:Name="NewZenderOmschrijving"/>
<Button HorizontalAlignment="Left" Margin="10,20,0,10" Click="CreateNewZender" >
<StackPanel Orientation="Horizontal">
<materialDesign:PackIcon Kind="SendOutline" Width="20px" Height="25px"/>
<Label VerticalAlignment="Center" FontSize="15px" Foreground="#DDFFFFFF">Toevoegen</Label>
</StackPanel>
</Button>
</StackPanel>
</materialDesign:Card>
</StackPanel>
</Grid>
<Grid Grid.Row="0" Grid.RowSpan="4">
<WrapPanel x:Name="WijzigZenderPanel" Panel.ZIndex="205"/>
</Grid>
<Grid Grid.Row="1" VerticalAlignment="Top" HorizontalAlignment="Center">
<WrapPanel x:Name="ExtraZender" HorizontalAlignment="Center"/>
</Grid>
<Grid Grid.Row="2" VerticalAlignment="Top" HorizontalAlignment="Center">
<WrapPanel x:Name="ExtraZender1" HorizontalAlignment="Center"/>
</Grid>
<Grid Grid.Row="3" VerticalAlignment="Top" HorizontalAlignment="Center">
<WrapPanel x:Name="ExtraZender2" HorizontalAlignment="Center"/>
</Grid>
<Grid Grid.Row="4" VerticalAlignment="Top" HorizontalAlignment="Center">
<WrapPanel x:Name="ExtraZender3" HorizontalAlignment="Center"/>
</Grid>
<Grid Grid.Row="4" VerticalAlignment="Top" HorizontalAlignment="Center">
<WrapPanel x:Name="ExtraZender4" HorizontalAlignment="Center"/>
</Grid>
<Grid Grid.Row="4" VerticalAlignment="Top" HorizontalAlignment="Center">
<WrapPanel x:Name="ExtraZender5" HorizontalAlignment="Center"/>
</Grid>
</Grid>
using Kraeken_en_Krønen_HKS_FO.Pages;
using Kraeken_en_Krønen_HKS_FO.UserControls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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.Navigation;
using System.Windows.Shapes;
namespace Kraeken_en_Krønen_HKS_FO
{
/// <summary>
/// Interaction logic for ZendersPage.xaml
/// </summary>
///
class ZenderInformation
{
private static string ZenderTitel = "";
public static string ZenderTitelText
{
get { return ZenderTitel; }
set { ZenderTitel = value; }
}
private static string ZenderOmschrijving = "";
public static string ZenderOmschrijvingText
{
get { return ZenderOmschrijving; }
set { ZenderOmschrijving = value; }
}
private static int i = 0;
public static int y
{
get { return i; }
set { i = value; }
}
private static int ZenderCount = 0;
public static int ZenderCounter
{
get { return ZenderCount; }
set { ZenderCount = value; }
}
}
public partial class ZendersPage : Page
{
Zenders zendersClass = new Zenders();
int gridCount = 0;
int totalCount;
public ZendersPage()
{
InitializeComponent();
try
{
zendersClass.GetAllChannels();
PlaceZendersInGrid();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
private void CreateNewZender(object sender, RoutedEventArgs e)
{
try
{
if (NewZenderNaam.Text != string.Empty && NewZenderOmschrijving.Text != string.Empty)
{
ZenderInformation.ZenderTitelText = NewZenderNaam.Text;
ZenderInformation.ZenderOmschrijvingText = NewZenderOmschrijving.Text;
zendersClass.UpdateDbWithNewZenders();
ExtraZender.Children.Clear();
ExtraZender1.Children.Clear();
ExtraZender2.Children.Clear();
ExtraZender3.Children.Clear();
ExtraZender4.Children.Clear();
ExtraZender5.Children.Clear();
PlaceZendersInGrid();
NewZenderNaam.Text = String.Empty;
NewZenderOmschrijving.Text = String.Empty;
}
else
{
MessageBox.Show("Geen zender informatie ingevoerd");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
public void PlaceZendersInGrid()
{
try
{
zendersClass.GetAllChannels();
foreach (var zender in ZenderNames.MusicZenders)
{
ZenderInformation.ZenderCounter++;
}
while (gridCount < ZenderInformation.ZenderCounter)
{
if (gridCount <= ZenderInformation.ZenderCounter)
{
for (ZenderInformation.y = 0; ZenderInformation.y < 3; ZenderInformation.y++)
{
NewZenderLayout newZenderLayout = new NewZenderLayout();
newZenderLayout.NewZender.Text = ZenderNames.MusicZenders[ZenderInformation.y].ToString();
newZenderLayout.NewOmschrijving.Text = ZenderNames.Musicdescription[ZenderInformation.y].ToString();
newZenderLayout.Name = "zender" + ZenderNames.ZendersId[ZenderInformation.y];
ExtraZender.Children.Add(newZenderLayout);
totalCount = gridCount + 1;
gridCount = totalCount;
}
if (gridCount <= ZenderInformation.ZenderCounter)
{
for (ZenderInformation.y = 3; ZenderInformation.y < 6; ZenderInformation.y++)
{
NewZenderLayout newZenderLayout = new NewZenderLayout();
newZenderLayout.NewZender.Text = ZenderNames.MusicZenders[ZenderInformation.y].ToString();
newZenderLayout.NewOmschrijving.Text = ZenderNames.Musicdescription[ZenderInformation.y].ToString();
newZenderLayout.Name = "zender" + ZenderNames.ZendersId[ZenderInformation.y];
ExtraZender1.Children.Add(newZenderLayout);
totalCount = gridCount + 1;
gridCount = totalCount;
}
if (gridCount <= ZenderInformation.ZenderCounter)
{
for (ZenderInformation.y = 6; ZenderInformation.y < 9; ZenderInformation.y++)
{
NewZenderLayout newZenderLayout = new NewZenderLayout();
newZenderLayout.NewZender.Text = ZenderNames.MusicZenders[ZenderInformation.y].ToString();
newZenderLayout.NewOmschrijving.Text = ZenderNames.Musicdescription[ZenderInformation.y].ToString();
newZenderLayout.Name = "zender" + ZenderNames.ZendersId[ZenderInformation.y];
ExtraZender2.Children.Add(newZenderLayout);
totalCount = gridCount + 1;
gridCount = totalCount;
}
if (gridCount <= ZenderInformation.ZenderCounter)
{
for (ZenderInformation.y = 9; ZenderInformation.y < 12; ZenderInformation.y++)
{
NewZenderLayout newZenderLayout = new NewZenderLayout();
newZenderLayout.NewZender.Text = ZenderNames.MusicZenders[ZenderInformation.y].ToString();
newZenderLayout.NewOmschrijving.Text = ZenderNames.Musicdescription[ZenderInformation.y].ToString();
newZenderLayout.Name = "zender" + ZenderNames.ZendersId[ZenderInformation.y];
ExtraZender3.Children.Add(newZenderLayout);
totalCount = gridCount + 1;
gridCount = totalCount;
}
if (gridCount <= ZenderInformation.ZenderCounter)
{
for (ZenderInformation.y = 12; ZenderInformation.y < 15; ZenderInformation.y++)
{
NewZenderLayout newZenderLayout = new NewZenderLayout();
newZenderLayout.NewZender.Text = ZenderNames.MusicZenders[ZenderInformation.y].ToString();
newZenderLayout.NewOmschrijving.Text = ZenderNames.Musicdescription[ZenderInformation.y].ToString();
newZenderLayout.Name = "zender" + ZenderNames.ZendersId[ZenderInformation.y];
ExtraZender4.Children.Add(newZenderLayout);
totalCount = gridCount + 1;
gridCount = totalCount;
}
if (gridCount <= ZenderInformation.ZenderCounter)
{
for (ZenderInformation.y = 15; ZenderInformation.y < 18; ZenderInformation.y++)
{
NewZenderLayout newZenderLayout = new NewZenderLayout();
newZenderLayout.NewZender.Text = ZenderNames.MusicZenders[ZenderInformation.y].ToString();
newZenderLayout.NewOmschrijving.Text = ZenderNames.Musicdescription[ZenderInformation.y].ToString();
newZenderLayout.Name = "zender" + ZenderNames.ZendersId[ZenderInformation.y];
ExtraZender5.Children.Add(newZenderLayout);
totalCount = gridCount + 1;
gridCount = totalCount;
}
}
}
}
}
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
You don't have a namespace called Kraeken_en_Krønen_HKS_FO.Pages. By convention, namespace structures usually match folder structures, but it's not automatic.
To make them match here you need to change namespace in your .xaml.cs file to:
namespace Kraeken_en_Krønen_HKS_FO.Pages
{
...
and then in your .xaml file you need to make the change in two places:
<Page x:Class="Kraeken_en_Krønen_HKS_FO.Pages.ZendersPage" <--HERE
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:Kraeken_en_Krønen_HKS_FO.Pages" <--HERE
Alternatives you could just remove the .Pages from the line where the error occurs, but in the long term this may cause confusion as you're breaching conventions.
I have a WPF RichTextBox with some standard buttons for text styling. As they should all work the same way, I am going to use the example of making text bold from now on.
So, my goal is, that the user may click the bold-button and then, the text he writes will be bold from wherever the caret was at this point.
The styling has to be set in the inlines of the flow document (because I have to transfer the whole text, including the styling, to another object as xaml string).
At this point, I'm going to post my code. Please note, that this is a simple test project I created to test ways to solve this specific problem.
First the xaml:
<Window x:Class="rtbTest.MainWindow"
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:rtbTest"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto"></RowDefinition>
<RowDefinition Height="180"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<DockPanel
Grid.Row="0"
LastChildFill="False">
<StackPanel
DockPanel.Dock="Left"
Orientation="Horizontal"
Background="Gray">
<TextBlock
Foreground="#000000"
FontWeight="Bold"
VerticalAlignment="Center"
Text="Font"
/>
<ComboBox
x:Name="fonts"
Margin="10,2,20,2"
>
</ComboBox>
<TextBlock
Foreground="#000000"
FontWeight="Bold"
VerticalAlignment="Center"
Text="Size"
/>
<ComboBox
x:Name="fontsize"
Margin="10,2,20,2"
>
</ComboBox>
<ToggleButton
x:Name="bold"
Content="B"
Margin="0,2,5,2"
Width="30">
</ToggleButton>
<ToggleButton
x:Name="italic"
Content="I"
Margin="0,2,5,2"
Width="30">
</ToggleButton>
</StackPanel>
</DockPanel>
<RichTextBox
Name="textbox"
Grid.Row="1" Grid.ColumnSpan="2" >
</RichTextBox>
<ScrollViewer
Grid.Row="2"
Grid.ColumnSpan="2"
Margin="0,10,0,0"
VerticalScrollBarVisibility="Auto">
<StackPanel
Name="entrys"
Background="Black"
>
</StackPanel>
</ScrollViewer>
</Grid>
</Window>
And then the code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using function = System.String;
namespace rtbTest
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.InitializeTextStyling();
}
private void InitializeTextStyling()
{
this.AddFonts();
this.fonts.SelectedIndex = 1;
this.textbox.IsInactiveSelectionHighlightEnabled = true;
this.fonts.SelectionChanged += (s, a) =>
{
if (this.fonts.SelectedIndex != 0)
{
if (this.textbox.Selection.IsEmpty)
{
this.textbox.Document.FontFamily = ((ComboBoxItem)this.fonts.SelectedItem).Content as FontFamily;
}
else
{
this.textbox.Selection.ApplyPropertyValue(TextBlock.FontFamilyProperty, ((ComboBoxItem)this.fonts.SelectedItem).Content as FontFamily);
}
}
};
for (double i = 10; i < 80; i = i + 1)
{
this.fontsize.Items.Add(i);
}
this.fontsize.SelectionChanged += (s, a) =>
{
if (this.textbox.Selection.IsEmpty)
{
this.textbox.Document.FontSize = double.Parse(this.fontsize.SelectedItem.ToString());
}
else
{
this.textbox.Selection.ApplyPropertyValue(TextBlock.FontSizeProperty, double.Parse(this.fontsize.SelectedItem.ToString()));
}
};
this.fontsize.SelectedItem = 40.0;
this.italic.Checked += (s, a) =>
{
if (this.textbox.Selection.IsEmpty)
{
this.textbox.Document.FontStyle = FontStyles.Italic;
}
else
{
this.textbox.Selection.ApplyPropertyValue(TextBlock.FontStyleProperty, FontStyles.Italic);
}
};
this.italic.Unchecked += (s, a) =>
{
if (this.textbox.Selection.IsEmpty)
{
this.textbox.Document.FontStyle = FontStyles.Normal;
}
else
{
this.textbox.Selection.ApplyPropertyValue(TextBlock.FontStyleProperty, FontStyles.Normal);
}
};
this.bold.Checked += (s, a) =>
{
this.textbox.Focus();
if (this.textbox.Selection.IsEmpty)
{
TextPointer tp = this.textbox.CaretPosition;
Run r = new Run("test", tp);
r.FontWeight = FontWeights.Bold;
this.textbox.CaretPosition = r.ElementStart;
r.Text = "";
string fds = XamlWriter.Save(this.textbox.Document);
}
else
{
this.textbox.Selection.ApplyPropertyValue(TextBlock.FontWeightProperty, FontWeights.Heavy);
}
};
this.bold.Unchecked += (s, a) =>
{
if (this.textbox.Selection.IsEmpty)
{
this.textbox.Document.FontWeight = FontWeights.Normal;
}
else
{
this.textbox.Selection.ApplyPropertyValue(TextBlock.FontWeightProperty, FontWeights.Normal);
}
};
FlowDocument fd = new FlowDocument();
fd.FontSize = double.Parse(this.fontsize.SelectedItem.ToString());
fd.FontFamily = ((ComboBoxItem)this.fonts.SelectedItem).Content as FontFamily;
fd.FontWeight = FontWeights.Normal;
this.textbox.Document = fd;
}
private function GetStringFromStream(Stream stream)
{
using (StreamReader r = new StreamReader(stream))
{
return r.ReadToEnd();
}
}
private void AddFonts()
{
//foreach (System.Drawing.FontFamily f in System.Drawing.FontFamily.Families)
//{
// ComboBoxItem item = new ComboBoxItem();
// item.Content = new FontFamily(f.GetName(0));
// item.FontFamily = (FontFamily)item.Content;
// this.fonts.Items.Add(item);
//}
ComboBoxItem item = new ComboBoxItem();
item.Content = new FontFamily("Arial");
item.FontFamily = (FontFamily)item.Content;
this.fonts.Items.Add(item);
item = new ComboBoxItem();
item.Content = new FontFamily("Corbel");
item.FontFamily = (FontFamily)item.Content;
this.fonts.Items.Add(item);
item = new ComboBoxItem();
item.Content = new FontFamily("Gabriola");
item.FontFamily = (FontFamily)item.Content;
this.fonts.Items.Add(item);
item = new ComboBoxItem();
item.Content = new FontFamily("MingLiU - ExtB");
item.FontFamily = (FontFamily)item.Content;
this.fonts.Items.Add(item);
item = new ComboBoxItem();
item.Content = new FontFamily("MV Boli");
item.FontFamily = (FontFamily)item.Content;
this.fonts.Items.Add(item);
item = new ComboBoxItem();
item.Content = new FontFamily("Noto Naskh Arabic UI");
item.FontFamily = (FontFamily)item.Content;
this.fonts.Items.Add(item);
}
}
}
This code should be enough to test straight away.
Now, my problem is in this part:
this.bold.Checked += (s, a) =>
{
this.textbox.Focus();
if (this.textbox.Selection.IsEmpty)
{
TextPointer tp = this.textbox.CaretPosition;
Run r = new Run("test", tp);
r.FontWeight = FontWeights.Bold;
this.textbox.CaretPosition = r.ElementStart;
r.Text = "";
string fds = XamlWriter.Save(this.textbox.Document);
}
else
{
this.textbox.Selection.ApplyPropertyValue(TextBlock.FontWeightProperty, FontWeights.Heavy);
}
};
What i actually need to do, is insert a Run with no text. But if i do this, a Run is inserted in this manner <Run FontWeight="bold" /> instead of <Run FontWeight="bold"></Run>.
I can get the second one (the one I need) when I use the constructor with an initial text like "test" and then I also can set the caret position to the newly created Run. But then i have the text in my RTB, which I don't want. I thought of setting the text in the constructor and later set the text to empty, but if I do so the inserted Run reverts again to the first version and I can't set the caret position inside the Run.
Is there a way to achieve this: insert a new empty run at caret position with the text styled bold and the caret position set inside this new run?
Note that the fds string was set only so I can see the flow document as XAML string while debugging.
I am trying to figure out how to best use WPF's HandOffBehavior technique. Right now, I have a scrolling error marquee in my application that animates opening up, scrolling the error message, and then closing itself.
I was just starting to build this WPF application this week. The problem is that I can't seem to gracefully prepare for a scenario like when the user clicks the Login button twice or more times in small consecutive intervals. I would like to see the error marquee only continue sending the error text across the screen when the user commits such behavior with the login button rather than open and close the marquee multiple redundant times, etc. Here's the relevant code.
MainWindow.xaml.cs:
using System;
using System.Collections.Generic;
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.Navigation;
using System.Windows.Shapes;
using System.Data.Entity;
using System.Windows.Media.Animation;
using PasswordHash;
namespace ChatClient
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void logIn(object sender, RoutedEventArgs e)
{
string nameRecord = "";
string passRecord = "";
if (UsernameField.Text == "" || UserPassField.Password == "")
{
openErrorMarquee("Username and password required");
}
else
{
using (otongadgethubEntities logCheck = new otongadgethubEntities())
{
var userNullCheck = logCheck.users.FirstOrDefault(a => a.username == UsernameField.Text);
if (userNullCheck == null)
{
openErrorMarquee("Username does not exist");
}
if (userNullCheck != null)
{
nameRecord = userNullCheck.username;
}
if (nameRecord == UsernameField.Text)
{
passRecord = Encrypt.MD5(UserPassField.Password).ToLower();
if (passRecord == userNullCheck.password)
{
//Yay! User logged in!
}
else
{
openErrorMarquee("Password invalid");
}
}
}
}
}
private void openErrorMarquee(string errorMessage)
{
errorMarquee.Visibility = System.Windows.Visibility.Visible;
DoubleAnimation openMarquee = new DoubleAnimation();
openMarquee.From = 0;
openMarquee.To = 17;
openMarquee.Duration = new Duration(TimeSpan.FromSeconds(1.0));
openMarquee.Completed += (s, doneEvent) => errorMarqueeScroll(errorMessage);
errorMarquee.BeginAnimation(Rectangle.HeightProperty, openMarquee, HandoffBehavior.Compose);
}
private void errorMarqueeScroll(string errorMessage)
{
errorText.Text = errorMessage;
errorText.Visibility = System.Windows.Visibility.Visible;
double height = errorCanvas.ActualHeight - errorText.ActualHeight;
errorText.Margin = new Thickness(0, height / 2, 0, 0);
DoubleAnimation doubleErrorAnimation = new DoubleAnimation();
doubleErrorAnimation.From = -errorText.ActualWidth;
doubleErrorAnimation.To = errorCanvas.ActualWidth;
//doubleErrorAnimation.RepeatBehavior = RepeatBehavior.Forever;
doubleErrorAnimation.Completed += new EventHandler(closeErrorMarquee);
doubleErrorAnimation.Duration = new Duration(TimeSpan.FromSeconds(7.0));
errorText.BeginAnimation(Canvas.RightProperty, doubleErrorAnimation);
}
private void closeErrorMarquee(object sender, EventArgs e)
{
DoubleAnimation closeMarquee = new DoubleAnimation();
closeMarquee.From = 17;
closeMarquee.To = 0;
closeMarquee.Duration = new Duration(TimeSpan.FromSeconds(1.0));
closeMarquee.Completed += (s, doneEvent) => {
errorMarquee.Visibility = System.Windows.Visibility.Hidden;
errorText.Visibility = System.Windows.Visibility.Hidden;
};
errorMarquee.BeginAnimation(Rectangle.HeightProperty, closeMarquee, HandoffBehavior.Compose);
}
}
}
And here's the XAML for those that need to see the window too:
<Window
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" mc:Ignorable="d" x:Class="ChatClient.MainWindow"
Title="MainWindow" Height="350" Width="525" Icon="media/favicon.gif" Background="#FF3C3636" Foreground="{x:Null}">
<Window.Resources>
<Storyboard x:Key="logolayer2excompsoundfad_mp4"/>
</Window.Resources>
<Window.BorderBrush>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="Black" Offset="0"/>
<GradientStop Color="#FF6F6D95" Offset="1"/>
</LinearGradientBrush>
</Window.BorderBrush>
<Window.Triggers>
<EventTrigger RoutedEvent="FrameworkElement.Loaded">
<BeginStoryboard Storyboard="{StaticResource logolayer2excompsoundfad_mp4}"/>
</EventTrigger>
</Window.Triggers>
<Grid>
<Rectangle x:Name="Menu" Fill="#755E5E83" HorizontalAlignment="Left" Height="273" Margin="35,23,0,0" Stroke="Black" VerticalAlignment="Top" Width="446" RadiusY="27.5" RadiusX="27.5"/>
<Button Content="Log In" HorizontalAlignment="Left" Height="80" Margin="162,200,0,0" Style="{DynamicResource OTonButtonStyle1}" VerticalAlignment="Top" Width="187" FontFamily="Impact" FontSize="26.667" Foreground="#FF1C045B" Click="logIn"/>
<TextBox x:Name="UsernameField" HorizontalAlignment="Left" Height="25" Margin="204,57,0,0" TextWrapping="Wrap" Text="[Username]" VerticalAlignment="Top" Width="193" Background="#BD251E1E" UseLayoutRounding="False" FontFamily="Copperplate Gothic Light" FontSize="16">
<TextBox.Foreground>
<LinearGradientBrush EndPoint="0.5,1" MappingMode="RelativeToBoundingBox" StartPoint="0.5,0">
<GradientStop Color="#FF1E2E95" Offset="0.5"/>
<GradientStop Color="White" Offset="1"/>
</LinearGradientBrush>
</TextBox.Foreground>
</TextBox>
<TextBlock HorizontalAlignment="Left" Height="16" Margin="98,57,0,0" TextWrapping="Wrap" Text="Username:" VerticalAlignment="Top" Width="101" FontFamily="Copperplate Gothic Light" FontSize="16">
<TextBlock.Foreground>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FF0A1D5F" Offset="0.374"/>
<GradientStop Color="#FF6E7FB9" Offset="1"/>
</LinearGradientBrush>
</TextBlock.Foreground>
</TextBlock>
<PasswordBox x:Name="UserPassField" HorizontalAlignment="Left" Height="25" Margin="204,99,0,0" VerticalAlignment="Top" Width="193" Background="#BD251E1E" UseLayoutRounding="False" FontFamily="Copperplate Gothic Light" FontSize="16">
<PasswordBox.Foreground>
<LinearGradientBrush EndPoint="0.5,1" MappingMode="RelativeToBoundingBox" StartPoint="0.5,0">
<GradientStop Color="#FF1E2E95" Offset="0.5"/>
<GradientStop Color="White" Offset="1"/>
</LinearGradientBrush>
</PasswordBox.Foreground>
</PasswordBox>
<TextBlock HorizontalAlignment="Left" Height="16" Margin="98,99,0,0" TextWrapping="Wrap" Text="Password:" VerticalAlignment="Top" Width="101" FontFamily="Copperplate Gothic Light" FontSize="16">
<TextBlock.Foreground>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FF0A1D5F" Offset="0.374"/>
<GradientStop Color="#FF6E7FB9" Offset="1"/>
</LinearGradientBrush>
</TextBlock.Foreground>
</TextBlock>
<Canvas ClipToBounds="True" Name="errorCanvas" Width="446" Height="17" Margin="36,152,35,151">
<Rectangle x:Name="errorMarquee" Fill="#FF0A0A0C" HorizontalAlignment="Left" Height="17" Stroke="#FF5B1D1D" VerticalAlignment="Top" Width="446" Canvas.Left="-1" Visibility="Hidden"/>
<TextBlock x:Name="errorText" HorizontalAlignment="Left" Height="16" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="690" FontFamily="Copperplate Gothic Bold" FontSize="16" Foreground="#FF7E0202" Visibility="Hidden"/>
</Canvas>
</Grid>
</Window>
Anyone have any suggestions, perhaps?
you can just use one flag to check this
private static flag = true;
private void logIn(object sender, RoutedEventArgs e)
{
if(flag){
flag=false;
string nameRecord = "";
string passRecord = "";
if (UsernameField.Text == "" || UserPassField.Password == "")
{
openErrorMarquee("Username and password required");
}
else
{
using (otongadgethubEntities logCheck = new otongadgethubEntities())
{
var userNullCheck = logCheck.users.FirstOrDefault(a => a.username == UsernameField.Text);
if (userNullCheck == null)
{
openErrorMarquee("Username does not exist");
}
if (userNullCheck != null)
{
nameRecord = userNullCheck.username;
}
if (nameRecord == UsernameField.Text)
{
passRecord = Encrypt.MD5(UserPassField.Password).ToLower();
if (passRecord == userNullCheck.password)
{
//Yay! User logged in!
}
else
{
openErrorMarquee("Password invalid");
}
}
}
}
}
else
{
openErrorMarquee("you pressed more one time");
}
}
You can use StopWatch to check fast clicks. In code example given below, try pressing button slow and fast.
Stopwatch w = new Stopwatch();
long milliseconds_prev = 0;
private void Button_Click(object sender, RoutedEventArgs e)
{
if (_checkFastClicks())
{
Debug.WriteLine("Fast click");
}
else
Debug.WriteLine("Slow click");
}
bool _checkFastClicks()
{
bool result = false;
if (!w.IsRunning)
{
w.Start();
}
if (w.IsRunning)
{
if (w.ElapsedMilliseconds - milliseconds_prev < 500)//imp
{
if (w.ElapsedMilliseconds > 0)
{
milliseconds_prev = w.ElapsedMilliseconds;
result = true;
}
else
result = false;
}
else
{
milliseconds_prev = 0;
w.Reset();
w.Stop();
result = false;
}
}
return result;
}
I am trying to make Alphabetically searching of records via accessing rest services in windows phone 7.
Design page code..
<controls:PivotItem Header="buddies">
<toolkit:LongListSelector x:Name="BookList" Background="Transparent" IsFlatList="true"
GroupViewOpened="LongListSelector_GroupViewOpened"
GroupViewClosing="LongListSelector_GroupViewClosing">
<toolkit:LongListSelector.GroupItemsPanel>
<ItemsPanelTemplate>
<toolkit:WrapPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</toolkit:LongListSelector.GroupItemsPanel>
<toolkit:LongListSelector.GroupItemTemplate>
<DataTemplate>
<Border Background="{Binding Converter={StaticResource GroupBackground}}"
Width="99" Height="99" Margin="6" IsHitTestVisible="{Binding HasItems}">
<TextBlock Text="{Binding Title}"
FontFamily="{StaticResource PhoneFontFamilySemiBold}"
FontSize="48"
Margin="8,0,0,0"
Foreground="{Binding Converter={StaticResource GroupForeground}}"
VerticalAlignment="Bottom"/>
<Border.Projection>
<PlaneProjection RotationX="-60"/>
</Border.Projection>
</Border>
</DataTemplate>
</toolkit:LongListSelector.GroupItemTemplate>
<toolkit:LongListSelector.GroupHeaderTemplate>
<DataTemplate>
<Border Background="Transparent" Margin="12,8,0,8">
<Border Background="{StaticResource PhoneAccentBrush}"
Padding="8,0,0,0" Width="62" Height="62"
HorizontalAlignment="Left">
<TextBlock Text="{Binding Title}"
Foreground="#FFFFFF"
FontSize="48"
FontFamily="{StaticResource PhoneFontFamilySemiLight}"
HorizontalAlignment="Left"
VerticalAlignment="Bottom"/>
</Border>
</Border>
</DataTemplate>
</toolkit:LongListSelector.GroupHeaderTemplate>
<toolkit:LongListSelector.ItemTemplate>
<DataTemplate>
<Grid Margin="12,8,0,8">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Image Width="110" Height="150" Source="{Binding ImageUrl}" VerticalAlignment="Top"/>
<StackPanel Grid.Column="1" VerticalAlignment="Top">
<TextBlock Text="{Binding AutherName}" Style="{StaticResource PhoneTextLargeStyle}" FontFamily="{StaticResource PhoneFontFamilySemiBold}" Margin="12,-12,12,6"/>
<TextBlock Text="{Binding Email}" Style="{StaticResource PhoneTextNormalStyle}" TextWrapping="Wrap" FontFamily="{StaticResource PhoneFontFamilySemiBold}"/>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Title:" Style="{StaticResource PhoneTextSmallStyle}"/>
<TextBlock Text="{Binding Title}" Style="{StaticResource PhoneTextSmallStyle}" FontFamily="{StaticResource PhoneFontFamilySemiBold}"/>
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Price:" Style="{StaticResource PhoneTextSmallStyle}"/>
<TextBlock Text="{Binding Price}" Style="{StaticResource PhoneTextSmallStyle}" FontFamily="{StaticResource PhoneFontFamilySemiBold}"/>
</StackPanel>
</StackPanel>
</Grid>
</DataTemplate>
</toolkit:LongListSelector.ItemTemplate>
</toolkit:LongListSelector>
</controls:PivotItem>
</controls:Pivot>
</Grid>
Here is my MainPage.xaml.cs page code
private LongListSelector currentSelector;
List<Person> objperson = null;
// Constructor
public MainPage()
{
InitializeComponent();
string Categoryid = "2";
WebClient proxy = new WebClient();
proxy.DownloadStringAsync(new Uri("http://localhost:3160/Service1.svc/GetListItemDetail/" + Categoryid));
proxy.DownloadStringCompleted += new DownloadStringCompletedEventHandler(proxy_DownloadStringCompleted);
}
void proxy_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
XDocument doc = XDocument.Load(new StringReader(e.Result));
var CatList = (from item in doc.Descendants("ItemDetail")
select new Person
{
GenreName = item.Element("GenreName").Value.ToString(),
ItemID = Convert.ToInt32(item.Element("ItemID").Value),
CatID = Convert.ToInt32(item.Element("CatID").Value),
GenreID = Convert.ToInt32(item.Element("GenreID").Value),
AutherName = item.Element("AutherName").Value.ToString(),
Title = item.Element("Title").Value.ToString(),
Email = item.Element("Email").Value.ToString(),
Price = item.Element("Price").Value.ToString(),
Description = item.Element("Description").Value.ToString(),
ImageUrl = item.Element("ImageUrl").Value.ToString()
}).ToList();
objperson = new List<Person>();
objperson = CatList;
BookList.ItemsSource = CatList;
}
}
public List<Person> GetPersonListInfo()
{
List<Person> objp = new List<Person>();
objp = objperson;
return objp;
}
private void LongListSelector_GroupViewOpened(object sender, GroupViewOpenedEventArgs e)
{
//Hold a reference to the active long list selector.
currentSelector = sender as LongListSelector;
//Construct and begin a swivel animation to pop in the group view.
IEasingFunction quadraticEase = new QuadraticEase { EasingMode = EasingMode.EaseOut };
Storyboard _swivelShow = new Storyboard();
ItemsControl groupItems = e.ItemsControl;
foreach (var item in groupItems.Items)
{
UIElement container = groupItems.ItemContainerGenerator.ContainerFromItem(item) as UIElement;
if (container != null)
{
Border content = VisualTreeHelper.GetChild(container, 0) as Border;
if (content != null)
{
DoubleAnimationUsingKeyFrames showAnimation = new DoubleAnimationUsingKeyFrames();
EasingDoubleKeyFrame showKeyFrame1 = new EasingDoubleKeyFrame();
showKeyFrame1.KeyTime = TimeSpan.FromMilliseconds(0);
showKeyFrame1.Value = -60;
showKeyFrame1.EasingFunction = quadraticEase;
EasingDoubleKeyFrame showKeyFrame2 = new EasingDoubleKeyFrame();
showKeyFrame2.KeyTime = TimeSpan.FromMilliseconds(85);
showKeyFrame2.Value = 0;
showKeyFrame2.EasingFunction = quadraticEase;
showAnimation.KeyFrames.Add(showKeyFrame1);
showAnimation.KeyFrames.Add(showKeyFrame2);
Storyboard.SetTargetProperty(showAnimation, new PropertyPath(PlaneProjection.RotationXProperty));
Storyboard.SetTarget(showAnimation, content.Projection);
_swivelShow.Children.Add(showAnimation);
}
}
}
_swivelShow.Begin();
}
private void LongListSelector_GroupViewClosing(object sender, GroupViewClosingEventArgs e)
{
//Cancelling automatic closing and scrolling to do it manually.
e.Cancel = true;
if (e.SelectedGroup != null)
{
currentSelector.ScrollToGroup(e.SelectedGroup);
}
//Dispatch the swivel animation for performance on the UI thread.
Dispatcher.BeginInvoke(() =>
{
//Construct and begin a swivel animation to pop out the group view.
IEasingFunction quadraticEase = new QuadraticEase { EasingMode = EasingMode.EaseOut };
Storyboard _swivelHide = new Storyboard();
ItemsControl groupItems = e.ItemsControl;
foreach (var item in groupItems.Items)
{
UIElement container = groupItems.ItemContainerGenerator.ContainerFromItem(item) as UIElement;
if (container != null)
{
Border content = VisualTreeHelper.GetChild(container, 0) as Border;
if (content != null)
{
DoubleAnimationUsingKeyFrames showAnimation = new DoubleAnimationUsingKeyFrames();
EasingDoubleKeyFrame showKeyFrame1 = new EasingDoubleKeyFrame();
showKeyFrame1.KeyTime = TimeSpan.FromMilliseconds(0);
showKeyFrame1.Value = 0;
showKeyFrame1.EasingFunction = quadraticEase;
EasingDoubleKeyFrame showKeyFrame2 = new EasingDoubleKeyFrame();
showKeyFrame2.KeyTime = TimeSpan.FromMilliseconds(125);
showKeyFrame2.Value = 90;
showKeyFrame2.EasingFunction = quadraticEase;
showAnimation.KeyFrames.Add(showKeyFrame1);
showAnimation.KeyFrames.Add(showKeyFrame2);
Storyboard.SetTargetProperty(showAnimation, new PropertyPath(PlaneProjection.RotationXProperty));
Storyboard.SetTarget(showAnimation, content.Projection);
_swivelHide.Children.Add(showAnimation);
}
}
}
_swivelHide.Completed += _swivelHide_Completed;
_swivelHide.Begin();
});
}
private void _swivelHide_Completed(object sender, EventArgs e)
{
//Close group view.
if (currentSelector != null)
{
currentSelector.CloseGroupView();
currentSelector = null;
}
}
I am new to windows phone 7 application development, no idea about grouping of alphabets in Longlistselector. Please help me in that. Thanks in advance.
There is code I used once for grouping. As you can see, it's similar to Claus's:
public class YourList : ObservableCollection<ItemsInGroup>
{
private static readonly string Groups = "#abcdefghijklmnopqrstuvwxyz";
Dictionary<string, ItemsInGroup> groups = new Dictionary<string, ItemsInGroup>();
public YourList()
{
foreach (char c in Groups)
{
ItemsInGroup group = new ItemsInGroup(c.ToString());
this.Add(group);
groups[c.ToString()] = group;
}
}
public void AddItem(Item item)
{
string GroupKey = Item.GetSomeFieldKey(item);// a, b, etc.
for (int i = 0; i < groups[GroupKey].Count; i++)
{
if (Item.CompareBySomeField(item, groups[GroupKey][i]) < 0)
{
groups[Item.GetSomeFilesKey(item)].Insert(i, item);
return;
}
}
groups[GroupKey].Add(item);
}
}
.
public class ItemsInGroup : ObservableCollection<Item>, INotifyPropertyChanged
{
public ItemsInGroup(string category)
{
Key = category;
}
public string Key { get; set; }
public bool HasItems { get { return Count > 0; } }
//INotifyPropertyChanged implementation
}
Item must implement:
public static string GetSomeFieldKey(Item item)
and
public static int CompareBySomeFields(object obj1, object obj2)
Usage:
YourList list = new YourList();
foreach (var item in resultListFromService)
{
list.AddItem(item); // fill list with items
}
myList.ItemsSource = list; // bind to UI
Hope this helps better understand how it works
A super easy way to do it, is to use a specialized collection for the LongListSelector. I just so happen to have written one
Basically you would change your code to the following:
BookList.ItemsSource = new LongListCollection<Person, char>(CatList, x => x.Title[0]));
And you would get the alphabetic grouping on the first character of the Title property.
The only detail you need to be aware of, is that your Person class would need to implement IComparable<Person> to be ordered by the Title property (because you do want sorting, right?)
Simply done as:
public int Compare(Person other)
{
if (other == null)
return 1;
return this.Title.CompareTo(other.Title);
}
I am developing an application based on OptiTrack SDK (from NaturalPoint). I need to run the application window as "Always on Top". The window is designed in XAML and is controled in the class "CameraView" but it does not seem to include a "TopMost" property or equivalent. Attached are the code of "CameraView.xaml.cs" and the code of "CameraView.xaml" that are part of OptiTrack SDK (NaturalPoint) called "Single_Camera_CSharp_.NET_3.0".
One could expect the class CameraView to contain properties or members to set the position of the window on the screen or to set it to TopMost but as far as searched I found nothing. I wonder what I should do.
Thank you,
Brian
================
"CameraView.xaml.cs"
using System;
using System.IO;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Windows.Threading;
namespace TestProject
{
public partial class CameraView
{
private const int NP_OPTION_OBJECT_COLOR_OPTION = 3;
private const int NP_OPTION_VIDEO_TYPE = 48;
private const int NP_OPTION_NUMERIC_DISPLAY_ON = 71;
private const int NP_OPTION_NUMERIC_DISPLAY_OFF = 72;
private const int NP_OPTION_FETCH_RLE = 73;
private const int NP_OPTION_FETCH_GRAYSCALE = 74;
private const int NP_OPTION_FRAME_DECIMATION = 52;
private const int NP_OPTION_INTENSITY = 50;
private const int NP_OPTION_SEND_EMPTY_FRAMES = 41;
private const int NP_OPTION_THRESHOLD = 5;
private const int NP_OPTION_EXPOSURE = 46;
private const int NP_OPTION_SEND_FRAME_MASK = 73;
private const int NP_OPTION_TEXT_OVERLAY_OPTION = 74;
// public delegate void OnCameraViewCreate(CameraView camera);
// public static OnCameraViewCreate onCameraViewCreate;
private System.Drawing.Bitmap raw = new System.Drawing.Bitmap(353, 288, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
private int mFrameCounter;
private int mDisplayCounter;
private DispatcherTimer timer1 = new DispatcherTimer();
private bool mVideoFrameAvailable = false;
private int mNumeric = -1;
private bool mGreyscale = false;
private bool mOverlay = true;
public CameraView()
{
this.InitializeComponent();
timer1.Interval = new TimeSpan(0, 0, 0, 0, 10);
timer1.Tick += new EventHandler(timer1_Tick);
}
public int Numeric
{
get { return mNumeric; }
set
{
mNumeric = value % 100;
if (mNumeric >= 0)
{
if (Camera != null)
Camera.SetOption(NP_OPTION_NUMERIC_DISPLAY_ON, value % 100);
}
}
}
private bool CameraRunning = false;
private OptiTrack.NPCamera mCamera;
public OptiTrack.NPCamera Camera
{
get { return mCamera; }
set
{
if (mCamera == value) return; //== Don't do anything if you're assigning the same camera ==
if (mCamera != null)
{
//== Shut the selected camera down ==<<
if (CameraRunning)
{
CameraRunning = false;
mCamera.Stop();
mCamera.FrameAvailable -= FrameAvailable;
}
}
mCamera = value;
if (mCamera == null)
{
mNumeric = -1;
}
else
{
serialLabel.Content = "Camera "+mCamera.SerialNumber.ToString(); //mNumeric.ToString();
}
}
}
private void FrameAvailable(OptiTrack.NPCamera Camera)
{
mFrameCounter++;
try
{
OptiTrack.NPCameraFrame frame = Camera.GetFrame(0);
int id = frame.Id;
if (CameraRunning)
{
GetFrameData(Camera, frame);
}
frame.Free();
}
catch (Exception)
{
int r = 0;
r++;
}
}
private void GetFrameData(OptiTrack.NPCamera camera, OptiTrack.NPCameraFrame frame)
{
BitmapData bmData = raw.LockBits(new System.Drawing.Rectangle(0, 0, raw.Width, raw.Height),
ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
int stride = bmData.Stride;
System.IntPtr bufferPtr = bmData.Scan0;
unsafe
{
byte* buffer = (byte*)(void*)bufferPtr;
camera.GetFrameImage(frame, bmData.Width, bmData.Height, bmData.Stride, 32, ref buffer[0]);
}
raw.UnlockBits(bmData);
mVideoFrameAvailable = true;
}
private void timer1_Tick(object sender, EventArgs e)
{
if (CameraRunning && mVideoFrameAvailable)
{
mVideoFrameAvailable = false;
cameraImage.Source = Img(raw);
mDisplayCounter++;
}
}
private System.Windows.Media.ImageSource Img(System.Drawing.Bitmap img)
{
System.Drawing.Imaging.BitmapData bmData = img.LockBits(new System.Drawing.Rectangle(0, 0, img.Width, img.Height),
System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);
System.Windows.Media.Imaging.BitmapSource bitmap = System.Windows.Media.Imaging.BitmapSource.Create(
img.Width, img.Height, 96, 96, PixelFormats.Bgra32,
System.Windows.Media.Imaging.BitmapPalettes.WebPalette,
bmData.Scan0, bmData.Stride * bmData.Height, bmData.Stride);
img.UnlockBits(bmData);
return bitmap;
}
private void startStopButton_Click(object sender, RoutedEventArgs e)
{
if (CameraRunning)
StopCamera();
else
StartCamera();
}
public void StartCamera()
{
if (Camera != null)
{
mFrameCounter = 0;
mDisplayCounter = 0;
Camera.FrameAvailable += FrameAvailable;
Camera.SetOption(NP_OPTION_VIDEO_TYPE, 0);
Camera.SetOption(NP_OPTION_FRAME_DECIMATION, 1);
Camera.SetOption(NP_OPTION_INTENSITY, 0);
Camera.SetOption(NP_OPTION_EXPOSURE, 10);
Camera.SetOption(NP_OPTION_THRESHOLD, 50);
Camera.SetOption(NP_OPTION_OBJECT_COLOR_OPTION, 0);
SetOverlayOption();
SetGreyscaleOption();
timer1.Start();
Camera.Start();
CameraRunning = true;
this.Numeric = mNumeric;
startStopButton.Content = "Stop Camera";
}
}
private void SetGreyscaleOption()
{
if(mGreyscale)
Camera.SetOption(NP_OPTION_VIDEO_TYPE, 1);
else
Camera.SetOption(NP_OPTION_VIDEO_TYPE, 0);
}
private void SetOverlayOption()
{
if(mOverlay)
Camera.SetOption(NP_OPTION_TEXT_OVERLAY_OPTION, 255);
else
Camera.SetOption(NP_OPTION_TEXT_OVERLAY_OPTION, 0);
}
public void StopCamera()
{
if (Camera != null)
{
Camera.Stop();
timer1.Stop();
CameraRunning = false;
Camera.FrameAvailable -= FrameAvailable;
Camera.SetOption(NP_OPTION_NUMERIC_DISPLAY_OFF, 0);
startStopButton.Content = "Start Camera";
}
}
private void greyscaleButton_Click(object sender, RoutedEventArgs e)
{
if(mGreyscale)
mGreyscale = false;
else
mGreyscale = true;
SetGreyscaleOption();
}
private void OverlayButton_Click(object sender, RoutedEventArgs e)
{
if(mOverlay)
mOverlay = false;
else
mOverlay = true;
SetOverlayOption();
}
private void exposureSlider_ValueChanged(object sender, RoutedEventArgs e)
{
if (mCamera!=null)
{
mCamera.SetOption(NP_OPTION_EXPOSURE, (int) this.exposureSlider.Value);
}
}
private void thresholdSlider_ValueChanged(object sender, RoutedEventArgs e)
{
if (mCamera != null)
{
mCamera.SetOption(NP_OPTION_THRESHOLD, (int)this.thresholdSlider.Value);
}
}
private void optionsButton_Click(object sender, RoutedEventArgs e)
{
if (!propertyPanel.IsVisible)
propertyPanel.Visibility = Visibility.Visible;
else
propertyPanel.Visibility = Visibility.Collapsed;
}
}
}
================
"CameraView.xaml"
<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="TestProject.CameraView"
x:Name="CameraView1"
Width="Auto" Height="Auto"
xmlns:d="http://schemas.microsoft.com/expression/blend/2006"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
>
<Grid x:Name="LayoutRoot" Width="Auto" Height="Auto">
<Grid.Background>
<x:Null/>
</Grid.Background>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="113.904"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="26.667"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid Margin="0,0,0,0" Grid.ColumnSpan="2">
<Rectangle RadiusX="1.25" RadiusY="1.25" Margin="0,0,0,0" VerticalAlignment="Stretch">
<Rectangle.Fill>
<LinearGradientBrush EndPoint="0.492,0.149" StartPoint="0.492,0.843">
<GradientStop Color="#FF000000" Offset="0"/>
<GradientStop Color="#FF23283F" Offset="1"/>
</LinearGradientBrush>
</Rectangle.Fill>
<Rectangle.Stroke>
<LinearGradientBrush EndPoint="0.291,-4.231" StartPoint="1.668,18.025">
<GradientStop Color="#FF000000" Offset="0"/>
<GradientStop Color="#FFFFFFFF" Offset="1"/>
</LinearGradientBrush>
</Rectangle.Stroke>
</Rectangle>
<Rectangle RadiusX="3.333" RadiusY="3.333" Opacity="0.13" Margin="0,0,0,13">
<Rectangle.Fill>
<SolidColorBrush Color="#FFFFFFFF"/>
</Rectangle.Fill>
<Rectangle.Stroke>
<x:Null/>
</Rectangle.Stroke>
</Rectangle>
</Grid>
<Image Margin="0,0,0,0" x:Name="cameraImage" Grid.ColumnSpan="2" Grid.Row="1"/>
<Label x:Name="serialLabel" FontSize="10" FontWeight="Bold" Foreground="#FFDEDADA" Content="Camera 10024" HorizontalAlignment="Right" Margin="0,0,4,0" VerticalAlignment="Top" Grid.Column="1">
<Label.BitmapEffect>
<OuterGlowBitmapEffect GlowColor="#FF000000" GlowSize="4" Opacity="0.7"/>
</Label.BitmapEffect>
</Label>
<WrapPanel Margin="3,3,3,3">
<Button HorizontalAlignment="Stretch" Margin="0,0,0,0" x:Name="startStopButton" Width="100" Height="Auto" BorderThickness="0,0,0,0" Content="Start Camera" Click="startStopButton_Click"/>
<Button x:Name="optionsButton" Width="61.474" Height="Auto" BorderThickness="0,0,0,0" Content="Options" Click="optionsButton_Click"/>
</WrapPanel>
<Grid Visibility="Visible" d:LayoutOverrides="HorizontalAlignment, VerticalAlignment" HorizontalAlignment="Right" Margin="0,0,16,16" x:Name="propertyPanel" VerticalAlignment="Bottom" Width="169.237" Height="81.455" Grid.ColumnSpan="2" Grid.Row="1">
<Rectangle Stroke="#FFFFFFFF" StrokeThickness="3" Margin="0,0,0,0">
<Rectangle.BitmapEffect>
<DropShadowBitmapEffect/>
</Rectangle.BitmapEffect>
<Rectangle.Fill>
<LinearGradientBrush EndPoint="1,0.5" StartPoint="0,0.5">
<GradientStop Color="#FF1E212F" Offset="0"/>
<GradientStop Color="#FF313551" Offset="1"/>
</LinearGradientBrush>
</Rectangle.Fill>
</Rectangle>
<Slider HorizontalAlignment="Stretch" Margin="62.633,5,4.681,0" x:Name="exposureSlider" VerticalAlignment="Top" Width="Auto" Height="Auto" Orientation="Horizontal" Maximum="255" ValueChanged="exposureSlider_ValueChanged"/>
<Label x:Name="serialLabel_Copy" FontSize="10" FontWeight="Bold" Foreground="#FFDEDADA" Content="Exposure" HorizontalAlignment="Left" Margin="3.853,3.853,0,0" VerticalAlignment="Top" Width="57.352">
<Label.BitmapEffect>
<OuterGlowBitmapEffect GlowColor="#FF000000" GlowSize="4" Opacity="0.7"/>
</Label.BitmapEffect>
</Label>
<Label x:Name="serialLabel_Copy1" FontSize="10" FontWeight="Bold" Foreground="#FFDEDADA" Content="Threshold" d:LayoutOverrides="Height" HorizontalAlignment="Left" Margin="3.853,27.691,0,0" VerticalAlignment="Top" Width="59.829">
<Label.BitmapEffect>
<OuterGlowBitmapEffect GlowColor="#FF000000" GlowSize="4" Opacity="0.7"/>
</Label.BitmapEffect>
</Label>
<Slider x:Name="thresholdSlider" Width="Auto" Orientation="Horizontal" Maximum="253" d:LayoutOverrides="Height, Margin" Margin="62.633,27.691,4.681,0" VerticalAlignment="Top" Minimum="54" Value="54" ValueChanged="thresholdSlider_ValueChanged"/>
<Button x:Name="greyScaleButton" Width="75.333" Content="Greyscale" Click="greyscaleButton_Click" HorizontalAlignment="Left" Height="21" d:LayoutOverrides="Height" Margin="8,53.761,0,0" VerticalAlignment="Top"/>
<Button x:Name="Overlay" Height="21" Content="Overlay" Click="OverlayButton_Click" d:LayoutOverrides="Height" HorizontalAlignment="Right" Margin="0,53.761,8,0" VerticalAlignment="Top" Width="64"/>
</Grid>
</Grid>
</UserControl>
The Topmost property exists on the Window class: http://msdn.microsoft.com/en-us/library/system.windows.window.topmost.aspx.
Your CameraView class is derived from UserControl, which is a kind of control that sits inside a Window (or other container such as a Page, but that's not important here). UserControl doesn't have a Topmost property because it doesn't appear independently on the desktop.
Host your CameraView in a Window and set the Window.Topmost:
<!-- MyWindow.xaml -->
<Window ...
xmlns:local="clr-namespace:TestProject"
Topmost="True">
<local:CameraView />
</Window>
where the ellipses represent the default gunk like x:Class and WPF xmlns declarations that Visual Studio creates for you.
In the UserControl code behind, you can get a reference to the window that is hosting it, then set the Topmost property. Example,
Window parent = Window.GetWindow(this);
parent.Topmost = true;
This is UserControl. You can set TopMost property for Windows only