Add Controls to GroupBox which was created dynamically - c#

I add GroupBoxes to an ItemsControl dynamically using:
string name_ = "TestName", header_ = "TestHeader"
GroupBox MyGroupBox = new GroupBox { Name = name_, Header= header_, Width = 240, Height = 150, Foreground=new SolidColorBrush(Color.FromArgb(255, 0, 0, 0)) };
MyItemsControl.Items.Add(MyGroupBox);
Now I need to add content to this GroupBox, like a few TextBlocks created like:
TextBlock MyTextBlock = new TextBlock {Text = "test"};
But I can't figure out how to do that. Normally to a Grid or something like that I would just use .Children.Add(MyTextBlock), but that doesn't work here.
Also I have to be able to remove specific Items from the ItemsControl again (best would be by the name of the Item, name_ in this example).

Try something like that
GroupBox groupBox1 = new GroupBox();
Grid grid1 = new Grid();
TextBlock MyTextBlock = new TextBlock {Text = "test"};
groupBox1.Width = 185;
groupBox1.Height = 160;
grid1.Height = 185;
grid1.Width = 160;
grid1.Children.Add(MyTextBlock);
groupBox1.Content = grid1;
mainWindow.canvas.Children.Add(groupBox1);

The GroupBox has only a Content Property which is designed to hold a ContentPresentor. You can add a Grid/Canvas etc.. to the GroupBox and then add your content to that.

Related

Create GroupBox and labels inside it programmatically

I want to create a groupbox programmatically and inside it put labels. Now I created this but with design and I have like this:
I'm trying but I don't know how can I assign labels in correct position and how can I assign it to a specific group box
GroupBox groupBox1 = new GroupBox();
Panel grid1 = new Panel();
Label lbl1 = new Label { Text = "Completed" };
Label lbl2 = new Label { Text = "label" };
Label lbl3 = new Label { Text = "In progress" };
Label lbl4 = new Label { Text = "label" };
//etcetera
groupBox1.Width = 185;
groupBox1.Height = 160;
grid1.Height = 185;
grid1.Width = 160;
How can I achieve that? Regards
Update
As the comments below I try
GroupBox groupBox1 = new GroupBox();
this.Controls.Add(groupBox1);
Panel grid1 = new Panel();
groupBox1.Controls.Add(grid1);
groupBox1.Location = new Point(20, 250);
grid1.Location = new Point(20, 250);
Label lbl1 = new Label { Text = "test" };
Label lbl2 = new Label { Text = "Test2" };
groupBox1.Name = "TESTTT";
groupBox1.Width = 222;
groupBox1.Height = 149;
grid1.Height = 218;
grid1.Width = 145;
grid1.Controls.Add(lbl1);
grid1.Controls.Add(lbl2);
Result:
But my group box it just clear without name and without labels, why it happen?
Controls in WinForms are arranged so that they reside inside one another. So your Form has a Controls collection which is essentially a Collection of type Control. So if you add a GroupBox to the form, then you must add it to the Controls collection of the form. Then if you add a control to your GroupBox then you need to add it to the GroupBox collection of controls.
With that in mind, you can do something like this:
private void AddGroupBoxAndLables()
{
GroupBox groupBox1 = new GroupBox();
groupBox1.SetBounds(50, 50, 300, 200);
this.Controls.Add(groupBox1);
Label lblCompleted = new Label { Name = "lblCompleted", Text = "Completed" };
lblCompleted.Location = new Point(20, 20);
groupBox1.Controls.Add(lblCompleted);
Label valCompleted = new Label { Name = "valCompleted" };
valCompleted.Location = new Point(80, 20);
groupBox1.Controls.Add(valCompleted);
Label lblInProgress = new Label { Name = "lblInProgress", Text = "In Progress" };
lblInProgress.Location = new Point(20, 60);
groupBox1.Controls.Add(lblInProgress);
Label valInProgress = new Label { Name = "valInProgress" };
valInProgress.Location = new Point(80, 60);
groupBox1.Controls.Add(valInProgress);
}
simplest way for solution is that your code is already created when you did design. Code is created automatically in respective form's designer.cs or designer.vb file. To see this file, in solution explorer click on button 'Show all files'. Still for your understanding let me explain code
You have created groupbox using
GroupBox groupBox1 = new GroupBox();
To see this group box on form you need to add this groupbox to form
this.Controls.Add(groupBox1);
Similar in case of panel. If you want to add panel inside of groupbox then
groupbox1.Controls.Add(grid1);
Then add all labels inside of panel.
You will find similar kind of code in form's designer.cs.

