I'm new to Windows Phone programming. I want to create a gridview like the following:
I've done the <DataTemplate>, so I've already done the items and their buttons. But I can't set 2 columns for the grid using MaximumRowsOrColumns, because it limits my grid with only 2 rows (can be ilimited rows, but I need to have only 2 columns).
Coding as below was the closest I made:
<GridView.ItemsPanel>
<ItemsPanelTemplate>
<ItemsWrapGrid Orientation="Vertical" MaximumRowsOrColumns="2"/>
</ItemsPanelTemplate>
</GridView.ItemsPanel>
EDIT: added <DataTemplate>code:
<DataTemplate x:Key="gridClassItem">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="14.96"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="14.96" />
</Grid.ColumnDefinitions>
<Button x:Name="btnItem" Grid.Row="0" Grid.Column="0"
BorderThickness="0 0 0 2" Opacity="100"
Height="70.4" Width="174.24"
Background="#FF6B33"
Click="btnItem_OnClick">
<TextBlock x:Name="txtItem" FontSize="38" Foreground="#5B1F08" Opacity="100" Margin="0" Text="{Binding Name}" TextAlignment="Center"/>
</Button>
<Grid Grid.Row="1" Grid.Column="0" Margin="0, -8, 0, 0" Height="52.8">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="86.24"/>
<ColumnDefinition Width="86.24"/>
</Grid.ColumnDefinitions>
<Button x:Name="btn1" Click="btn1_OnClick"
Grid.Row="0" Grid.Column="0"
BorderBrush="#FFFFFF" BorderThickness="0 0 1.76 0"
Margin="-10, -15, 0, 0"
DataContext="{Binding}">
<Button.Background>
<ImageBrush ImageSource="\Assets\bt1.png" Stretch="UniformToFill"/>
</Button.Background>
</Button>
<Button x:Name="btn2" Click="btn2_OnClick"
Grid.Row="0" Grid.Column="1"
BorderBrush="#FFFFFF" BorderThickness="1.76 0 0 0"
Margin="0, -15, -2.5, 0"
DataContext="{Binding}">
<Button.Background>
<ImageBrush ImageSource="\Assets\bt2.png" Stretch="UniformToFill"/>
</Button.Background>
</Button>
</Grid>
<Rectangle Grid.Row="2" Grid.Column="1" Fill="#FFFFFF" Margin="0"/>
</Grid>
</DataTemplate>
Any suggestions?
By the way, any idea how could i change the GridViewItem's background color? I was thinking about a geometric series, like the first item will be orange, the followings - always counting by two - will be green and then orange again. But I don't know how to implement it.
Well, since I couldn't find a way to do it using XAML, I did it at C#. Below is my solution, if someone need something looked like:
enum GridItemColor
{
NONE,
BLUE,
RED
};
//Some event to populate a list
...
myGrid.Items.Clear();
GridItemColor lastColor = GridItemColor.NONE;
foreach (MyModel item in myList)
{
if (lastColor == GridItemColor.NONE || lastColor == GridItemColor.BLUE)
{
myGrid.Items.Add(FormatGridViewItem(item, GridItemColor.RED));
lastColor = GridItemColor.RED;
}
else if (lastColor == GridItemColor.RED)
{
myGrid.Items.Add(FormatGridViewItem(item, GridItemColor.BLUE));
lastColor = GridItemColor.BLUE;
}
}
...
private Grid FormatGridViewItem(MyModel currentItem, GridItemColor itemColor)
{
Grid gridItem = new Grid();
#region Grid Item Row Definition and GridItem Setup
RowDefinition itemRowDef = new RowDefinition();
RowDefinition minorButtonRowDef = new RowDefinition();
itemRowDef.Height = new GridLength(72);
minorButtonRowDef.Height = new GridLength(49);
gridItem.RowDefinitions.Add(classPlanRowDef);
gridItem.RowDefinitions.Add(minorButtonRowDef);
gridItem.MaxWidth = 196;
gridItem.Width = 196;
gridItem.Margin = new Thickness(0, 0, 24, 24);
#endregion
#region Button Item
Button btnItem = new Button();
btnItem.BorderThickness = new Thickness(0);
btnItem.Margin = new Thickness(-3, 0, 0, 0);
btnItem.Opacity = 100;
btnItem.MaxWidth = 203;
btnItem.MinWidth = 203;
btnItem.Height = 78;
btnItem.DataContext = currentItem;
if (itemColor == GridItemColor.RED)
btnItem.Background = new SolidColorBrush(Windows.UI.Color.FromArgb(0xFF, 255, 107, 51));
else
btnItem.Background = new SolidColorBrush(Windows.UI.Color.FromArgb(0xFF, 23, 229, 192));
btnItem.Click += btnItem_Click;
TextBlock txtItem = new TextBlock();
txtItem.FontSize = 40;
if (itemColor == GridItemColor.RED)
txtItem.Foreground = new SolidColorBrush(Windows.UI.Color.FromArgb(0xFF, 91, 31, 8));
else
txtItem.Foreground = new SolidColorBrush(Windows.UI.Color.FromArgb(0xFF, 3, 97, 80));
txtItem.Opacity = 100;
txtItem.TextAlignment = TextAlignment.Center;
txtItem.Text = currentItem.Name;
txtItem.TextTrimming = TextTrimming.CharacterEllipsis;
btnItem.Content = txtItem;
gridItem.Children.Add(btnItem);
Grid.SetRow(btnItem, 0);
#endregion
#region Grid Minor Buttons Row
Grid minorButtonsRow = new Grid();
minorButtonsRow.Margin = new Thickness(0);
if (itemColor == GridItemColor.RED)
minorButtonsRow.Background = new SolidColorBrush(Windows.UI.Color.FromArgb(0xFF, 255, 107, 51));
else
minorButtonsRow.Background = new SolidColorBrush(Windows.UI.Color.FromArgb(0xFF, 23, 229, 192));
ColumnDefinition btnOneColumnDef = new ColumnDefinition();
ColumnDefinition btnTwoColumnDef = new ColumnDefinition();
btnOneColumnDef.Width = new GridLength(98);
btnTwoColumnDef.Width = new GridLength(98);
minorButtonsRow.ColumnDefinitions.Add(btnOneColumnDef);
minorButtonsRow.ColumnDefinitions.Add(btnTwoColumnDef);
// Button One
Button btnOne = new Button();
btnOne.BorderBrush = new SolidColorBrush(Windows.UI.Color.FromArgb(0xFF, 255, 255, 255));
btnOne.BorderThickness = new Thickness(0);
btnOne.MinWidth = 97;
btnOne.MaxWidth = 97;
btnOne.MinHeight = 48;
btnOne.MaxHeight = 48;
btnOne.Margin = new Thickness(0, 0, 1, 0);
btnOne.DataContext = currentItem;
btnOne.Click += btnOne_Click;
ImageBrush imgOne = new ImageBrush();
BitmapImage bitImg;
if (itemColor == GridItemColor.RED)
{
bitImg = new BitmapImage(new Uri("ms-appx:/Assets/Icons/btOneRED.png", UriKind.RelativeOrAbsolute));
btnOne.Style = (Style)this.Resources["btnOneRedStyle"];
}
else
{
bitImg = new BitmapImage(new Uri("ms-appx:/Assets/Icons/btOneBLUE.png", UriKind.RelativeOrAbsolute));
btnOne.Style = (Style)this.Resources["btnOneBlueStyle"];
}
imgOne.ImageSource = bitImg;
imgOne.Stretch = Stretch.UniformToFill;
btnOne.Background = imgOne;
minorButtonsRow.Children.Add(btnOne);
Grid.SetRow(btnOne, 0);
Grid.SetColumn(btnOne, 0);
// END Button One
// Button Two
Button btnTwo = new Button();
btnTwo.BorderBrush = new SolidColorBrush(Windows.UI.Color.FromArgb(0xFF, 255, 255, 255));
btnTwo.BorderThickness = new Thickness(0);
btnTwo.MinWidth = 97;
btnTwo.MaxWidth = 97;
btnTwo.MinHeight = 48;
btnTwo.MaxHeight = 48;
btnTwo.Margin = new Thickness(1, 0, 0, 0);
btnTwo.DataContext = currentItem;
btnTwo.Click += btnTwo_Click;
ImageBrush imgTwo = new ImageBrush();
BitmapImage bitImgTwo;
if (itemColor == GridItemColor.RED)
{
bitImgTwo = new BitmapImage(new Uri("ms-appx:/Assets/Icons/btTwoRED.png", UriKind.RelativeOrAbsolute));
btnTwo.Style = (Style)this.Resources["btnTwoRedStyle"];
}
else
{
bitImgTwo = new BitmapImage(new Uri("ms-appx:/Assets/Icons/bt_AgendaVerde.png", UriKind.RelativeOrAbsolute));
btnTwo.Style = (Style)this.Resources["btnTwoBlueStyle"];
}
imgTwo.ImageSource = bitImgTwo;
imgTwo.Stretch = Stretch.UniformToFill;
btnTwo.Background = imgTwo;
minorButtonsRow.Children.Add(btnTwo);
Grid.SetRow(btnTwo, 0);
Grid.SetColumn(btnTwo, 1);
gridItem.Children.Add(minorButtonsRow);
Grid.SetRow(minorButtonsRow, 1);
Grid.SetColumn(minorButtonsRow, 0);
// END Button Two
#endregion
return gridItem;
}
If you have DataTemplate done correctly, then you don't need the ItemsPanel template. Can you show the code for DataTemplate? Because with it you can do pretty much everything.
For the colors. Declare brushes on your ViewModel and then assign it to your classes.Then just bind the Background. You only need one for each color.
Color binding: say you have SolidColorBrush property on your model named BgBrush. All you need to do is declare Background property on your control (i.e. grid) as "{Binding BgBrush}"
Related
I need to implement this drop-down menu in WPF:
When you click on the number of the question, it should open additional content. I can't attach the code, because there is not even an approximate implementation. I tried to implement via Grid.Row and Grid.Column, ListBox, StackPanel but I just didn't have enough knowledge.
Here is the code I've tried:
<Grid>
<ListBox HorizontalContentAlignment="Left">
<Button Content="1"/>
<TextBlock Text="Content"/>
<Button Content="2"/>
</ListBox>
</Grid>
Step 1: Add a User Control to your project.
Step 2: Name it Arrow.
Step 3: This Control will act as a drop-down arrow for us. Add the following XAML code to the control:
<UserControl x:Class="Question_Builder_App.Controls.Arrow"
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"
mc:Ignorable="d">
<Grid>
<Border BorderThickness="0,0,5,0" Height="15" BorderBrush="Black" RenderTransformOrigin="0.5,0.5" Width="10" Margin="0,0,0,10">
<Border.RenderTransform>
<TransformGroup>
<ScaleTransform/>
<SkewTransform/>
<RotateTransform Angle="135"/>
<TranslateTransform/>
</TransformGroup>
</Border.RenderTransform>
</Border>
<Border BorderThickness="0,0,5,0" BorderBrush="Black" RenderTransformOrigin="0.5,0.5" Height="15" Width="10" Margin="0,11,0,0" Grid.RowSpan="2">
<Border.RenderTransform>
<TransformGroup>
<ScaleTransform/>
<SkewTransform/>
<RotateTransform Angle="225"/>
<TranslateTransform/>
</TransformGroup>
</Border.RenderTransform>
</Border>
</Grid>
The control should look like this:
Step 4: Add the following XAML to your MainWindow:
<Window x:Class="Question_Builder_App.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"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800" Background="#FF283246">
<Grid x:Name="MainGrid">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<StackPanel x:Name="LeftPanel" Grid.Column="0">
<Border CornerRadius="10,10,10,10" HorizontalAlignment="Center" VerticalAlignment="Center" Background="#FF033B50" Margin="50,20,50,0">
<Button x:Name="AddQuestion_BTN" FontSize="24" Content="+" HorizontalAlignment="Stretch" VerticalAlignment="Center" Foreground="White" HorizontalContentAlignment="Left" Padding="10,0,10,0" Click="AddQuestion_BTN_Click" Background="{x:Null}" BorderBrush="{x:Null}"/>
</Border>
</StackPanel>
<Frame x:Name="RightPanel" Grid.Column="1" NavigationUIVisibility="Hidden"/>
</Grid>
The designer should look like this:
Step 5: Now lets add some C# codes to our MainWindow:
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace Question_Builder_App
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
AddSampleData("Test Button 1", "Test Button");
AddSampleData("Test Button 2", "Test Button");
AddSampleData("Test Button 3", "Test Button");
}
private int ButtonCount = 0;
private ObservableCollection<DataModel> PageCollection = new ObservableCollection<DataModel>();
private class DataModel
{
public string MainButtonName { get; set; }
public string PageName { get; set; }
public Page DisplayPage { get; set; }
}
private static string CreateInputWindow(string WindowDescription)
{
Window ButtonInfoWindow = new Window();
ButtonInfoWindow.Background = null; ButtonInfoWindow.SizeToContent = SizeToContent.WidthAndHeight;
StackPanel SP = new StackPanel();
Border TextDescription = AddBorder(WindowDescription, 24);
TextBox TB = new TextBox();
TB.MinWidth = 100; TB.FontSize = 24;
Button B = new Button();
B.FontSize = 24; B.Margin = new Thickness(0, 10, 0, 0); B.Content = "Set";
B.Click += delegate { ButtonInfoWindow.Close(); };
SP.Children.Add(TextDescription); SP.Children.Add(TB); SP.Children.Add(B);
ButtonInfoWindow.Content = SP;
ButtonInfoWindow.ShowDialog();
return TB.Text;
}
private void AddQuestion_BTN_Click(object sender, RoutedEventArgs e)
{
Border TopBorder = new Border();
TopBorder.CornerRadius = new CornerRadius(10); TopBorder.Background = new SolidColorBrush(Color.FromRgb(3, 59, 80)); TopBorder.HorizontalAlignment = HorizontalAlignment.Left;
TopBorder.Margin = new Thickness(40, 20, 40, 0);
StackPanel TopSPPanel = new StackPanel();
TopBorder.Child = TopSPPanel;
StackPanel LowerPanel = new StackPanel();
LowerPanel.Visibility = Visibility.Collapsed;
string MainButtonName = CreateInputWindow("What is the name of the button you wish to create?");
Border NewQuestion_BTN = AddBorder(ButtonCount + 1 + ". " + MainButtonName, 24);
NewQuestion_BTN.MouseLeftButtonDown += delegate
{
if (LowerPanel.Visibility == Visibility.Visible)
{
LowerPanel.Visibility = Visibility.Collapsed;
NewQuestion_BTN.Background = new SolidColorBrush(Color.FromRgb(3, 59, 80));
}
else
{
LowerPanel.Visibility = Visibility.Visible;
NewQuestion_BTN.Background = new SolidColorBrush(Colors.Blue);
}
};
TopSPPanel.Children.Add(NewQuestion_BTN);
LowerPanel.Margin = new Thickness(0, 10, 0, 10);
Border LowerNewQuestion_BTN = AddBorder("+", 24);
LowerNewQuestion_BTN.MouseLeftButtonDown += delegate
{
string InputText = CreateInputWindow("What is the name of the button you wish to create?");
Border ChooseQuestionBTN = AddBorder(LowerPanel.Children.Count + ". " + InputText, 16);
ChooseQuestionBTN.MouseLeftButtonDown += delegate
{
UncheckAllButtons();
ChooseQuestionBTN.Background = new SolidColorBrush(Colors.Aquamarine);
NavigateToPage(MainButtonName, InputText);
};
LowerPanel.Children.Insert(LowerPanel.Children.Count - 1, ChooseQuestionBTN);
};
LowerPanel.Children.Add(LowerNewQuestion_BTN); TopSPPanel.Children.Add(LowerPanel);
LeftPanel.Children.Insert(ButtonCount, TopBorder);
ButtonCount++;
}
private void NavigateToPage(string MainButtonText, string NameChecker)
{
bool CheckIfToADDANewPage = true;
foreach (DataModel PageFinder in PageCollection)
{
if (PageFinder.PageName == NameChecker && PageFinder.MainButtonName == MainButtonText)
{
RightPanel.Navigate(PageFinder.DisplayPage);
CheckIfToADDANewPage = false;
}
}
if (CheckIfToADDANewPage == true)
{
DataModel SavePage = new DataModel();
SavePage.MainButtonName = MainButtonText; SavePage.PageName = NameChecker; SavePage.DisplayPage = CreateANewPage();
PageCollection.Add(SavePage);
RightPanel.Navigate(SavePage.DisplayPage);
}
}
private static Page CreateANewPage()
{
Page QuestionPage = new Page();
StackPanel QuestionPanel = new StackPanel();
Border QuestionBorder = AddBorder("+", 24);
QuestionBorder.Margin = new Thickness(5, 20, 0, 0); QuestionBorder.Background = new SolidColorBrush(Colors.Aqua);
QuestionBorder.MouseLeftButtonDown += delegate
{
StackPanel UpperQuestionPanel = new StackPanel(); UpperQuestionPanel.Orientation = Orientation.Horizontal;
UpperQuestionPanel.Margin = new Thickness(0, 20, 0, 0);
Border QuestionNumberTXT = AddBorder(QuestionPanel.Children.Count.ToString(), 24);
QuestionNumberTXT.VerticalAlignment = VerticalAlignment.Top; QuestionNumberTXT.Background = new SolidColorBrush(Colors.Aqua);
Controls.Arrow PanelArrow = new Controls.Arrow();
PanelArrow.Margin = new Thickness(20, 10, 10, 0); PanelArrow.VerticalAlignment = VerticalAlignment.Top;
StackPanel InnerQuestionPanel = new StackPanel(); InnerQuestionPanel.Visibility = Visibility.Collapsed; InnerQuestionPanel.Margin = new Thickness(0, 10, 10, 0);
PanelArrow.MouseLeftButtonDown += delegate
{
if (InnerQuestionPanel.Visibility == Visibility.Collapsed)
{
InnerQuestionPanel.Visibility = Visibility.Visible;
PanelArrow.RenderTransform = new RotateTransform(90);
PanelArrow.Margin = new Thickness(45, 20, 10, 0);
if (InnerQuestionPanel.ActualWidth < 1)
{
Border InnerQuestionBorder = AddBorder(CreateInputWindow("Please enter description of the question: "), 24);
InnerQuestionBorder.MaxWidth = 800;
InnerQuestionPanel.Children.Insert(0, InnerQuestionBorder);
}
}
else
{
InnerQuestionPanel.Visibility = Visibility.Collapsed;
PanelArrow.RenderTransform = new RotateTransform(0);
PanelArrow.Margin = new Thickness(20, 10, 10, 0);
}
};
WrapPanel NewQuestionWrapPanel = new WrapPanel();
NewQuestionWrapPanel.Orientation = Orientation.Horizontal;
Border AddNewQuestionBTN = AddBorder("+", 24);
AddNewQuestionBTN.Margin = new Thickness(10, 10, 0, 0);
AddNewQuestionBTN.MouseLeftButtonDown += delegate
{
NewQuestionWrapPanel.MaxWidth = InnerQuestionPanel.ActualWidth;
Border ChooseNewQuestion = AddBorder(CreateInputWindow("Add new question: "), 24);
ChooseNewQuestion.Margin = new Thickness(10, 10, 0, 0);
NewQuestionWrapPanel.Children.Insert(NewQuestionWrapPanel.Children.Count - 1, ChooseNewQuestion);
};
NewQuestionWrapPanel.Children.Insert(NewQuestionWrapPanel.Children.Count, AddNewQuestionBTN); InnerQuestionPanel.Children.Add(NewQuestionWrapPanel);
UpperQuestionPanel.Children.Add(QuestionNumberTXT); UpperQuestionPanel.Children.Add(PanelArrow); UpperQuestionPanel.Children.Add(InnerQuestionPanel);
QuestionPanel.Children.Insert(QuestionPanel.Children.Count - 1, UpperQuestionPanel);
};
QuestionPanel.Children.Insert(QuestionPanel.Children.Count, QuestionBorder); QuestionPage.Content = QuestionPanel;
return QuestionPage;
}
private static Border AddBorder(string InnerText, int SetFontSize)
{
Border NewBorder = new Border();
NewBorder.CornerRadius = new CornerRadius(10); NewBorder.Background = new SolidColorBrush(Color.FromRgb(3, 59, 80)); NewBorder.HorizontalAlignment = HorizontalAlignment.Left;
NewBorder.Margin = new Thickness(10, 0, 10, 0);
TextBlock NewButton = new TextBlock();
NewButton.FontSize = SetFontSize; NewButton.VerticalAlignment = VerticalAlignment.Stretch; NewButton.Foreground = new SolidColorBrush(Colors.White);
NewButton.Margin = new Thickness(10, 0, 10, 0);
NewButton.Text = InnerText;
NewButton.TextWrapping = TextWrapping.Wrap;
NewBorder.Child = NewButton;
return NewBorder;
}
private void AddSampleData(string MainButtonText, string SecondaryButtonText)
{
Border TopBorder = new Border();
TopBorder.CornerRadius = new CornerRadius(10); TopBorder.Background = new SolidColorBrush(Color.FromRgb(3, 59, 80)); TopBorder.HorizontalAlignment = HorizontalAlignment.Left;
TopBorder.Margin = new Thickness(40, 20, 40, 0);
StackPanel TopSPPanel = new StackPanel();
TopBorder.Child = TopSPPanel;
StackPanel LowerPanel = new StackPanel();
LowerPanel.Visibility = Visibility.Collapsed;
Border NewQuestion_BTN = AddBorder(ButtonCount + 1 + ". " + MainButtonText, 24);
NewQuestion_BTN.MouseLeftButtonDown += delegate
{
if (LowerPanel.Visibility == Visibility.Visible)
{
LowerPanel.Visibility = Visibility.Collapsed;
NewQuestion_BTN.Background = new SolidColorBrush(Color.FromRgb(3, 59, 80));
}
else
{
LowerPanel.Visibility = Visibility.Visible;
NewQuestion_BTN.Background = new SolidColorBrush(Colors.Blue);
}
};
TopSPPanel.Children.Add(NewQuestion_BTN);
LowerPanel.Margin = new Thickness(0, 10, 0, 10);
Border LowerNewQuestion_BTN = AddBorder("+", 24);
LowerNewQuestion_BTN.MouseLeftButtonDown += delegate
{
string InputText = CreateInputWindow("What is the name of the button you wish to create?");
Border ChooseQuestionBTN = AddBorder(LowerPanel.Children.Count + ". " + InputText, 16);
ChooseQuestionBTN.MouseLeftButtonDown += delegate
{
UncheckAllButtons();
ChooseQuestionBTN.Background = new SolidColorBrush(Colors.Aquamarine);
NavigateToPage(MainButtonText, InputText);
};
LowerPanel.Children.Insert(LowerPanel.Children.Count - 1, ChooseQuestionBTN);
};
Border SampleQuestionBTN = AddBorder(LowerPanel.Children.Count + 1 + ". " + SecondaryButtonText, 16);
SampleQuestionBTN.MouseLeftButtonDown += delegate
{
UncheckAllButtons();
SampleQuestionBTN.Background = new SolidColorBrush(Colors.Aquamarine);
NavigateToPage(MainButtonText, SecondaryButtonText);
};
LowerPanel.Children.Insert(LowerPanel.Children.Count, SampleQuestionBTN);
LowerPanel.Children.Add(LowerNewQuestion_BTN); TopSPPanel.Children.Add(LowerPanel);
LeftPanel.Children.Insert(ButtonCount, TopBorder);
ButtonCount++;
}
private void UncheckAllButtons()
{
foreach (Border _BR in LeftPanel.Children)
{
if (_BR.Child is StackPanel)
{
StackPanel SP = (StackPanel)_BR.Child;
foreach (UIElement UE in SP.Children)
{
if (UE is StackPanel)
{
StackPanel SP1 = (StackPanel)UE;
foreach (Border B in SP1.Children)
{
B.Background = null;
}
}
}
}
}
}
}
}
I have a WPF Canvas with a TextBlock and an Image on it. The text is animated, but it doesn't look smooth. I tried many combinations of different FPS-Settings and durations but it won't get better.
I also want to let the text fade-in/out at the start and ending. But I found no methods to do so.
At the moment it looks like that:
How can I get the animation smoothly? How can I fade it in/out smoothly?
Before you ask, I need to show the Window invisible because I use the WpfAppBar and that component needs an HWND.
Here is the canvas xaml:
<Canvas x:Name="canMain" HorizontalAlignment="Stretch" VerticalAlignment="Center">
<Border x:Name="boLogo" Panel.ZIndex="2" Height="40" Background="Gray" Canvas.Left="0" Canvas.Top="-20">
<Image Height="39" Width="auto" Margin="5, 0, 5, 0" Source="pack://siteoforigin:,,,/Resources/Logo.png" />
</Border>
<TextBlock x:Name="tbInfo" Panel.ZIndex="1" Visibility="Hidden" RenderOptions.BitmapScalingMode="NearestNeighbor" FontSize="32" TextOptions.TextFormattingMode="Display" TextOptions.TextRenderingMode="ClearType" FontFamily="Arial" FontWeight="Bold" Padding="5" HorizontalAlignment="Stretch" VerticalAlignment="Center">
<TextBlock.RenderTransform>
<TranslateTransform x:Name="AnimatedTranslateTransform" X="0" Y="0" />
</TextBlock.RenderTransform>
</TextBlock>
</Canvas>
And the code to animate the text:
public void ShowWindow(Brush fontColor, Brush backgroundColor, string str) {
var helper = new WindowInteropHelper(this);
helper.EnsureHandle();
tbInfo.Foreground = fontColor;
this.Background = backgroundColor;
tbInfo.Text = str;
this.Height = 39;
this.Width = SystemParameters.WorkArea.Width;
this.Left = SystemParameters.PrimaryScreenWidth - this.Width;
ShowWindowInvisible();
WpfAppBar.AppBarFunctions.SetAppBar(this, WpfAppBar.ABEdge.Top);
Visibility = Visibility.Visible;
int duration = 10 + str.Length / 5;
TextMarquee(duration);
}
private void TextMarquee(int duration)
{
Timeline.DesiredFrameRateProperty.OverrideMetadata(
typeof(Timeline),
new FrameworkPropertyMetadata { DefaultValue = 60 }
);
double height = canMain.ActualHeight - tbInfo.ActualHeight;
tbInfo.Margin = new Thickness(0, height / 2, 0, 0);
DoubleAnimation doubleAnimation = new DoubleAnimation();
doubleAnimation.From = canMain.ActualWidth;
doubleAnimation.To = tbInfo.ActualWidth *-1;
doubleAnimation.RepeatBehavior = RepeatBehavior.Forever;
doubleAnimation.Duration = new Duration(TimeSpan.FromSeconds(duration));
tbInfo.BeginAnimation(Canvas.LeftProperty, doubleAnimation);
tbInfo.Visibility = Visibility.Visible;
}
private void ShowWindowInvisible()
{
var width = Width;
var height = Height;
var windowStyle = WindowStyle;
var showInTaskbar = ShowInTaskbar;
var showActivated = ShowActivated;
Width = 0;
Height = 0;
WindowStyle = WindowStyle.None;
ShowInTaskbar = false;
ShowActivated = false;
Show();
Visibility = Visibility.Hidden;
Width = width;
Height = height;
WindowStyle = windowStyle;
ShowInTaskbar = showInTaskbar;
ShowActivated = showActivated;
}
I have built a UI block in XAML that will represent a customizable web page test automation. No problem so far.
I'm now trying to translate these UI elements from XAML to the C# code behind, so I can generate the UI blocks dynamically, and there are differences I can't explain: several element are not displayed when generated from the code behind.
Screenshot for comparison:
XAML code:
<StackPanel x:Name="TestPanel" Orientation="Vertical" Grid.RowSpan="2">
<Grid Margin="0,20,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="100*"/>
<ColumnDefinition Width="auto"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<CheckBox Grid.Column="0" Grid.Row="0" Grid.ColumnSpan="2" Margin="10,0,0,0">Page link here</CheckBox>
<TextBlock Grid.Column="2" Grid.Row="0" Margin="0,0,10,0">Status here</TextBlock>
<CheckBox Grid.Column="0" Grid.Row="1" Margin="30,8,0,0">Url to check:</CheckBox>
<TextBox Grid.Column="1" Grid.Row="1" Margin="5,5,5,0">Url here</TextBox>
<TextBlock Grid.Column="2" Grid.Row="1" VerticalAlignment="Center" Margin="0,0,10,0">Status here</TextBlock>
<CheckBox Grid.Column="0" Grid.Row="2" Margin="30,8,0,0">Text to check:</CheckBox>
<TextBox Grid.Column="1" Grid.Row="2" Margin="5,5,5,0">Text here</TextBox>
<TextBlock Grid.Column="2" Grid.Row="2" VerticalAlignment="Center" Margin="0,0,10,0">Status here</TextBlock>
</Grid>
</StackPanel>
C# code behind:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
new Test(this);
}
}
public class Test
{
public MainWindow Window { get; set; }
public Grid Grid { get; set; }
public CheckBox PageCB { get; set; }
public TextBlock PageStatus { get; set; }
public CheckBox UrlCB { get; set; }
public TextBox UrlTB { get; set; }
public TextBlock UrlStatus { get; set; }
public CheckBox TextCB { get; set; }
public TextBox TextTB { get; set; }
public TextBlock TextStatus { get; set; }
public Test(MainWindow window)
{
this.Window = window;
this.Grid = new Grid();
this.Grid.Margin = new Thickness(0, 20, 0, 0);
// Columns
this.Grid.ColumnDefinitions.Add(new ColumnDefinition());
ColumnDefinition col = new ColumnDefinition();
col.Width = new GridLength(100, GridUnitType.Star);
this.Grid.ColumnDefinitions.Add(col);
this.Grid.ColumnDefinitions.Add(new ColumnDefinition());
// Rows
this.Grid.RowDefinitions.Add(new RowDefinition());
this.Grid.RowDefinitions.Add(new RowDefinition());
this.Grid.RowDefinitions.Add(new RowDefinition());
// Elements
this.PageCB = new CheckBox();
this.PageCB.Margin = new Thickness(10, 0, 0, 0);
this.PageCB.Content = "Page link here";
Grid.SetColumn(this.PageCB, 0);
Grid.SetRow(this.PageCB, 0);
Grid.SetColumnSpan(this.PageCB, 2);
this.Grid.Children.Add(this.PageCB);
this.PageStatus = new TextBlock();
this.PageStatus.Margin = new Thickness(0, 0, 10, 0);
this.PageStatus.Text = "Status here";
Grid.SetColumn(this.PageStatus, 2);
Grid.SetRow(this.PageStatus, 0);
this.Grid.Children.Add(this.PageStatus);
this.UrlCB = new CheckBox();
this.UrlCB.Margin = new Thickness(30, 8, 0, 0);
this.UrlCB.Content = "Url to check:";
Grid.SetColumn(this.UrlCB, 0);
Grid.SetRow(this.UrlCB, 1);
this.Grid.Children.Add(this.UrlCB);
this.UrlTB = new TextBox();
this.UrlTB.Margin = new Thickness(5, 5, 5, 0);
this.UrlTB.Text = "Url here";
Grid.SetColumn(this.UrlTB, 1);
Grid.SetRow(this.UrlTB, 1);
this.Grid.Children.Add(this.UrlTB);
this.UrlStatus = new TextBlock();
this.UrlStatus.Margin = new Thickness(0, 0, 10, 0);
this.UrlStatus.Text = "Status here";
Grid.SetColumn(this.UrlStatus, 2);
Grid.SetRow(this.UrlStatus, 1);
this.Grid.Children.Add(this.UrlStatus);
this.TextCB = new CheckBox();
this.TextCB.Margin = new Thickness(30, 8, 0, 0);
this.TextCB.Content = "Text to check:";
Grid.SetColumn(this.TextCB, 0);
Grid.SetRow(this.TextCB, 2);
this.Grid.Children.Add(this.TextCB);
this.TextTB = new TextBox();
this.TextTB.Margin = new Thickness(5, 5, 5, 0);
this.TextTB.Text = "Text here";
Grid.SetColumn(this.TextTB, 1);
Grid.SetRow(this.TextTB, 2);
this.Grid.Children.Add(this.TextTB);
this.TextStatus = new TextBlock();
this.TextStatus.Margin = new Thickness(0, 0, 10, 0);
this.TextStatus.Text = "Status here";
Grid.SetColumn(this.TextStatus, 2);
Grid.SetRow(this.TextStatus, 2);
this.Grid.Children.Add(this.TextStatus);
this.Window.TestPanel.Children.Add(this.Grid);
}
}
Thanks
I second the suggestion that you should create a User Control and reuse that. However, to answer the question directly, you need to set the Column and Row Width and Height properties to Auto.
// Columns
this.Grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = GridLength.Auto });
ColumnDefinition col = new ColumnDefinition();
col.Width = new GridLength(100, GridUnitType.Star);
this.Grid.ColumnDefinitions.Add(col);
this.Grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = GridLength.Auto });
// Rows
this.Grid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
this.Grid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
this.Grid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
The problem is you arent setting the height or the rows and width of the columns inside your layout grid. The default height/width isnt auto but * size.
So this code:
// Columns
this.Grid.ColumnDefinitions.Add(new ColumnDefinition());
ColumnDefinition col = new ColumnDefinition();
col.Width = new GridLength(100, GridUnitType.Star);
this.Grid.ColumnDefinitions.Add(col);
this.Grid.ColumnDefinitions.Add(new ColumnDefinition());
// Rows
this.Grid.RowDefinitions.Add(new RowDefinition());
this.Grid.RowDefinitions.Add(new RowDefinition());
this.Grid.RowDefinitions.Add(new RowDefinition());
Should be :
// Columns
this.Grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = GridLength.Auto });
this.Grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(100, GridUnitType.Star) });
this.Grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = GridLength.Auto });
// Rows
this.Grid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
this.Grid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
this.Grid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
I have a Grid which scaled/zoomed with ScaleTransform by slider. At runtime many UIElements are added to this Grid.
I want to show some tooltips, but not scaled! How should I do that?
For the example: Grid has scaleX and scaleY 2, so I set new ScaleTransform(0.5, 0.5), but didn't help. It seems that the most similar value is 0.740.. Why?
Even Grid's LayoutTransform.Inverse is set to scale values 0.5.
XAML:
<ScrollViewer HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto" Height="Auto" Width="Auto" Name="graphScrollViewer" ScrollChanged="graphScrollViewer_ScrollChanged">
<Grid Margin="0,0,0,0" Name="graphGrid" Width="Auto" Height="Auto" ScrollViewer.IsDeferredScrollingEnabled="True" MouseLeftButtonDown="graphGrid_MouseLeftButtonDown" MouseLeftButtonUp="graphGrid_MouseLeftButtonUp" MouseMove="graphGrid_MouseMove">
<Grid.LayoutTransform>
<ScaleTransform ScaleX="{Binding ElementName=sldZoom, Path=Value}" ScaleY="{Binding ElementName=sldZoom, Path=Value}" />
</Grid.LayoutTransform>
</Grid>
</ScrollViewer>
<Slider Minimum="0.1" Maximum="20" Value="1" x:Name="sldZoom" Panel.ZIndex="10" Orientation="Horizontal" VerticalAlignment="Bottom" HorizontalAlignment="Right" Margin="0,0,20,20" Height="23" Width="100" ValueChanged="sldZoom_ValueChanged"/>
Code-behind:
(method of Rectangle (MouseEnter event) dynamically added to grid)
private void rect_MouseEnter(object sender, MouseEventArgs e)
{
RectToolTip = new TextBlock();
RectToolTip.HorizontalAlignment = HorizontalAlignment.Left;
RectToolTip.VerticalAlignment = VerticalAlignment.Top;
RectToolTip.TextAlignment = TextAlignment.Center;
RectToolTip.Height = this.HeaderTwoHeight + 1;
RectToolTip.Text = " " + (RectsTasks[(sender as Rectangle)]).Info + " ";
RectToolTip.Background = this.ToolTipBackground;
RectToolTip.Foreground = this.ToolTipFontColor;
RectToolTipBorder = new Border();
RectToolTipBorder.Child = RectToolTip;
RectToolTipBorder.BorderThickness = new Thickness(this.ToolTipBorderThickness);
RectToolTipBorder.BorderBrush = this.ToolTipBorderColor;
RectToolTipBorder.Margin = new Thickness(e.GetPosition((graphGrid)).X + 10, e.GetPosition((graphGrid)).Y + 10, 0, 0);
RectToolTipBorder.VerticalAlignment = System.Windows.VerticalAlignment.Top;
RectToolTipBorder.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
graphGrid.Children.Add(RectToolTipBorder);
RectToolTipBorder.LayoutTransform = RectToolTip.LayoutTransform = new ScaleTransform(????);
Grid.SetZIndex(RectToolTip, 20);
Grid.SetZIndex(RectToolTipBorder, 20);
}
You need to assign the inverse transform to the child element, so that the child will stay intact.
RectToolTipBorder.LayoutTransform = graphGrid.LayoutTransform.Inverse as Transform;
Why does the following C# code not produce the equivalent of my Silverlight code?
XAML
<Border CornerRadius="8" BorderBrush="White" Height="70" BorderThickness="4">
<StackPanel Orientation="Horizontal">
<Border Margin="5,0,0,0" BorderBrush="White" Height="45" Width="45" BorderThickness="2" CornerRadius="2" Background="White">
<Image Source="/Crystal%20Cloud;component/Resources/Images/weapons/swords/sword_0.png" />
</Border>
<StackPanel Margin="10,0,0,0">
<TextBlock Text="Wooden Dagger" FontFamily="Comic Sans MS" />
<TextBlock Text="DPS: 1" FontFamily="Comic Sans MS" FontSize="16" Margin="15,0,0,0" />
</StackPanel>
</StackPanel>
</Border>
C#
private Border CreateListItem(Item item)
{
// Main border
Border itemBorder = new Border();
itemBorder.BorderThickness = new Thickness(4);
itemBorder.CornerRadius = new CornerRadius(8);
itemBorder.BorderBrush = new SolidColorBrush(Colors.White);
itemBorder.Height = 70;
// Main stack panel
StackPanel mainPanel = new StackPanel();
mainPanel.Orientation = Orientation.Horizontal;
itemBorder.Child = mainPanel;
// The item's image border
Border imageBorder = new Border();
imageBorder.Margin = new Thickness(5, 0, 0, 0);
itemBorder.BorderThickness = new Thickness(2);
itemBorder.CornerRadius = new CornerRadius(2);
itemBorder.BorderBrush = new SolidColorBrush(Colors.White);
itemBorder.Background = new SolidColorBrush(Colors.White);
itemBorder.Height = 45;
itemBorder.Width = 45;
mainPanel.Children.Add(imageBorder);
// The item's image
Image image = new Image();
image.Source = new BitmapImage(new Uri("/Crystal%20Cloud;component/Resources/Images/weapons/swords/sword_0.png"));
imageBorder.Child = image;
// The stack panel for the text
StackPanel textPanel = new StackPanel();
textPanel.Margin = new Thickness(10, 0, 0, 0);
mainPanel.Children.Add(textPanel);
// The title text block
TextBlock titleText = new TextBlock();
titleText.Text = "Wooden Dagger";
titleText.FontFamily = new FontFamily("Comic Sans MS");
textPanel.Children.Add(titleText);
// The status text block
TextBlock statusText = new TextBlock();
statusText.Text = "DPS: 1";
statusText.FontFamily = new FontFamily("Comic Sans MS");
statusText.FontSize = 16;
statusText.Margin = new Thickness(15, 0, 0, 0);
textPanel.Children.Add(statusText);
return itemBorder;
}
Erg... just found the bug itemBorder should be changed to imageBorder.