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 });
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 want to bind data to a grid in xaml. This is the code I am using for binding it:
<Grid x:Name="Example" Grid.Column="1" Grid.Row="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" >
<ContentPresenter Content="{Binding ExampleImage}" />
</Grid>
Now when I bind it using fixed width and height it will display the grid at set dimensions.
Code:
private Grid _exampleImage;
public Grid ExampleImage
{
get
{
if (SelectedSectie != null)
{
var convertFromString = System.Windows.Media.ColorConverter.ConvertFromString("#CCCCCC");
if (convertFromString != null)
{
DropShadowEffect dse = new DropShadowEffect
{
BlurRadius = 5,
ShadowDepth = 1,
Direction = 270,
Color =
(System.Windows.Media.Color)
convertFromString
};
_exampleImage = new Grid
{
Background =
new SolidColorBrush(SingleIcons.Helpers.ColorConverter.ToMediaColor(SelectedSectie.Color.ColorValue)),
VerticalAlignment = VerticalAlignment.Stretch,
Width = SelectedIconSize.Width,
Height = SelectedIconSize.Height,
MaxWidth = SelectedIconSize.Width,
MaxHeight = SelectedIconSize.Height,
HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch,
Effect = dse,
RowDefinitions =
{
new RowDefinition {Height = new GridLength(46, GridUnitType.Star)},
new RowDefinition {Height = new GridLength(3, GridUnitType.Star)}
}
};
}
TextBlock afbeeldingTextBlock = new TextBlock
{
Text = _selectedSectie.Sectie,
TextWrapping = TextWrapping.Wrap,
TextAlignment = TextAlignment.Center,
Width = _exampleImage.Width,
FontSize = Global.Fontsize,
FontFamily = new System.Windows.Media.FontFamily(Global.Family.Name),
VerticalAlignment = VerticalAlignment.Center,
Foreground =
new SolidColorBrush(
SingleIcons.Helpers.ColorConverter.ToMediaColor(SelectedSectie.Color.TextColorValue)),
};
TextOptions.SetTextFormattingMode(afbeeldingTextBlock, TextFormattingMode.Display);
TextOptions.SetTextRenderingMode(afbeeldingTextBlock, TextRenderingMode.ClearType);
Canvas bottomCanvas = new Canvas
{
Background = (SolidColorBrush) (new BrushConverter().ConvertFrom("#26000000"))
};
Grid.SetRow(afbeeldingTextBlock, 0);
Grid.SetRow(bottomCanvas, 1);
_exampleImage.Children.Add(afbeeldingTextBlock);
_exampleImage.Children.Add(bottomCanvas);
_exampleImage.Measure(new System.Windows.Size(_exampleImage.Width,
_exampleImage.Height));
_exampleImage.Arrange(
new Rect(new System.Windows.Size(_exampleImage.Width, _exampleImage.Height)));
return _exampleImage;
}
else
{
return null;
}
}
}
Now what I would like to do is to keep the grid at set dimensions but allow the GUI to scale the grid,
because when I make the window smaller the grid stays at these dimensions and it hurts the scaling of the application.
The reason I am using a databound grid is because I have another function which exports this grid to a .png.
Putting it inside a Viewbox and setting StretchDirection to DownOnly was the result i wanted.
<Grid x:Name="Example" Grid.Column="1" Grid.Row="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" >
<Viewbox StretchDirection="DownOnly" >
<ContentPresenter Content="{Binding ExampleImage}" />
</Viewbox>
</Grid>
Problem while programmatically generating buttons in a user control of windows phone, and using this user control to mainpage.xaml but there are no buttons shown when application runs.
here is the code snippet which i am using, Thanks !
usercontrol.xaml:
<ScrollViewer >
<StackPanel x:Name="Panel">
<ContentControl x:Name="container"></ContentControl>
</StackPanel>
</ScrollViewer>
usercontrol.xaml.cs:
public LoginInterfaceControl()
{
InitializeComponent();
this.container = new ContentControl();
this.Panel = new StackPanel();
}
public LoginInterfaceControl(string Api_key)
{
InitializeComponent();
this.Panel = new StackPanel();
this.container = new ContentControl();
loginWP_DownloadString(Api_key);
}
public async void loginWP_DownloadString(string key)
{
InitializeComponent();
string cont;
using (HttpClient client = new HttpClient())
{
var result = await client.GetAsync("http://cdn.loginradius.com/interface/json/" + key + ".json");
if (result.StatusCode == HttpStatusCode.OK)
{
cont = await result.Content.ReadAsStringAsync();
MessageBox.Show(cont);
}
else
{
cont = await result.Content.ReadAsStringAsync();
MessageBox.Show(cont);
}
if (!string.IsNullOrEmpty(cont))
{
var root1 = JsonConvert.DeserializeObject<RootObject>(cont);
int no = 1;
foreach (var provider in root1.Providers)
{
no++;
Button newBtn = new Button()
{
Content = provider.Name.ToString(),
Name = provider.Name.ToString(),
//Width = 88,
//Height = 77,
Visibility = System.Windows.Visibility.Visible,
//Margin = new Thickness(5 + 20, 5, 5, 5),
Background = new SolidColorBrush(Colors.Black),
VerticalAlignment =VerticalAlignment.Center,
Opacity=0.5
};
newBtn.Click += google_click;
System.Windows.Visibility.Visible;
container.Opacity = 0.5;
this.container.Content = newBtn;
}
}
}
Mainpage.xaml:
<Grid xmlns:src="clr-namespace:LRDemo"
Background="White" Margin="10,0,-10,186" Grid.Row="1">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<src:LoginInterfaceControl Grid.Row="0"/>
<!--<src:LoginInterfaceControl Grid.Row="1" Margin="0,15,0,0"/>-->
</Grid>
usercontrol.xaml
<ScrollViewer>
<ContentControl x:Name="container">
<StackPanel x:Name="Panel">
</StackPanel>
</ContentControl>
</ScrollViewer>
there is no need to again create stackpanel and contentcontrol in constructor of usercontrol because they are already there in usercontrol structure.
Contentcontrol can hold content that is assign to it last so I took stackpanel into contentcontol.
usercontrol.xaml.cs
public LoginInterfaceControl()
{
this.InitializeComponent();
abc();
}
public void abc()
{
for (int i = 0; i <= 5; i++)
{
Button newBtn = new Button()
{
Content = "name" + i,
Name = "name" + i,
Background = new SolidColorBrush(Colors.Black),
VerticalAlignment = VerticalAlignment.Center,
Opacity = 0.5
};
newBtn.Click += newBtn_Click;
container.Opacity = 0.5;
this.Panel.Children.Add(newBtn);
}
}
P.S : I do not know your exact need so I took static methods to add buttons.
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}"
I have some problems with new Metro design in Windows 8. I'm building simple e-reader app, and want to use two-column pages. So, my choice is FlipView and RichTextBlock with overflows. But after adding two pages, overflow doesn't have overflow content! So I have only three pages. But text is very large.
I have such code:
private async void CreatePages()
{
_pages = new List<UIElement>();
_pageCount = 1;
_lastOverflow = AddOnePage(null, _pageCount);
while (_lastOverflow.HasOverflowContent) //It's here!!
{
_pageCount++;
_lastOverflow = AddOnePage(_lastOverflow, _pageCount);
View.UpdateLayout();
}
for (var i = 1; i <= _pageCount; i++)
{
var scrollViewer = new ScrollViewer
{
Margin = new Thickness(10, 30, 10, 30),
HorizontalContentAlignment = HorizontalAlignment.Stretch,
ZoomMode = ZoomMode.Enabled,
VerticalScrollMode = ScrollMode.Enabled,
HorizontalScrollMode = ScrollMode.Disabled,
Name = "Scroll" + i
};
var snappedBlock = new RichTextBlock
{
VerticalAlignment = VerticalAlignment.Center,
HorizontalAlignment = HorizontalAlignment.Center,
TextWrapping = TextWrapping.Wrap,
IsTextSelectionEnabled = true
};
foreach (var text in new string[0])
{
var paragraph = new Paragraph();
paragraph.Inlines.Add(new Run { Text = text });
snappedBlock.Blocks.Add(paragraph);
}
scrollViewer.Content = snappedBlock;
SnappedView.Items.Add(scrollViewer);
}
}
private RichTextBlockOverflow AddOnePage(RichTextBlockOverflow lastOverflow, int pageNumber)
{
// Create a grid which represents the page
var grid = new Grid
{
Name = "Grid" + pageNumber
};
grid.ColumnDefinitions.Add(new ColumnDefinition
{
Width = new GridLength(1, GridUnitType.Star)
});
grid.ColumnDefinitions.Add(new ColumnDefinition
{
Width = new GridLength(1, GridUnitType.Star)
});
var grid1 = new Grid
{
Name = "Grid1_" + pageNumber
};
var grid2 = new Grid
{
Name = "Grid2_" + pageNumber
};
grid1.SetValue(Grid.ColumnProperty, 0);
grid2.SetValue(Grid.ColumnProperty, 1);
grid.Children.Add(grid1);
grid.Children.Add(grid2);
View.Items.Add(grid);
// If lastRTBOAdded is null then we know we are creating the first page.
var isFirstPage = lastOverflow == null;
RichTextBlockOverflow richTextBlockOverflow = null;
if (isFirstPage)
{
var overflow = new RichTextBlockOverflow
{
Margin = new Thickness(20, 30, 70, 30),
Name = "SecondBlock" + pageNumber,
OverflowContentTarget = new RichTextBlockOverflow(),
VerticalAlignment = VerticalAlignment.Center,
HorizontalAlignment = HorizontalAlignment.Center
};
overflow.SetValue(Grid.ColumnProperty, 1);
_textBlock = new RichTextBlock
{
VerticalAlignment = VerticalAlignment.Center,
HorizontalAlignment = HorizontalAlignment.Center,
Margin = new Thickness(70, 30, 20, 30),
TextWrapping = TextWrapping.Wrap,
IsTextSelectionEnabled = true,
Name = "FirstBlock" + pageNumber,
OverflowContentTarget = overflow
};
_textBlock.SetValue(Grid.ColumnProperty, 0);
foreach (var text in _content.Trim('\n', ' ', '\t').Split('\n'))
{
var paragraph = new Paragraph();
paragraph.Inlines.Add(new Run { Text = text });
_textBlock.Blocks.Add(paragraph);
}
grid1.Children.Add(_textBlock);
grid2.Children.Add(overflow);
_textBlock.Measure(grid1.RenderSize);
overflow.Measure(grid2.RenderSize);
_pages.Add(grid);
richTextBlockOverflow = overflow;
}
else
{
// This is not the first page so the first element on this page has to be a
// RichTextBoxOverflow that links to the last RichTextBlockOverflow added to
// the previous page.
if (lastOverflow.HasOverflowContent)
{
var overflowSecond = new RichTextBlockOverflow
{
VerticalAlignment = VerticalAlignment.Center,
HorizontalAlignment = HorizontalAlignment.Center,
Margin = new Thickness(20, 30, 70, 30),
Name = "SecondBlock" + pageNumber
};
overflowSecond.SetValue(Grid.ColumnProperty, 1);
var overflowFirst = new RichTextBlockOverflow
{
VerticalAlignment = VerticalAlignment.Center,
HorizontalAlignment = HorizontalAlignment.Center,
Margin = new Thickness(70, 30, 20, 30),
Name = "FirstBlock" + pageNumber,
OverflowContentTarget = overflowSecond
};
overflowFirst.SetValue(Grid.ColumnProperty, 0);
lastOverflow.OverflowContentTarget = overflowFirst;
grid1.Children.Add(overflowFirst);
grid2.Children.Add(overflowSecond);
overflowFirst.Measure(grid1.RenderSize);
overflowSecond.Measure(grid2.RenderSize);
_pages.Add(overflowFirst);
_pages.Add(overflowSecond);
richTextBlockOverflow = overflowSecond;
}
}
_pages.Clear();
LayoutRoot.UpdateLayout();
return richTextBlockOverflow;
}
In LoadState() I call CreatePages() method.
My XAML:
<Grid x:Name="LayoutRoot" Style="{StaticResource LayoutRootStyle}" Background="#FFDEDEDE">
<FlipView x:Name="View" HorizontalAlignment="Stretch" VerticalAlignment="Center" Foreground="Black" SelectionChanged="ViewOnSelectionChanged" FontSize="18" >
</FlipView>
<FlipView x:Name="SnappedView" HorizontalAlignment="Stretch" VerticalAlignment="Top" Foreground="Black" SelectionChanged="SnappedViewOnSelectionChanged" FontSize="12" Visibility="Collapsed">
</FlipView>
<ProgressBar x:Name="LoadProgressBar" HorizontalAlignment="Stretch" VerticalAlignment="Top" IsIndeterminate="True" Foreground="#007ACC"/>
</Grid>
Thanks to all! I hope, that someone knows, how to solve this problem..