Multiple Pages withing one Form? C# - c#

I haven't done this for a while so am not quite sure how to do what I need, but I am sure it is pretty simple.
Basically, I have a form with a navigation pane. I want to make it so when a user clicks a button on that pane, say 'Home' it changes the content on the form, but doesn't actually switch to another form, if you get me?
As in, I would like the navigation pane to stay as it is the entire time and I only want the content of the form to change. It is almost like the 'TabControl' tool in Visual Studio's 'Toolbox' although instead of the tabs being directly above the content, I want them to be buttons displayed in a side pane. See the image below for a better understanding. Thanks!
(Side pane, and header stays the same regardless on what button is pressed, but the content changes.)

I'd implement this using UserControls. One UserControl is shown when a button is clicked. I'd create an interface (for example IView) that would be implemented by each UserControl that declares common functionality, like for example a method to check whether you can switch from one to another (like a form's OnClosing event) like this:
public interface IView
{
bool CanClose();
}
public UserControl View1: IView
{
public bool CanClose()
{
...
}
}
public UserControl View2: IView
{
public bool CanClose()
{
...
}
}
Then, switching views is quite easy:
private bool CanCurrentViewClose()
{
if (groupBox1.Controls.Count == 0)
return true;
IView v = groupBox1.Controls[0] as IView;
return v.CanClose();
}
private void SwitchView(IView newView)
{
if (groupBox1.Controls.Count > 0)
{
UserControl oldView = groupBox1.Controls[0] as UserControl;
groupBox1.Controls.Remove(oldView);
oldView.Dispose();
}
groupBox1.Controls.Add(newView);
newView.Dock = Dock.Fill;
}
In a button you could do this:
private void btnHome_Click(object sender, EventArgs e)
{
if (CanCurrentViewClose())
{
ViewHome v = new ViewHome();
// Further initialization of v here
SwitchView(v);
}
else
{
MessageBox.Show("Current View can not close!");
}
}
I've successfully used this approach on many occasions.

Simplest way is to place multiple Panels as content holders, implement content manager which keeps references to Panels and with it show/hide desired panel.
Simple, but for smaller apps it will work

You can simply use a TabControl which has as many TabPages as you want. For the TabControl you can set the Alignment property to Left

Related

Responsive Design UI with DockPanel Suite

I have design 1 winform to look like the picture. But I want the highlighted yellow part to be dockable with dockpanel suite reference. Is that do-able or any other suggestion of better design?
Right now the treeview is on the dockpanel and the red box part is a usercontrol placed in the same dockpanel. I tried to put the redbox as another form but I can't place it as it is in the picture. Also, this winform is need to be responsive so I put in the redbox part in a table layout panel.winform design and not familiar actually with the dockpanel suite reference. If there is a beginner tutorial that I can refer to, it would be much appreciated.
Current design:
There are two approach to your problem. First is dirty one and second elegant one. By dirty and elegant i mean way they display. Method they work are both same.
I will explain to you how to do it on empty form and you just implement that in your populated one.
First create new form.
Add 2 or more GroupBoxes to it
Add some items inside them (just to see if it works)
At the top of the each boxes add Button which will toggle visibility
Our form now looks like this and let's look of code behind it.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace Test
{
public partial class TestForm : Form
{
// This is property
bool ShowFirstGroupBox
{
get
{
// We let user get our property from private variable
return _ShowFirstGroupBox;
}
set
{
// When user change this property we do something based on that
switch(value)
{
case true:
groupBox1.Size = new Size(groupBox1.Width, FirstGroupBoxDefaultHeight);
break;
case false:
groupBox1.Size = new Size(groupBox1.Width, 55);
break;
}
_ShowFirstGroupBox = value;
}
}
bool ShowSecondGroupBox
{
get
{
return _ShowSecondGroupBox;
}
set
{
switch (value)
{
case true:
groupBox2.Size = new Size(groupBox1.Width, FirstGroupBoxDefaultHeight);
break;
case false:
groupBox2.Size = new Size(groupBox1.Width, 55);
break;
}
_ShowSecondGroupBox = value;
}
}
// We store our boxes current state ( TRUE = shown, FALSE = HIDDEN )
bool _ShowFirstGroupBox = true;
bool _ShowSecondGroupBox = true;
// We store our default height for groupboxes
int FirstGroupBoxDefaultHeight;
int SecondGroupBoxDefaultHeight;
public TestForm()
{
InitializeComponent();
// Assigning default height of our groupboxes
FirstGroupBoxDefaultHeight = groupBox1.Height;
SecondGroupBoxDefaultHeight = groupBox2.Height;
}
private void button1_Click_1(object sender, EventArgs e)
{
ShowFirstGroupBox = !(_ShowFirstGroupBox); // This sets our property value to opposite of this boolean
}
private void button1_Click_1(object sender, EventArgs e)
{
ShowSecondGroupBox = !(_ShowSecondGroupBox); // This sets our property value to opposite of this boolean
}
}
}
Now when we have code like this and press button it will collapse groupbox.
NOTE: Controls under groupbox are still on place but just hidden since they are child of groupbox and everything outside of bounds is not visible to user.
This is dirty way since i would like to display it much prettier with MINUS sign on the right side of the groupbox title so i do not have button inside it. To do this you would need to create custom control which inherits groupbox, add button to it and position it in title bar and create event for it. It is easy if you have ever tried creating custom controls but if you haven't and you think dirty approach is okay with you then do not try it.

How do I clear a user control from a winform?

This is probably a basic question, but I can't find answers because the terms are generic.
I am building a WinForm aplication. Its purpose is to set up memory in a certain chip. I think the best way to organize the application is to have a user control for each chip type, derived from a generic parent class. Think of the children as "iphone," "android" and "blackberry," derived from a parent class "phone".
VS2017 Designer has a Panel where I want the control to be. On startup, I generate an object of the base class and add it to the panel. When I press a button, the old object is deleted and replaced with a new one. Each class has just one control, a label with distinctive text.
The problem is, after I press the button, I see both texts. The panel's Controls collection has just one element, but I see the text from both objects. I have tried Refresh, Update and Invalidate withe the same results.
What do I have to do to make the old text "go away" so the only thing I see is the latest object?
private ChipMemBase ChipMemControl = new ChipMemBase();
public Form1()
{
InitializeComponent();
//tbFeedback.Text = string.Format(fmtString, 0, 1, 2, 3, 4, 5);
cbChipName.SelectedIndex = 0;
tbVersion.Text = Version;
OriginalWindowColor = tbFeedback.BackColor;
ShowChipMemControl();
PrintToFeedback(Version);
}
private void ShowChipMemControl()
{
var ctl = pnlChipMem.GetChildAtPoint(new Point(5,5));
if (null != ctl)
{
if (ctl != ChipMemControl)
{
pnlChipMem.Controls.Remove(ctl);
ctl.Dispose();
pnlChipMem.Update();
Refresh();
}
}
if (null != ChipMemControl)
{
pnlChipMem.Controls.Add(ChipMemControl);
}
}
private void btnMakeChipMemory_Click(object sender, EventArgs e)
{
ChipMemControl = new ChipMemGen2();
ShowChipMemControl();
}
Screenshots before and after clicking Create
Your ShowChipMemControl gets the control at point 5,5 and checks if it's a ChipMemControl then removes it.
I'm guessing that the reason it's not getting removed is that the control at point 5,5 is not a ChipMemControl.
You can use:
pnlChipMem.Controls.Clear()
to remove all the controls
Or:
ChipMemControl cmc = pnlChipMem.Controls.OfType<ChipMemBase>().FirstOrDefault();
if (cmc != null)
{
pnlChipMem.Controls.Remove(cmc);
cmc.Dispose();
}
To only remove the first instance of ChipMemBase on your pnlChipMem panel.
Got it. The problem was from inheritance, not window behavior. Control lblDefault in the base class, carrying the inconvenient text, was still present in the child class. I had to make it Public in the base class and remove it in the child class constructor:
InitializeComponent();
Controls.Remove(lblDefault);
lblDefault.Dispose();
lblDefault = null;
The clue was this article and project:
dynamically-and-remove-a-user-control

Implementing an options dialog

in my application i want to implement an options dialog like you have in VisualStudios if you go to Tools->Options in the menubar. How can i do this? My first idea was to use pages and navigation but maybe there's an easier approach?
It's probably not the easiest way but I wrote this snippet that match your goal and it's a good exercise.
In an empty Windows Forms project add a ListBox (listBox1) and a Panel (panel1). Then create 2 UserControls (UserControl1 and UserControl2), these will be the content that is shown when you click the list.
In your Form1 class we create a ListItem class that will contain your menu options as such:
public partial class Form1 : Form
{
public class ListItem
{
public string Text { get; set; }
public UserControl Value { get; set; }
public ListItem(string text, UserControl value)
{
Text = text;
Value = value;
}
};
...
}
After that you add items to the ListBox right after InitializeComponent() in Form1:
public Form1()
{
InitializeComponent();
listBox1.DisplayMember = "Text";
listBox1.ValueMember = "Value";
listBox1.Items.Add(new ListItem("Item1", new UserControl1()));
listBox1.Items.Add(new ListItem("Item2", new UserControl2()));
}
This will make it so when you use listBox1.SelectedItem it will return an object that you can cast to a ListItem and access the associated UserControl.
To make use of this behaviour, go to designmode and double-click the ListBox, this'll add code for the SelectedIndexChanged event. We use this event to display the UserControl in the Panel panel1. This will clear any old Panel content and add a selected UserControl:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
panel1.Controls.Clear();
UserControl control = (listBox1.SelectedItem as ListItem).Value;
if(control != null)
{
panel1.Controls.Add(control);
control.Dock = DockStyle.Fill;
}
}
I suggest you try adding a button or something to differentiate the UserControls and play around. Have fun! :)
You should create a new Window and show that as opposed to create a page and navigate to it. Then you would call .show() on the new window for it to show.
Then you would change the look of the new window to however you want, the same as editing pages.
If you build your options into a full object model that matches the structure of the options window, then the best way is to use whatever navigation-aware UI binding that your MVVM toolkit uses. The options window would start off as a new root level window to which you would bind the root of your options data model.
So, in short think of the options dialog as a mini-application that uses the same structure as your main MVVM application, but with a different data model root.
If you plan to allow the user to cancel the changes to the options, then you would want your options data model to be clonable so that you can populate the options window with the clone and then swap out the real options with the new data if the user presses OK on the options window. If they select cancel you can just throw the cloned object away and destroy the window.