How To Add A Border To DataGrid Column Cells

I am displaying data in a WPF DataGrid and the first column shows the static text "View". I added the code below to make the text look like a button. I don't want to do a lot of work to create a button column custom template. This is almost working; the text is centered, the border is drawn. The only thing not working is the background does not appear - I can still see the underlying alternating row colors. Is there something else I need to do to activate the background color, or does the problem arise because the TextBlock is nested inside the DataGridCell and (I think) some other objects?
[I've also tried creating the Background setter with TextBlock.BackgroundProperty and that doesn't work either. And I tried setting BackgroundProperty to an ImageBrush which would be even better, but it couldn't find my image location.]
private void dgvDetail_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
string sHeader = e.Column.Header.ToString();
if (sHeader.Trim().ToLower() == "view")
{
e.Column.CellStyle = GetViewColumnStyle();
}
}
private Style GetViewColumnStyle()
{
Style oStyle = new Style(typeof(DataGridCell));
Setter oTextAlignment = new Setter(TextBlock.TextAlignmentProperty, TextAlignment.Center);
oStyle.Setters.Add(oTextAlignment);
Setter oBackground = new Setter(DataGridCell.BackgroundProperty, Brushes.LightGray);
oStyle.Setters.Add(oBackground);
Setter oForeground = new Setter(DataGridCell.ForegroundProperty, Brushes.Black);
oStyle.Setters.Add(oForeground);
Setter oBorderBrush = new Setter(DataGridCell.BorderBrushProperty, Brushes.Black);
oStyle.Setters.Add(oBorderBrush);
Setter oMargin = new Setter(DataGridCell.MarginProperty, new Thickness(2, 2, 2, 2));
oStyle.Setters.Add(oMargin);
return oStyle;
}
You are only styling the TextBlock inside. You should set DataGridCell.Template:
private Style GetViewColumnStyle()
{
// The TextBlock
FrameworkElementFactory textBlockFactory = new FrameworkElementFactory(typeof(TextBlock));
// DataBinding for TextBlock.Text
Binding textBinding = new Binding("YourTextBindingPath");
textBlockFactory.SetValue(TextBlock.TextProperty, textBinding);
//Other TextBlock attributes
textBlockFactory.SetValue(TextBlock.TextAlignmentProperty, TextAlignment.Center);
textBlockFactory.SetValue(TextBlock.BackgroundProperty, Brushes.LightGray);
textBlockFactory.SetValue(TextBlock.ForegroundProperty, Brushes.Black);
textBlockFactory.SetValue(TextBlock.MarginProperty, new Thickness(2, 2, 2, 2));
// The Border around your TextBlock
FrameworkElementFactory borderFactory = new FrameworkElementFactory(typeof(Border));
borderFactory.SetValue(Border.BorderBrushProperty, Brushes.Black);
borderFactory.SetValue(Border.BorderThicknessProperty, new Thickness(1, 1, 1, 1));
// Add The TextBlock to the Border as a child element
borderFactory.AppendChild(textBlockFactory);
// The Template for each DataGridCell = your Border that contains your TextBlock
ControlTemplate cellTemplate = new ControlTemplate();
cellTemplate.VisualTree = borderFactory;
// Setting Style.Template
Style oStyle = new Style(typeof(DataGridCell));
Setter templateSetter = new Setter(DataGridCell.TemplateProperty, cellTemplate);
oStyle.Setters.Add(templateSetter);
return oStyle;
}

WPF grid cells in C# no text

