I have a Panel with AutoScroll=true. I'd like to manually scroll the panel's VerticalScroll. I've tried both setting VerticalScroll.Value and Panel.ScrollControlIntoView(...).
However, both cases yielded the following result: The scrollbar does appear to have scrolled to the value but the panel's contents remain unmoved. Scrolling upwards shows an empty panel.
I'm trying to do this during startup. If I scroll directly to the control after a delay (from a thread), it works (though setting the scrollbar value doesn't).
Is there a better (synchronous) way of achieving what I'm looking for?
Use Shown event, for example:
private void Form1_Shown(object sender, EventArgs e)
{
this.panel1.ScrollControlIntoView(this.button1);
//Or if you need a special location:
//this.panel1.AutoScrollPosition = new Point(100, 100);
}
Related
In my application, I need to select the newly created document(note) when I go back to library. After library item is selected, the Library must be scrolled to the selected item.
My library's OnLoaded method:
private async void OnLoaded(object sender, RoutedEventArgs e)
{
await this.ViewModel.InitializeAsync();
// CollectionViewSource of my GridView being filled
ViewModel.CollectionChanging = true;
GroupInfoCVS.Source = ViewModel.GroupsCollection;
ViewModel.CollectionChanging = false;
// Loading Last selected item - THIS CHANGES SELECTION
ViewModel.LoadLastSelection();
}
After I call the LoadLastSelection method, selection is changed successfuly (I've tested). This is the method that is called after that (in our GridView's extended control):
private void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
this.SelectedItemsCount = this.SelectedItems.Count;
var newlySelectedItems = e.AddedItems;
if (newlySelectedItems.Any())
{
var item = newlySelectedItems.Last();
ScrollTo(item);
}
}
private void ScrollTo(object item)
{
UpdateLayout();
var itemUI = (FrameworkElement)this.ContainerFromItem(item);
if (itemUI != null)
{
_scrollViewer.UpdateLayout();
_scrollViewer.ChangeView(null, itemUI.ActualOffset.Y - itemUI.ActualHeight, null, false);
}
}
This also works for the most part. When itemUI is not null, the method scrolls successfully to the required item. The problems start when the items start to overflow the screen size. When items are completely hidden from the screen, they are virtualized. That means that ContainerFromItem returns null, so I can't take the offset properties. Keep in mind that this actually occurs before Library's OnLoaded method is finished.
Please, help me with some alternative to get such properties or other methods of scrolling, which will help me scroll successfully.
I've read a lot and tried using Dispatcher.RunAsync and ScrollIntoView methods, but I couldn't manage to produce any scrolling behavior. If you point me how to use them successfully, that would be a nice help too.
Here's what I've read (and tried):
ItemContainerGenerator.ContainerFromItem() returns null?
How to Know When a FrameworkElement Has Been Totally Rendered?
Is there a "All Children loaded" event in WPF
Let ListView scroll to selected item
Thanks in advance!
IMPORTANT: If you don't want to read all the conversation within the official answer, please read the solution in short here:
TemplatedControl's style had changed ScrollViewer's name from "ScrollViewer" to "LibraryScrollViewer" and that rendered ScrollIntoView method useless.
For GridView, the best way to achieve your needs is to call GridView.ScrollIntoView.
But you seem to have made similar attempts, and it does not to be successful, then the following points may help you:
1. Don't use GridView as a child element of ScrollViewer.
In your code, I see that you are calling the method of ScrollViewer.ChangeView to adjust the view scrolling, so it is speculated that you may put the GridView in the ScrollViewer, which is not recommended.
Because there is a ScrollViewer inside the GridView, and its ScrollIntoView method is to change the scroll area of the internal ScrollViewer. When there is a ScrollViewer outside, the ScrollViewer inside the GridView will lose the scrolling ability, thus making the ScrollIntoView method invalid.
2. Implement the Equals method of the data class.
If your data class is not a simple type (such as String, Int32, etc.), then implementing the Equals method of the data class will help the GridView to find the corresponding item.
Thanks.
I'm trying to make it to where a panel becomes visible and it sent to the front so it can be seen and interacted with, like this.
private void SettingsButton_Click(object sender, EventArgs e)
{
SettingsPanel.Visible = true;
SettingsPanel.BringToFront();
}
The problem is that after clicking a few of the buttons, it will either display the wrong panel or none at all. Is there a way to fix this?
EDIT: Before y'all ask, i'm using WinForms.
OK, so I was wrong, WinForms is smarter than I thought. Here's a test you can do. I'm not exactly sure what you are trying to do, but this should help you along. To start, we're going to build a small WinForms app. With one exception, we aren't going to set any properties of the controls we drop on the screen:
Create a new WinForms app
In the designer, drop a Panel (which will be named panel1) on the form
In the properties pane, set the BorderStyle to FixedSingle (that's the only property we are going to set)
Make two copies of that panel (panel2 and panel3). Position them so that panels do not overlap at all.
On each panel drop a couple of controls (I put labels (labels 1-3) and textboxes (also 1-3)) on each one
Beside each panel (arranged so that there is no overlap) drop three buttons on the form (buttons 1-3) make it so that visually, each button is associated with the similarly numbered panel
Duplicate panel3 including its contained controls (so that you get panel4, label4 and textbox4). Position the duplicate so that it significantly overlaps panel 3
Now we're going to look at the code that the designer creates for your form. Don't mess with this code (you can, but if you don't know what you are doing, it can turn out bad - and, we're keeping this simple).
In the Solution Explorer click the unfilled triangle to the left of Form1.cs. Note that it rotates and turns solid. Also note that Form1.Designer.cs is displayed. That's a normally hidden source file that contains all the designer created code that corresponds with the form and the controls you dropped on it.
Open Form1.Designer.cs
Click the little grey plus sign icon next to Windows Form Designer generated code
Inspect the file. Note that every action you did in the designer has a corresponding line of code in the Designer.cs file (more or less)
Look at the code for one of the panels (say panel1).
See that it includes:
this.panel1.Controls.Add(this.textBox1);
this.panel1.Controls.Add(this.label1);
Scroll all the way down to the Form1 code and see that the panels and buttons get added to the Form's Controls collection:
Like:
this.Controls.Add(this.button3);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Controls.Add(this.panel4);
this.Controls.Add(this.panel3);
this.Controls.Add(this.panel2);
this.Controls.Add(this.panel1);
Note that the order is reversed. The order is important, it sets the Z-Order (i.e., what overlaps what) for the form and the controls on the form.
Wiring up the buttons
Select all three buttons and press <Enter>. This will open the Form1.cs file and generate three button click handlers that you can fill in.
Use this code for the three button handlers:
private void button1_Click(object sender, EventArgs e) {
var wasVisible = panel1.Visible;
panel1.Visible = !wasVisible;
}
private void button2_Click(object sender, EventArgs e) {
panel2.BringToFront();
}
private void button3_Click(object sender, EventArgs e) {
panel3.BringToFront();
}
The first one will toggle the first panel's visibility (I put in an extra variable so you can set a breakpoint and see what's going on). The second one brings panel2 to the front, changing its Z-Order (it's called Z-Order because the position on the screen is measure in X and Y, which the overlap position is related to the "depth" of the screen, or the Z-coordinate). The last one does the same thing to panel3.
Run the program.
When you press the first button, the first panel and its controls disappear (this surprised me, WinForms is smarter than I thought)
When you press the second button, nothing appears to happen. This is because the only thing that panel2 intersects is the form, and panel2 already covers the form, so you don't see any effect. (and because WinForms is smarter than I thought)
When you press the third button, panel2 (and it's controls) jump to the front of the stack of controls, covering the intersecting part of panel4.
Does this help you understand how Visible and BringToFront() work?
What you're describing is similar to a TabControl alternative. Here's an example:
You can manage the current panel simply by making it visible and docked to fill. Hide the other panels.
public partial class FormTabsAlternative
: Form
{
int m_current = 0;
List<Panel> m_tabs = new List<Panel>();
public FormTabsAlternative()
{
InitializeComponent();
AddTab(pnl1);
AddTab(pnl2);
AddTab(pnl3);
AddTab(pnl4);
SetUpTabsAndButtons();
}
private void AddTab(Panel pnl)
{
m_tabs.Add(pnl);
pnl.Dock = DockStyle.Fill;
}
private void OnLeftClick(object sender, EventArgs e)
{
if (m_current > 0)
{
m_current--;
SetUpTabsAndButtons();
}
}
private void OnRightClick(object sender, EventArgs e)
{
if (m_current < m_tabs.Count - 1)
{
m_current++;
SetUpTabsAndButtons();
}
}
private void SetUpTabsAndButtons()
{
for (int index = 0; index < m_tabs.Count; index++)
{
var panel = m_tabs[index];
panel.Visible = index == m_current;
}
btnLeft .Enabled = m_current > 0;
btnRight.Enabled = m_current < m_tabs.Count - 1;
}
}
I have a TabControl with AutoScroll set to true on tabpages. The tabpage contains a RichTextBox, which is bigger in height that the page, so vertical scrollbar appears on a TabPage. If I scroll the page down and then click on the RichTextBox, the page scrolls back to top. Any ideas on how to prevent such behaviour?
UPD: Here is a sample project which can reproduce the issue. The issue occurs when the RichTextBox receives focus. E.g. scroll tabPage1 down, then select tabPage2, return to tabPage1 and click on the RichTextBox.
Well, after a bit of struggling I've finally found a solution here. All I had to do was to create my own class inherited from TabPage and override the ScrollToControl method, making it return DisplayRectangle.Location.
This happens due to the fact that once you select the richTextBox and it is "out of sight" it goes to the current position(which in your case is not visible or at the top). If you select the richTextBox first and then scroll you will avoid this. One way you can do this is to Select() the richTextBox on application start.
Add this:
private void Form1_Load(object sender, EventArgs e)
{
richTextBox1.Select();
}
EDIT:
You can also add the Select() on TabIndexChanged as the behavior will reoccur if you change Tabs.
The answer while correct was difficult for me to initially understand without seeing the code.
Perhaps this helps others.
public class CustomTabPage : System.Windows.Forms.TabPage
{
protected override System.Drawing.Point ScrollToControl(System.Windows.Forms.Control activeControl)
{
//return base.ScrollToControl(activeControl);
return activeControl.DisplayRectangle.Location;
}
}
After defining your custom tabpage class, inherit now from this class in your form with your TabControl.
private CustomTabPage tpJobSetup;
I'm trying to center my checkboxes in a TableLayoutPanel, but they always end up looking left-aligned due to the nature of the checkbox control. See picture below:
I want each rows checks to be left-aligned, but for it to appear more centered. Something like the following:
I've checked around online, and I can center the checkboxes by setting AnchorStyles.None which is not what I want, because then the checkboxes are not aligned. I have them set to Dock.Fill so you can click anywhere in the cell to activate the checkbox.
I'm currently just padding my table to achieve a similar effect, but it's by far not an acceptable solution long-term. Also, padding the cells will line break the checkbox text without taking up all the available space on the row (since some of the row is being eaten by padding). The same goes for using a spacer-cell on the left of the table, not an ideal solution.
Does anyone have any ideas? Thanks!
This may work for you:
Set all the ColumnStyles of your TableLayoutPanel as .SizeType = SizeType.AutoSize.
Set your TableLayoutPanel.AutoSize = true and TableLayoutPanel.AutoSizeMode = AutoSizeMode.GrowAndShrink;
Add this code to center your checkboxes (as well as your TableLayoutPanel) dynamically:
//SizeChanged event handler of your tableLayoutPanel1
private void tableLayoutPanel1_SizeChanged(object sender, EventArgs e){
//We just care about the horizontal position
tableLayoutPanel1.Left = (tableLayoutPanel1.Parent.Width - tableLayoutPanel1.Width)/2;
//you can adjust the vertical position if you need.
}
UPDATE
As for your added question, I think we have to change some things:
Set your CheckBox AutoSize to false. The solution before requires it to be true.
Add more code (beside the code above):
int checkWidth = CheckBoxRenderer.GetGlyphSize(yourCheckBox.CreateGraphics(),System.Windows.Forms.VisualStyles.CheckBoxState.MixedNormal).Width;
//TextChanged event handler of your CheckBoxes (used for all the checkBoxes)
private void checkBoxes_TextChanged(object sender, EventArgs e){
UpdateCheckBoxSize((CheckBox)sender);
}
//method to update the size of CheckBox, the size is changed when the CheckBox's Font is bolded and AutoSize = true.
//However we set AutoSize = false and we have to make the CheckBox wide enough
//to contain the bold version of its Text.
private void UpdateCheckBoxSize(CheckBox c){
c.Width = TextRenderer.MeasureText(c.Text, new Font(c.Font, FontStyle.Bold)).Width + 2 * checkWidth;
}
//initially, you have to call UpdateCheckBoxSize
//this code can be placed in the form constructor
foreach(CheckBox c in tableLayoutPanel1.Controls.OfType<CheckBox>())
UpdateCheckBoxSize(c);
//add this to make your CheckBoxes centered even when the form containing tableLayoutPanel1 resizes
//This can also be placed in the form constructor
tableLayoutPanel1.Parent.SizeChanged += (s,e) => {
tableLayoutPanel1.Left = (tableLayoutPanel1.Parent.Width - tableLayoutPanel1.Width)/2;
};
Instead of having the checkboxes in cells, having each one inside a panel all inside a groupbox will allow the checkboxes to fill each panel and have a click able area around them. then with the groupbox dock set to fill and the panels' anchors set to top,bottom they all stay centered.
When i render contextmenustrip, it gets render at the top left of my PC Screen. I have a listview, which contains 5-6 items and on right click of each item, the context Menu strip gets displayed.Also i need to change the color of context menu strip including backgrounds and text as well.
Thanks in advance!
By far the simplest way is to just set the ListView.ContextMenuStrip property to your CMS, everything is automatic then. You can do so in the designer.
If you need a custom handler for some reason, to check if the right item was clicked for example, then you can call the Show() method property with code like this:
private void listView1_MouseClick(object sender, MouseEventArgs e) {
if (allowContextMenu(listView1.SelectedItems) {
contextMenuStrip1.Show(listView1, e.Location);
}
}
You haven't shown any code, but if you're not calling the Show overload that takes a control as a parameter, the new Point(0, 0) that your obviously passing will put the menu in the upper left of the screen.