Transfer value of Form to Usercontrol

I create a user control and add a textbox to it. In my windows form I add the user control i created and add a textbox and a button. How to copy the text I input from the textbox of Form to textbox of Usercontrol and vice versa. Something like
usercontrol.textBox1.text = textBox1.text
You could add to your User Control code a public property that delegates into the TextBox's Text property:
public string MyTxtBoxValue { get { return this.txtBox.Text; } }
And you could also have a setter to that, of course, if needed.
What you don't want to do, however, is exposing the whole TextBox by making it public. That is flawed.
From Form to Usercontrol
Form Code
public string ID
{
get { return textBox1.Text; }
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
userControl11.ID = ID;
}
Usercontrol Code
public string ID
{
set { textBox1.Text = value; }
}
There are multiple ways to access your user control text box data. One way to accomplish this would be to expose the text box on the user control at a scope that can be accessed via the form it's loaded on. Another way would be raising an event on the button click of the user control and subscribing to it on the parent form.
Although some stuff are inherited when creating a custom user control, for the most part you have to define your own properties. (like text value, etc..)
I would take a look at this:
http://msdn.microsoft.com/en-us/library/6hws6h2t.aspx
good luck!

How can I modify the visual state of a disabled checkbox to look enabled?

I am designing a comparison dialog (shows several widgets with their characteristics in a grid). There is a features section where all available features are listed with a check box for each one. If the part has that feature, the checkbox is checked. These checkboxes need to be read-only so I've isEnabled=false. However visually the checkboxes (and the label content) show as greyed out.
Here are some important points:
The checkbox is a visual indicator of whether a part has a feature. There is no requirement for interaction.
The requirement is for a checkbox; I'd have to convince the powers that be to use something different.
What I want is an easy way to style/controltemplate a checkbox (and it's content) so it looks enabled, but doesn't react to user input.
Microsoft provides some of their default styles on MSDN and you can find the default style for a checkbox here: http://msdn.microsoft.com/en-us/library/ms752319(v=vs.85).aspx. Copy this style into your project, remove the Trigger for IsEnabled and set the style for your checkboxes to this new style.
On a side note, I'd recommend copying the style into a separate ResourceDictionary for reusablitiy and to keep the style from cluttering up your xaml files.
Create a custom control by inheriting from CheckBox, and in its constructor create a Click handler for it. Within that Click handler, put the following code:
((CheckBox)sender).Checked = !((CheckBox)sender).Checked;
Here's a complete example.
For Windows Forms:
namespace System.Windows.Forms
{
public class UnChangingCheckBox : System.Windows.Forms.CheckBox
{
public UnChangingCheckBox()
{
this.Click += new EventHandler(UnChangingCheckBox_Click);
}
void UnChangingCheckBox_Click(object sender, EventArgs e)
{
((CheckBox)sender).Checked = !((CheckBox)sender).Checked;
}
}
}
For WPF:
namespace System.Windows.Controls
{
public class UnchangingCheckBox : System.Windows.Controls.CheckBox
{
public UnchangingCheckBox()
{
this.Click += new System.Windows.RoutedEventHandler(UnchangingCheckBox_Click);
}
void UnchangingCheckBox_Click(object sender, System.Windows.RoutedEventArgs e)
{
if (((CheckBox)sender).IsChecked.HasValue)
((CheckBox)sender).IsChecked = !((CheckBox)sender).IsChecked;
}
}
}
If you place the above code in a new class in your Windows Forms or WPF project, they'll appear as new tools in your toolbox. Then all you need to do is drag your new "UnchangingCheckBox" control onto your form where you were using a CheckBox. You don't need to do any coding on your form.
Using this approach your code will still be able to do everything you could do to a CheckBox (set its value, etc). It's only user interaction that's been disabled in a way that doesn't interfere with the visual style.
The solution suggested above works well for Windows Forms, but I see what you mean about WPF and the check mark appearing for a second.
Try this instead:
namespace System.Windows.Controls
{
public class UnchangingCheckbox : CheckBox
{
public UnchangingCheckbox()
{
this.IsReadOnly = true;
}
public bool IsReadOnly
{
get { return !this.IsHitTestVisible && !this.Focusable; }
set
{
this.IsHitTestVisible = !value;
this.Focusable = !value;
}
}
}
}
You acquire a property called "IsReadOnly", which by default is set to true, and has the behaviour you require without the annoying "checkmark appears for a second" behaviour.

Categories