I need to show some data in a structured way with colored letters and rows with background colors.
I made a grid in a WPF Window. It shows the textboxes and some of the labels, but none of the text. Also the column header, last column, gridseperators, grid bot and left edges are invisible.
My grid is called propertiesView.
Code for adding header elements (labels)
private void AddHeaderElement(string text, int row, int col)
{
Label headerElement = new Label();
headerElement.Height = cellHeight;
headerElement.Width = cellWidth;
headerElement.DataContext = text;
headerElement.Background = headerBackground;
headerElement.BorderBrush = new SolidColorBrush(Color.FromRgb(120, 120, 120));
headerElement.BorderThickness = new Thickness(3);
propertiesView.Children.Add(headerElement);
Grid.SetRow(headerElement, row);
Grid.SetColumn(headerElement, col);
}
Code for adding cells
RichTextBox cell = new RichTextBox();
cell.Height = cellHeight;
cell.Width = cellWidth;
cell.ToolTip = toolTip;
cell.DataContext = text;
cell.Background = rowDifferent;
propertiesView.Children.Add(cell);
//box.SetValue(Grid.RowProperty, rowCount);
//box.SetValue(Grid.ColumnProperty, columnCount);
Grid.SetRow(cell, rowCount);
Grid.SetColumn(cell, columnCount);
Code for adding grid seperators
GridSplitter colSeperator = new GridSplitter();
colSeperator.Margin = new Thickness(-2.5, 0, 0, 0);
colSeperator.Width = 5;
colSeperator.ResizeDirection = GridResizeDirection.Columns;
colSeperator.ResizeBehavior = GridResizeBehavior.CurrentAndNext;
colSeperator.VerticalAlignment = VerticalAlignment.Stretch;
colSeperator.HorizontalAlignment = HorizontalAlignment.Left;
propertiesView.Children.Add(colSeperator);
Grid.SetColumn(colSeperator, 0);
Grid.SetRowSpan(colSeperator, totalRows + 1);
The tooltips do show the right text.
I tried using TextBox instead of RichTextBox and setting all this stuff in the class constructor instead of a seperate method.
Well it seems like you just never set the Content dependency property on your labels, or the Document of your RichTextBoxes.
For your labels, as you set the text parameter as the DataContext, you can just add something like
headerElement.SetBinding(Label.ContentProperty, new Binding());
Turns out I needed labels with textblocks, spans and runs.
Style can be added on the span (through properties like Foreground, TextDecoration or FontWeight). Add the text to the span inside a Run, then add all spans to a textblock, which is shown through a label.
Span span = new Span();
span.Foreground = Brushes.Black;
span.Inlines.Add(new Run("Text"));
textBlock.Inlines.Add(span);
Label cell = new Label();
cell.MinHeight = cellHeight;
cell.MaxWidth = cellWidth * 3;
cell.MinWidth = cellWidth;
cell.ToolTip = "toolTip";
cell.BorderThickness = new Thickness(2);
TextBlock cellText = new TextBlock();
cellText.HorizontalAlignment = HorizontalAlignment.Stretch;
cellText.TextWrapping = TextWrapping.WrapWithOverflow;
cell.Content = cellText;
The text works now, I should be able to get the gridseperators working.

Issue in creating combobox dynamically

I tried to create a ComboBox dynamically, but cannot create it.
Here is the code that I wrote.
ComboBox com_dynamic = new ComboBox();
com_dynamic.Height = 50;
com_dynamic.Width = 100;
LayoutRoot.Children.Add(com_dynamic);
tb.Margin = new Thickness(0, 145, 87, 0);
tb.VerticalAlignment = VerticalAlignment.Top;
tb.HorizontalAlignment = HorizontalAlignment.Right;
ComboBoxItem com_dynamic_item = new ComboBoxItem();
com_dynamic.AddChild(com_dynamic_item);
com_dynamic_item.Content = "item1";
You should also add the combobox to a container control. If you want to add it in the LayoutRoot, then this is the line you are missing.
LayoutRoot.Children.Add(com_dynamic);
You can reposition the combobox using its margin in the container.

Adding controls to GroupBox during runtime

I'm trying to create a GroupBox, add a Grid (or StackPanel) to it then put some TextBlocks on it, all during runtime. This is what i've tried
GroupBox groupBox1 = new GroupBox();
Grid grid1 = new Grid();
groupBox1.Width = 85;
groupBox1.Height = 60;
grid1.Height = 85;
grid1.Width = 60;
groupBox1.Content = grid1.Children.Add(textBlock1);
groupBox1.Margin = new Thickness(50, 50, 0, 0);
mainWindow.canvas.Children.Add(groupBox1);
But all I get is a groupbox with a thick white border with nothing in it.
As far as I can see a Grid.Children.Add returns an int and that's not what you want to set the content of the groupBox1 to.
An untested idea from me as a non WPF expert is to set the grid as the Content of your groupbox.
grid1.Children.Add(textBlock1);
groupBox1.Content = grid1;
For simple checkboxes i used this code :
var container = new FlowLayoutPanel
{
FlowDirection = FlowDirection.TopDown,
Dock = DockStyle.Fill
};
myGroupBox.Controls.Add(container);
foreach (var myText in textList)
{
var checkBox = new CheckBox
{
Text = myText
};
container.Controls.Add(checkBox);
}
Of course the foreach statement is just for the example :)

Categories

Resources