diff --git a/src/System.Windows.Forms.Design.Editors/src/System/ComponentModel/Design/MultilineStringEditor.cs b/src/System.Windows.Forms.Design.Editors/src/System/ComponentModel/Design/MultilineStringEditor.cs index 781b73e021f..d587f05b0d5 100644 --- a/src/System.Windows.Forms.Design.Editors/src/System/ComponentModel/Design/MultilineStringEditor.cs +++ b/src/System.Windows.Forms.Design.Editors/src/System/ComponentModel/Design/MultilineStringEditor.cs @@ -2,20 +2,17 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; using System.Collections; using System.Diagnostics; using System.Drawing; using System.Drawing.Design; using System.Globalization; using System.Runtime.InteropServices; -using System.Text; using System.Windows.Forms; using System.Windows.Forms.Design; using Microsoft.Win32; - -using IComDataObject = System.Runtime.InteropServices.ComTypes.IDataObject; using static Interop; +using IComDataObject = System.Runtime.InteropServices.ComTypes.IDataObject; namespace System.ComponentModel.Design { @@ -478,7 +475,7 @@ internal OleCallback(RichTextBox owner) public HRESULT GetNewStorage(out Ole32.IStorage storage) { Debug.WriteLineIf(RichTextDbg.TraceVerbose, "IRichTextBoxOleCallback::GetNewStorage"); - + Ole32.ILockBytes pLockBytes = Ole32.CreateILockBytesOnHGlobal(IntPtr.Zero, true); Debug.Assert(pLockBytes != null, "pLockBytes is NULL!"); @@ -560,7 +557,7 @@ public HRESULT QueryAcceptData(IComDataObject lpdataobj, IntPtr lpcfFormat, uint return HRESULT.E_FAIL; } - + return HRESULT.E_NOTIMPL; } @@ -584,20 +581,10 @@ public HRESULT GetDragDropEffect(BOOL fDrag, int grfKeyState, ref int pdwEffect) public HRESULT GetContextMenu(short seltype, IntPtr lpoleobj, ref Richedit.CHARRANGE lpchrg, out IntPtr hmenu) { - TextBox tb = new TextBox - { - Visible = true - }; - ContextMenu cm = tb.ContextMenu; - if (cm == null || _owner.ShortcutsEnabled == false) - { - hmenu = IntPtr.Zero; - } - else - { - hmenu = cm.Handle; - } + Debug.WriteLineIf(RichTextDbg.TraceVerbose, "IRichTextBoxOleCallback::GetContextMenu"); + // do nothing, we don't have ContextMenu any longer + hmenu = IntPtr.Zero; return HRESULT.S_OK; } } diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ControlDesigner.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ControlDesigner.cs index 3343fa42ae8..899a271b5e9 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ControlDesigner.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ControlDesigner.cs @@ -462,11 +462,6 @@ protected override void Dispose(bool disposing) UnhookChildControls(Control); } - if (ContextMenu != null) - { - ContextMenu.Disposed -= new EventHandler(DetachContextMenu); - } - if (_designerTarget != null) { _designerTarget.Dispose(); @@ -514,38 +509,6 @@ private interface IDesignerTarget : IDisposable void DefWndProc(ref Message m); } - private void DetachContextMenu(object sender, EventArgs e) - { - ContextMenu = null; - } - - private ContextMenu ContextMenu - { - get => (ContextMenu)ShadowProperties["ContextMenu"]; - set - { - ContextMenu oldValue = (ContextMenu)ShadowProperties["ContextMenu"]; - - if (oldValue != value) - { - EventHandler disposedHandler = new EventHandler(DetachContextMenu); - - if (oldValue != null) - { - oldValue.Disposed -= disposedHandler; - } - - ShadowProperties["ContextMenu"] = value; - - if (value != null) - { - value.Disposed += disposedHandler; - } - } - - } - } - private void DataSource_ComponentRemoved(object sender, ComponentEventArgs e) { // It is possible to use the control designer with NON CONTROl types. @@ -1598,7 +1561,7 @@ protected override void PreFilterProperties(IDictionary properties) base.PreFilterProperties(properties); PropertyDescriptor prop; // Handle shadowed properties - string[] shadowProps = new string[] { "Visible", "Enabled", "ContextMenu", "AllowDrop", "Location", "Name" }; + string[] shadowProps = new string[] { "Visible", "Enabled", "AllowDrop", "Location", "Name" }; Attribute[] empty = Array.Empty(); for (int i = 0; i < shadowProps.Length; i++) diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DocumentDesigner.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DocumentDesigner.cs index 0d464f9b95c..2587452c9f5 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DocumentDesigner.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DocumentDesigner.cs @@ -22,9 +22,6 @@ public class DocumentDesigner : ScrollableControlDesigner, IRootDesigner, IToolb { static internal IDesignerSerializationManager manager; - //our menu editor service - protected IMenuEditorService menuEditorService = null; - /// /// We override our selectino rules to make the document non-sizeable. /// @@ -106,45 +103,6 @@ protected override void OnCreateHandle() throw new NotImplementedException(SR.NotImplementedByDesign); } - internal virtual void DoProperMenuSelection(ICollection selComponents) - { - foreach (object obj in selComponents) - { - if (obj is ContextMenu cm) - { - menuEditorService.SetMenu((Menu)obj); - } - else - { - if (obj is MenuItem item) - { - //before we set the selection, we need to check if the item belongs the current menu, if not, we need to set the menu editor to the appropiate menu, then set selection - MenuItem parent = item; - while (parent.Parent is MenuItem) - { - parent = (MenuItem)parent.Parent; - } - - if (menuEditorService.GetMenu() != parent.Parent) - { - menuEditorService.SetMenu(parent.Parent); - } - - //ok, here we have the correct editor selected for this item. Now, if there's only one item selected, then let the editor service know, if there is more than one - then the selection was done through themenu editor and we don't need to tell it - if (selComponents.Count == 1) - { - menuEditorService.SetSelection(item); - } - } - //Here, something is selected, but the menuservice isn't interested so, we'll collapse our active menu accordingly - else - { - menuEditorService.SetMenu(null); - } - } - } - } - /// /// Determines if a MenuEditorService has already been started. If not, /// this method will create a new instance of the service. diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/FormDocumentDesigner.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/FormDocumentDesigner.cs index 1fd8d3867cc..7518eae37a6 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/FormDocumentDesigner.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/FormDocumentDesigner.cs @@ -20,10 +20,6 @@ internal class FormDocumentDesigner : DocumentDesigner { private Size _autoScaleBaseSize = Size.Empty; private bool _inAutoscale = false; - private int _heightDelta = 0; - private bool _isMenuInherited; //indicates if the 'active menu' is inherited - private bool _hasMenu = false; - private InheritanceAttribute _inheritanceAttribute; private bool _initializing = false; private bool _autoSize = false; private ToolStripAdornerWindowService _toolStripAdornerWindowService = null; @@ -126,13 +122,6 @@ private Size ClientSize set { IDesignerHost host = (IDesignerHost)GetService(typeof(IDesignerHost)); - if (host != null) - { - if (host.Loading) - { - _heightDelta = GetMenuHeight(); - } - } ((Form)Component).ClientSize = value; } } @@ -157,59 +146,6 @@ private bool IsMdiContainer } } - /// - /// Returns true if the active menu is an inherited component. We use this to determine if we need to resize the base control or not. - /// - private bool IsMenuInherited - { - get - { - if (_inheritanceAttribute == null && Menu != null) - { - _inheritanceAttribute = (InheritanceAttribute)TypeDescriptor.GetAttributes(Menu)[typeof(InheritanceAttribute)]; - if (_inheritanceAttribute.Equals(InheritanceAttribute.NotInherited)) - { - _isMenuInherited = false; - } - else - { - _isMenuInherited = true; - } - } - return _isMenuInherited; - } - } - - /// - /// Accessor method for the menu property on control. We shadow this property at design time. - /// - internal MainMenu Menu - { - get => (MainMenu)ShadowProperties["Menu"]; - set - { - if (value == ShadowProperties["Menu"]) - { - return; - } - ShadowProperties["Menu"] = value; - IDesignerHost host = (IDesignerHost)GetService(typeof(IDesignerHost)); - if (host != null && !host.Loading) - { - EnsureMenuEditorService(value); - if (menuEditorService != null) - { - menuEditorService.SetMenu(value); - } - } - - if (_heightDelta == 0) - { - _heightDelta = GetMenuHeight(); - } - } - } - /// /// Opacity property on control. We shadow this property at design time. /// @@ -356,69 +292,6 @@ protected override void Dispose(bool disposing) base.Dispose(disposing); } - internal override void DoProperMenuSelection(ICollection selComponents) - { - foreach (object obj in selComponents) - { - //first check to see if our selection is any kind of menu: main, context, item AND the designer for the component is this one - if (obj is Menu menu) - { - //if it's a menu item, set the selection - if (menu is MenuItem item) - { - Menu currentMenu = menuEditorService.GetMenu(); - // before we set the selection, we need to check if the item belongs the current menu, if not, we need to set the menu editor to the appropiate menu, then set selection - MenuItem parent = item; - while (parent.Parent is MenuItem) - { - parent = (MenuItem)parent.Parent; - } - - if (!(currentMenu == parent.Parent)) - { - menuEditorService.SetMenu(parent.Parent); - } - - // ok, here we have the correct editor selected for this item. Now, if there's only one item selected, then let the editor service know, if there is more than one - then the selection was done through the menu editor and we don't need to tell it - if (selComponents.Count == 1) - { - menuEditorService.SetSelection(item); - } - } - // here, either it's a main or context menu, even if the menu is the current one, we still want to call this "SetMenu" method, 'cause that'll collapse it and remove the focus - else - { - menuEditorService.SetMenu(menu); - } - return; - } - // Here, something is selected, but it is in no way, shape, or form a menu so, we'll collapse our active menu accordingly - else - { - if (Menu != null && Menu.MenuItems.Count == 0) - { - menuEditorService.SetMenu(null); - } - else - { - menuEditorService.SetMenu(Menu); - } - NativeMethods.SendMessage(Control.Handle, WindowMessages.WM_NCACTIVATE, 1, 0); - } - } - } - - /// - /// Determines if a MenuEditorService has already been started. If not, this method will create a new instance of the service. We override this because we want to allow any kind of menu to start the service, not just ContextMenus. - /// - protected override void EnsureMenuEditorService(IComponent c) - { - if (menuEditorService == null && c is Menu) - { - menuEditorService = (IMenuEditorService)GetService(typeof(IMenuEditorService)); - } - } - private void EnsureToolStripWindowAdornerService() { if (_toolStripAdornerWindowService == null) @@ -427,29 +300,6 @@ private void EnsureToolStripWindowAdornerService() } } - /// - /// Gets the current menu height so we know how much to increment the form size by - /// - private int GetMenuHeight() - { - if (Menu == null || (IsMenuInherited && _initializing)) - { - return 0; - } - - if (menuEditorService != null) - { - // there is a magic property on teh menueditorservice that gives us this information. Unfortuantely, we can't compute it ourselves -- the menu shown in the designer isn't a windows one so we can't ask windows. - PropertyDescriptor heightProp = TypeDescriptor.GetProperties(menuEditorService)["MenuHeight"]; - if (heightProp != null) - { - int height = (int)heightProp.GetValue(menuEditorService); - return height; - } - } - return SystemInformation.MenuHeight; - } - /// /// Initializes the designer with the given component. The designer can get the component's site and request services from it in this call. /// @@ -479,21 +329,6 @@ public override void Initialize(IComponent component) /// private void OnComponentAdded(object source, ComponentEventArgs ce) { - if (ce.Component is Menu) - { - IDesignerHost host = (IDesignerHost)GetService(typeof(IDesignerHost)); - if (host != null && !host.Loading) - { - //if it's a MainMenu & we don't have one set for the form yet, then do it... - if (ce.Component is MainMenu && !_hasMenu) - { - PropertyDescriptor menuProp = TypeDescriptor.GetProperties(Component)["Menu"]; - Debug.Assert(menuProp != null, "What the happened to the Menu property"); - menuProp.SetValue(Component, ce.Component); - _hasMenu = true; - } - } - } if (ce.Component is ToolStrip && _toolStripAdornerWindowService == null) { IDesignerHost host = (IDesignerHost)GetService(typeof(IDesignerHost)); @@ -509,21 +344,6 @@ private void OnComponentAdded(object source, ComponentEventArgs ce) /// private void OnComponentRemoved(object source, ComponentEventArgs ce) { - if (ce.Component is Menu) - { - //if we deleted the form's mainmenu, set it null... - if (ce.Component == Menu) - { - PropertyDescriptor menuProp = TypeDescriptor.GetProperties(Component)["Menu"]; - Debug.Assert(menuProp != null, "What the happened to the Menu property"); - menuProp.SetValue(Component, null); - _hasMenu = false; - } - else if (menuEditorService != null && ce.Component == menuEditorService.GetMenu()) - { - menuEditorService.SetMenu(Menu); - } - } if (ce.Component is ToolStrip && _toolStripAdornerWindowService != null) { _toolStripAdornerWindowService = null; @@ -541,24 +361,6 @@ private void OnComponentRemoved(object source, ComponentEventArgs ce) } } - /// - /// We're watching the handle creation in case we have a menu editor. If we do, the menu editor will have to be torn down and recreated. - /// - protected override void OnCreateHandle() - { - if (Menu != null && menuEditorService != null) - { - menuEditorService.SetMenu(null); - menuEditorService.SetMenu(Menu); - } - - if (_heightDelta != 0) - { - ((Form)Component).Height += _heightDelta; - _heightDelta = 0; - } - } - // Called when our document becomes active. We paint our form's border the appropriate color here. private void OnDesignerActivate(object source, EventArgs evevent) { @@ -612,23 +414,6 @@ private void OnLoadComplete(object source, EventArgs evevent) svc.SyncSelection(); } - // if there is a menu and we need to update our height because of it, do it now. - if (_heightDelta == 0) - { - _heightDelta = GetMenuHeight(); - } - - if (_heightDelta != 0) - { - form.Height += _heightDelta; - _heightDelta = 0; - } - - // After loading the form if the ControlBox and ShowInTaskbar properties are false, the form will be sized incorrectly. This is due to the text property being set after the ControlBox and ShowInTaskbar properties, which causes windows to recalculate our client area wrong. The reason it does this is because after setting the ShowInTaskbar and ControlBox it assumes we have no titlebar, and bases the clientSize we pass it on that. In reality our ClientSize DOES depend on having a titlebar, so windows gets confused. This only happens at designtime, because at runtime our special DesignTime only MainMenu is not around to mess things up. Because of this, I'm adding this nasty workaround to correctly update the height at design time. - if (!form.ControlBox && !form.ShowInTaskbar && !string.IsNullOrEmpty(form.Text) && Menu != null && !IsMenuInherited) - { - form.Height += SystemInformation.CaptionHeight + 1; - } form.PerformLayout(); } @@ -642,7 +427,7 @@ protected override void PreFilterProperties(IDictionary properties) PropertyDescriptor prop; base.PreFilterProperties(properties); // Handle shadowed properties - string[] shadowProps = new string[] { "Opacity", "Menu", "IsMdiContainer", "Size", "ShowInTaskBar", "WindowState", "AutoSize", "AcceptButton", "CancelButton" }; + string[] shadowProps = new string[] { "Opacity", "IsMdiContainer", "Size", "ShowInTaskBar", "WindowState", "AutoSize", "AcceptButton", "CancelButton" }; Attribute[] empty = Array.Empty(); for (int i = 0; i < shadowProps.Length; i++) { @@ -683,13 +468,6 @@ private unsafe void WmWindowPosChanging(ref Message m) updateSize = host.Loading; } } - // we want to update the size if we have a menu and... - // 1) we're doing an autoscale - // 2) we're loading a form without an inherited menu (inherited forms will already have the right size) - if (updateSize && Menu != null && (wp->flags & NativeMethods.SWP_NOSIZE) == 0 && (IsMenuInherited || _inAutoscale)) - { - _heightDelta = GetMenuHeight(); - } } /// diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/IMenuEditorService.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/IMenuEditorService.cs deleted file mode 100644 index 25c4ee82534..00000000000 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/IMenuEditorService.cs +++ /dev/null @@ -1,38 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System.Windows.Forms.Design -{ - /// - /// Provides access to the menu editing service. - /// - public interface IMenuEditorService - { - /// - /// Gets the current menu. - /// - Menu GetMenu(); - - /// - /// Gets a value indicating whether the current menu is active. - /// - bool IsActive(); - - /// - /// Sets the current menu visible - /// on the form. - /// - void SetMenu(Menu menu); - - /// - /// Sets the selected menu item of the current menu. - /// - void SetSelection(MenuItem item); - - /// - /// Allows the editor service to intercept Win32 messages. - /// - bool MessageFilter(ref Message m); - } -} diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripDesigner.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripDesigner.cs index 89e2581e87a..810b41b1793 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripDesigner.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripDesigner.cs @@ -1289,47 +1289,41 @@ protected override ControlBodyGlyph GetControlGlyph(GlyphSelectionType selection } } - // Check if menuEditor is present and active... - IMenuEditorService menuEditorService = (IMenuEditorService)GetService(typeof(IMenuEditorService)); - if (menuEditorService == null || (menuEditorService != null && !menuEditorService.IsActive())) + // now walk the ToolStrip and add glyphs for each of it's children + foreach (ToolStripItem item in ToolStrip.Items) { - - // now walk the ToolStrip and add glyphs for each of it's children - foreach (ToolStripItem item in ToolStrip.Items) + if (item is DesignerToolStripControlHost) { - if (item is DesignerToolStripControlHost) - { - continue; - } - // make sure it's on the ToolStrip... - if (item.Placement == ToolStripItemPlacement.Main) + continue; + } + // make sure it's on the ToolStrip... + if (item.Placement == ToolStripItemPlacement.Main) + { + ToolStripItemDesigner itemDesigner = (ToolStripItemDesigner)_host.GetDesigner(item); + if (itemDesigner != null) { - ToolStripItemDesigner itemDesigner = (ToolStripItemDesigner)_host.GetDesigner(item); - if (itemDesigner != null) + bool isPrimary = (item == primarySelection); + if (isPrimary) { - bool isPrimary = (item == primarySelection); - if (isPrimary) - { - ((ToolStripItemBehavior)toolStripBehavior)._dragBoxFromMouseDown = _dragBoxFromMouseDown; - } + ((ToolStripItemBehavior)toolStripBehavior)._dragBoxFromMouseDown = _dragBoxFromMouseDown; + } - // Get Back the Current Bounds if current selection is not a primary selection - if (!isPrimary) - { - item.AutoSize = (itemDesigner != null) ? itemDesigner.AutoSize : true; - } + // Get Back the Current Bounds if current selection is not a primary selection + if (!isPrimary) + { + item.AutoSize = (itemDesigner != null) ? itemDesigner.AutoSize : true; + } - Rectangle itemBounds = itemDesigner.GetGlyphBounds(); - Control parent = ToolStrip.Parent; - Rectangle parentBounds = BehaviorService.ControlRectInAdornerWindow(parent); - if (IsGlyphTotallyVisible(itemBounds, parentBounds) && item.Visible) - { - // Add Glyph ONLY AFTER item width is changed... - ToolStripItemGlyph bodyGlyphForItem = new ToolStripItemGlyph(item, itemDesigner, itemBounds, toolStripBehavior); - itemDesigner.bodyGlyph = bodyGlyphForItem; - //Add ItemGlyph to the Collection - selMgr.BodyGlyphAdorner.Glyphs.Add(bodyGlyphForItem); - } + Rectangle itemBounds = itemDesigner.GetGlyphBounds(); + Control parent = ToolStrip.Parent; + Rectangle parentBounds = BehaviorService.ControlRectInAdornerWindow(parent); + if (IsGlyphTotallyVisible(itemBounds, parentBounds) && item.Visible) + { + // Add Glyph ONLY AFTER item width is changed... + ToolStripItemGlyph bodyGlyphForItem = new ToolStripItemGlyph(item, itemDesigner, itemBounds, toolStripBehavior); + itemDesigner.bodyGlyph = bodyGlyphForItem; + //Add ItemGlyph to the Collection + selMgr.BodyGlyphAdorner.Glyphs.Add(bodyGlyphForItem); } } } @@ -1468,17 +1462,10 @@ public override void InitializeNewComponent(IDictionary defaultValues) { Control parent = defaultValues["Parent"] as Control; Form parentForm = _host.RootComponent as Form; - MainMenu parentMenu = null; FormDocumentDesigner parentFormDesigner = null; if (parentForm != null) { parentFormDesigner = _host.GetDesigner(parentForm) as FormDocumentDesigner; - if (parentFormDesigner != null && parentFormDesigner.Menu != null) - { - // stash off the main menu while we initialize - parentMenu = parentFormDesigner.Menu; - parentFormDesigner.Menu = null; - } } ToolStripPanel parentPanel = parent as ToolStripPanel; @@ -1501,11 +1488,6 @@ public override void InitializeNewComponent(IDictionary defaultValues) if (parentFormDesigner != null) { - //Add MenuBack - if (parentMenu != null) - { - parentFormDesigner.Menu = parentMenu; - } //Set MainMenuStrip property if (ToolStrip is MenuStrip) { diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripDropDownDesigner.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripDropDownDesigner.cs index 610752578d1..cfd49be1ed4 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripDropDownDesigner.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripDropDownDesigner.cs @@ -6,7 +6,6 @@ using System.ComponentModel; using System.ComponentModel.Design; using System.Configuration; -using System.Diagnostics.CodeAnalysis; using System.Drawing; using System.Globalization; using System.Windows.Forms.Design.Behavior; @@ -26,7 +25,6 @@ internal class ToolStripDropDownDesigner : ComponentDesigner private bool selected; private ControlBodyGlyph dummyToolStripGlyph; private uint _editingCollection = 0; // non-zero if the collection editor is up for this ToolStrip or a child of it. - MainMenu parentMenu = null; FormDocumentDesigner parentFormDesigner = null; internal ToolStripMenuItem currentParent = null; private INestedContainer nestedContainer = null; //NestedContainer for our DesignTime MenuItem. @@ -293,11 +291,6 @@ private void HideMenu() { return; } - //Add MenuBack - if (parentMenu != null && parentFormDesigner != null) - { - parentFormDesigner.Menu = parentMenu; - } selected = false; if (host.RootComponent is Control form) @@ -649,20 +642,18 @@ public void ShowMenu(ToolStripItem selectedItem) { return; } + Control parent = designMenu.Parent as Control; if (parent is Form parentForm) { parentFormDesigner = host.GetDesigner(parentForm) as FormDocumentDesigner; - if (parentFormDesigner != null && parentFormDesigner.Menu != null) - { - parentMenu = parentFormDesigner.Menu; - parentFormDesigner.Menu = null; - } } + selected = true; designMenu.Visible = true; designMenu.BringToFront(); menuItem.Visible = true; + // Check if this is a design-time DropDown if (currentParent != null && currentParent != menuItem) { diff --git a/src/System.Windows.Forms/src/Resources/SR.resx b/src/System.Windows.Forms/src/Resources/SR.resx index 8768e3d9f78..7d81d6761d9 100644 --- a/src/System.Windows.Forms/src/Resources/SR.resx +++ b/src/System.Windows.Forms/src/Resources/SR.resx @@ -787,21 +787,6 @@ The parent form of this container control. - - Raised when the context menu collapses. - - - Gets or sets the ImageList associated with this context menu. - - - ContextMenu cannot be shown on an invisible control. - - - Gets or sets a value indicating whether the menu has an image margin. - - - The last control that caused this context menu to be displayed. - The last control that caused this context menu strip to be displayed. @@ -1312,282 +1297,6 @@ RemoveAt is not supported for property-to-property binding. - - Indicates whether the grid can be re-sorted by clicking a column header. - - - Indicates the background color of alternating rows for a ledger appearance. - - - Occurs when the user clicks the Back button on a child table to return to the parent table. - - - Indicates the color of the DataGrid background. - - - BeginInit() has already been called without an EndInit(). - - - Specifies whether the DataGridBoolColumn allows null values. - - - Indicates the border style for the DataGrid. - - - Navigates back to the parent rows. - - - Indicates the background color of the top caption. - - - Shows/Hides the parent rows for the current set of child rows. - - - Indicates the font of the top caption. - - - Indicates the color of text that appears in the top caption. - - - Indicates the text displayed in the top caption. - - - Indicates whether the top caption is visible. - - - DataGridColumn instance does not exist in the collection. - - - Indicates whether the column headers are visible. - - - Position of ListManager must be equal to 'rowNum'. - - - PropertyDescriptor has not been set on this DataGridColumn. - - - Data grid column styles collection already contains a column style with the same mapping name. - - - DataGridColumnStyle of '{0}' cannot be used because it is not associated with a Property or Column in the DataSource. - - - ColumnWidth must be greater than or equal to 0. - - - The currently selected cell in the DataGrid. - - - Indicates a sub-list of the DataSource to show in the DataGrid. - - - Indicates the source of data for the DataGrid. - - - User cannot change the contents of the default GridColumnStylesCollection. - - - Value of this property cannot be changed on the default DataGridTableStyle. - - - Occurs when the user clicks the "show/hide parent rows" icon. - - - Value '{0}' cannot be set to an empty value. - - - Committing the row to the original data store has caused an error. - - - DataGrid received an exception at design time. Reset the DataSource and DataMember property on the grid. - - - Program cannot get information about the painting and scrolling region. - - - Indicates the index of the column that is first shown. - - - Indicates whether the grid has a flat appearance. - - - Indicates the color of the grid lines. - - - Indicates the style of the grid lines. - - - The collection of DataGridTableStyle objects that the DataGrid can render its data with. - - - Indicates the background color of the column and row headers. - - - Indicates the font of the text in the column and row headers. - - - Indicates the color of the text in the column and row headers. - - - Returns the horizontal scroll bar used by the grid. - - - Indicates the color of the text that appears inside the child links. - - - Indicates the color of the text that appears inside a child link when the mouse pointer moves over it. - - - The CurrencyManager that the DataGrid uses to get data from the data source. - - - Occurs when the user navigates to the child rows or when the user navigates back to the parent rows. - - - Indicates whether links to child tables are shown. - - - Occurs when the user clicks on the expansion glyph on the row header. - - - (null) - - - Event raised when the value of the BackgroundColor property is changed on DataGrid. - - - Event raised when the value of the BorderStyle property is changed on DataGrid. - - - Event raised when the value of the CaptionVisible property is changed on DataGrid. - - - Event raised when the value of the CurrentCell property is changed on DataGrid. - - - Event raised when the value of the DataSource property is changed on DataGrid. - - - Event raised when the value of the FlatMode property is changed on DataGrid. - - - Event raised when the value of the NavigationMode property is changed on DataGrid. - - - Event raised when the value of the ParentRowsLabelStyle property is changed on DataGrid. - - - Event raised when the value of the ParentRowsVisible property is changed on DataGrid. - - - Event raised when the value of the ReadOnly property is changed on DataGrid. - - - Indicates the background color of the parent rows. - - - Indicates the color of the text in the parent rows. - - - Indicates whether the parent rows show labels for the table and for the columns. - - - Indicates whether the parent rows area is visible. - - - Specifies what the default pixel widths of the grid columns are. The default value for PreferredColumnWidth is 75. - - - Indicates the preferred height of the rows. - - - Value {0} Do you want to correct this value? - - - Indicates whether rows in the grid can be edited, added, or deleted. - - - Indicates whether the row headers are visible. - - - Indicates the width of the row headers. - - - DataGridRow.Height cannot be negative. - - - DataGridRow cannot have a negative row number. - - - Occurs when the user scrolls either the horizontal or vertical scroll bar. - - - Indicates the index of the current row. - - - Indicates the background color of any selected cells or rows. - - - Indicates the color of the text in any selected cells or rows. - - - ListManager can be set using the DataSource and DataMember properties. - - - Position on a null ListManager cannot be set. - - - CurrentCell cannot be set at this time. Moving your code to the Form.Load event should solve this problem. - - - DataGridTable instance does not exist in the collection. - - - DataGridTableStyle that is already parented to another DataGrid cannot be added. - - - Data grid table styles collection already contains a table style with the same mapping name. - - - DataGridTableStyle does not support transparent AlternatingBackColor. - - - DataGridTableStyle does not support transparent BackColor. - - - DataGridTableStyle does not support transparent HeaderBackColor. - - - DataGridTableStyle does not support transparent SelectionBackColor. - - - null rectangle for icon bounds when adding tool tip. - - - DataGrid control does not support transparent AlternatingBackColor. - - - DataGrid control does not support transparent BackColor. - - - DataGrid control does not support transparent CaptionBackColor. - - - DataGrid control does not support transparent HeaderBackColor. - - - DataGrid control does not support transparent ParentRowsBackColor. - - - DataGrid control does not support transparent SelectionBackColor. - - - Data cannot be read from a DataGrid which is not bound to a DataTable. - - - Returns the vertical scroll bar used by the grid. - Press @@ -3435,15 +3144,9 @@ Do you want to replace it? Retrieves the MDI parent of this form. - - The main menu of the form. This must be set to a component of type MainMenu. - Specifies the primary MenuStrip for the Form. This property is used for keyboard activation and automatic merging in MDI. - - The merged menu of this form, which is used when displaying a single merged MDI menu. - Determines whether a form has a minimize box in the upper-right corner of its caption bar. @@ -4310,18 +4013,6 @@ Stack trace where the illegal operation occurred was: Cannot load the text. - - Occurs when the main menu collapses. - - - Gets or sets the ImageList associated with this main menu. - - - Gets or sets a value indicating whether the menu has an image margin. - - - <No Form> - Indicates whether the prompt character is valid as input. @@ -4418,87 +4109,12 @@ Stack trace where the illegal operation occurred was: Occurs whenever a particular item's height needs to be calculated. - - Parameter must be of type MenuItem. - - - Gets or sets the background color of this menu's image margin. - - - Indicates if this menu contains any child items. - - - Cannot add MenuItem '{0}'. It already exists as a parent of the current menu item. - - - Indicates whether the item is checked. - - - Indicates whether the item is the default item. - - - Indicates whether the item is enabled. - - - Gets or sets the image to be displayed on this menu item. - - - Gets or sets the ImageList associated with this menu item. - - - Gets or sets the background color of this menu item's image margin. - - - True is not a valid value for the Checked property. This is only valid for MenuItems that have no children and are not top-level. - - - Determines whether the MDI child window list is appended to this item. - - - Determines the merge order of the item. - - - Determines how the item is handled when menus are merged. - - - Occurs when the menu item is selected. - - - Occurs before the containing menu is displayed. - - - Occurs when the menu item is selected. - - - Indicates if Windows will draw the menu item or if the user will handle the painting. - - - If the item is checked, this value will determine whether the check style is a radio button. - The shortcut key associated with the menu item. Indicates whether the shorcut key for the menu item is displayed on the item. - - The caption displayed by the item. - - - Indicates whether the item is visible. - - - Retrieves the menu item that contains a list of MDI child windows. - - - The menu items for the menu. - - - Cannot merge a menu with itself. - - - Indicates if this menu should display right to left - Specifies the item whose DropDown will show the list of MDI windows. @@ -5963,84 +5579,6 @@ Stack trace where the illegal operation occurred was: Occurs whenever the specified interval time elapses. - - Controls the appearance of the ToolBar control, using values from the ToolBarAppearance enumeration. - - - Controls whether the ToolBar will automatically size itself based on Button size. - - - Parameter must be of type ToolBarButton. - - - Controls what type of border the ToolBar control will have. - - - Occurs whenever a button in the ToolBar is clicked by the user. - - - Occurs whenever a button with the DropDownButton style is pressed. - - - Controls whether this button responds to user input. - - - Identifies the image displayed on the button. - - - The drop-down menu for a ToolBarButton must be of type ContextMenu. - - - The shortcut menu that will appear if this button's style is set to DropDownButton. - - - References that a non-existent ToolBarButton has been received. - - - Controls whether the button should be displayed as partially pushed or not, but only if the style of the button is ToggleButton. - - - Indicates whether the button is pushed or not. This is most commonly seen for buttons with the TOGGLEBUTTON style. - - - The collection of ToolBarButtons that make up this ToolBar. - - - The size of the buttons on the control if the button contents do not require a larger size. - - - Indicates what style of ToolBarButton this will be. - - - The caption to be displayed for this button. - - - The ToolTip text to be displayed for this button. - - - Indicates whether this button should be visible. - - - Controls whether the ToolBar will display a 3-D line at the top of its client area. - - - Controls whether the ToolBar will display an arrow on the side of drop-down buttons. - - - The ImageList from which this ToolBar will get all of the button images. - - - The size of the images within the ToolBar's ImageList. - - - Indicates whether ToolTips will be shown for each of the buttons, if available. - - - Controls how the text is positioned relative to the Image in each button. - - - Indicates if more than one row of buttons is allowed. - AllowItemReorder and AllowDrop cannot both be true. diff --git a/src/System.Windows.Forms/src/Resources/xlf/SR.cs.xlf b/src/System.Windows.Forms/src/Resources/xlf/SR.cs.xlf index 6d7fda9be24..e56699cfa81 100644 --- a/src/System.Windows.Forms/src/Resources/xlf/SR.cs.xlf +++ b/src/System.Windows.Forms/src/Resources/xlf/SR.cs.xlf @@ -1217,34 +1217,9 @@ Nadřazený formulář tohoto ovládacího prvku kontejneru. - - Raised when the context menu collapses. - Vyvolá se při sbalení místní nabídky. - - - - Gets or sets the ImageList associated with this context menu. - Získá nebo nastaví ovládací prvek ImageList spojený s touto místní nabídkou. - - - - ContextMenu cannot be shown on an invisible control. - Nabídku ContextMenu nelze zobrazit v neviditelném ovládacím prvku. - - - - Gets or sets a value indicating whether the menu has an image margin. - Získá nebo nastaví hodnotu označující, zda má nabídka okraj pro obrázek. - - - - The last control that caused this context menu to be displayed. - Poslední ovládací prvek, který způsobil zobrazení této kontextové nabídky. - - The last control that caused this context menu strip to be displayed. - Poslední ovládací prvek, který způsobil zobrazení této místní nabídky + The last control that caused this context menu strip to be displayed. @@ -2107,466 +2082,6 @@ Funkce RemoveAt není pro vazby mezi vlastnostmi podporována. - - Indicates whether the grid can be re-sorted by clicking a column header. - Určuje, zda lze mřížku znovu seřadit kliknutím na záhlaví sloupce. - - - - Indicates the background color of alternating rows for a ledger appearance. - Určuje barvu pozadí střídavých řádků pro vzhled účetní knihy. - - - - Occurs when the user clicks the Back button on a child table to return to the parent table. - Vyvolá se v případě, že uživatel klikne na tlačítko Zpět v podřízené tabulce, aby se vrátil do nadřazené tabulky. - - - - Indicates the color of the DataGrid background. - Určuje barvu pozadí ovládacího prvku DataGrid. - - - - BeginInit() has already been called without an EndInit(). - Funkce BeginInit() již byla volána bez funkce EndInit(). - - - - Specifies whether the DataGridBoolColumn allows null values. - Určuje, zda funkce DataGridBoolColumn umožňuje použití hodnot NULL. - - - - Indicates the border style for the DataGrid. - Určuje styl ohraničení ovládacího prvku DataGrid. - - - - Navigates back to the parent rows. - Přejde zpět na nadřazené řádky. - - - - Indicates the background color of the top caption. - Určuje barvu pozadí titulku nejvyšší úrovně. - - - - Shows/Hides the parent rows for the current set of child rows. - Zobrazí nebo skryje nadřazené řádky pro aktuální sadu podřízených řádků. - - - - Indicates the font of the top caption. - Určuje písmo titulku nejvyšší úrovně. - - - - Indicates the color of text that appears in the top caption. - Určuje barvu textu, který je zobrazen v titulku nejvyšší úrovně. - - - - Indicates the text displayed in the top caption. - Určuje text zobrazený v titulku nejvyšší úrovně. - - - - Indicates whether the top caption is visible. - Určuje, zda je titulek nejvyšší úrovně viditelný. - - - - DataGridColumn instance does not exist in the collection. - Instance DataGridColumn v kolekci neexistuje. - - - - Indicates whether the column headers are visible. - Určuje, zda jsou záhlaví sloupců viditelná. - - - - Position of ListManager must be equal to 'rowNum'. - Pozice správce ListManager musí být rovna hodnotě rowNum. - - - - PropertyDescriptor has not been set on this DataGridColumn. - V tomto objektu DataGridColumn nebyl nastaven popisovač PropertyDescriptor. - - - - Data grid column styles collection already contains a column style with the same mapping name. - Kolekce stylů sloupců datové mřížky již obsahuje styl sloupce se stejným názvem mapování. - - - - DataGridColumnStyle of '{0}' cannot be used because it is not associated with a Property or Column in the DataSource. - Styl DataGridColumnStyle {0} nelze použít, protože není přidružen k objektu Property nebo Column v objektu DataSource. - - - - ColumnWidth must be greater than or equal to 0. - Hodnota ColumnWidth musí být větší nebo rovna 0. - - - - The currently selected cell in the DataGrid. - Aktuálně vybraná buňka v objektu DataGrid. - - - - Indicates a sub-list of the DataSource to show in the DataGrid. - Určuje podseznam objektu DataSource, který bude zobrazen v objektu DataGrid. - - - - Indicates the source of data for the DataGrid. - Určuje zdroj dat pro objekt DataGrid. - - - - User cannot change the contents of the default GridColumnStylesCollection. - Uživatel nemůže změnit obsah výchozí kolekce GridColumnStylesCollection. - - - - Value of this property cannot be changed on the default DataGridTableStyle. - Hodnotu této vlastnosti nelze ve výchozím objektu DataGridTableStyle změnit. - - - - Occurs when the user clicks the "show/hide parent rows" icon. - Vyvolá se v případě, že uživatel klikne na ikonu pro zobrazení nebo skrytí nadřazených řádků. - - - - Value '{0}' cannot be set to an empty value. - Hodnotu {0} nelze nastavit na prázdnou hodnotu. - - - - Committing the row to the original data store has caused an error. - Při potvrzování řádku původnímu úložišti dat došlo k chybě. - - - - DataGrid received an exception at design time. Reset the DataSource and DataMember property on the grid. - Objekt DataGrid obdržel výjimku v době návrhu. Obnovte nastavení vlastností DataSource a DataMember mřížky. - - - - Program cannot get information about the painting and scrolling region. - Program nemohl získat informace týkajících se oblasti pro překreslování a posouvání. - - - - Indicates the index of the column that is first shown. - Určuje index sloupce, který je zobrazen jako první. - - - - Indicates whether the grid has a flat appearance. - Určuje, zda je mřížka zobrazena jako plochá. - - - - Indicates the color of the grid lines. - Určuje barvu čar mřížky. - - - - Indicates the style of the grid lines. - Určuje styl čar mřížky. - - - - The collection of DataGridTableStyle objects that the DataGrid can render its data with. - Kolekce objektů DataGridTableStyle, pomocí kterých může prvek DataGrid zobrazit data. - - - - Indicates the background color of the column and row headers. - Určuje barvu pozadí záhlaví řádků a sloupců. - - - - Indicates the font of the text in the column and row headers. - Určuje písmo textu v záhlaví řádků a sloupců. - - - - Indicates the color of the text in the column and row headers. - Určuje barvu textu v záhlaví řádků a sloupců. - - - - Returns the horizontal scroll bar used by the grid. - Vrátí vodorovný posuvník používaný mřížkou. - - - - Indicates the color of the text that appears inside the child links. - Určuje barvu textu, který se zobrazí uvnitř podřízených odkazů. - - - - Indicates the color of the text that appears inside a child link when the mouse pointer moves over it. - Určuje barvu textu, který se zobrazí uvnitř podřízeného odkazu při umístění ukazatele myši nad odkaz. - - - - The CurrencyManager that the DataGrid uses to get data from the data source. - Správce CurrencyManager, který ovládací prvek DataGrid používá k získání dat ze zdroje dat - - - - Occurs when the user navigates to the child rows or when the user navigates back to the parent rows. - Vyvolá se v případě, že uživatel přejde k podřízeným řádkům nebo pokud uživatel přejde zpět k nadřazeným řádkům. - - - - Indicates whether links to child tables are shown. - Určuje, zda jsou zobrazeny odkazy na podřízené tabulky. - - - - Occurs when the user clicks on the expansion glyph on the row header. - Vyvolá se v případě, že uživatel klikne na piktogram rozbalení v záhlaví řádku. - - - - (null) - (null) - - - - Event raised when the value of the BackgroundColor property is changed on DataGrid. - Událost aktivovaná při změně hodnoty vlastnosti BackgroundColor ovládacího prvku DataGrid - - - - Event raised when the value of the BorderStyle property is changed on DataGrid. - Událost aktivovaná při změně hodnoty vlastnosti BorderStyle ovládacího prvku DataGrid - - - - Event raised when the value of the CaptionVisible property is changed on DataGrid. - Událost aktivovaná při změně hodnoty vlastnosti CaptionVisible ovládacího prvku DataGrid - - - - Event raised when the value of the CurrentCell property is changed on DataGrid. - Událost aktivovaná při změně hodnoty vlastnosti CurrentCell ovládacího prvku DataGrid - - - - Event raised when the value of the DataSource property is changed on DataGrid. - Událost aktivovaná při změně hodnoty vlastnosti DataSource ovládacího prvku DataGrid - - - - Event raised when the value of the FlatMode property is changed on DataGrid. - Událost aktivovaná při změně hodnoty vlastnosti FlatMode ovládacího prvku DataGrid - - - - Event raised when the value of the NavigationMode property is changed on DataGrid. - Událost aktivovaná při změně hodnoty vlastnosti NavigationMode ovládacího prvku DataGrid - - - - Event raised when the value of the ParentRowsLabelStyle property is changed on DataGrid. - Událost aktivovaná při změně hodnoty vlastnosti ParentRowsLabelStyle ovládacího prvku DataGrid - - - - Event raised when the value of the ParentRowsVisible property is changed on DataGrid. - Událost aktivovaná při změně hodnoty vlastnosti ParentRowsVisible ovládacího prvku DataGrid - - - - Event raised when the value of the ReadOnly property is changed on DataGrid. - Událost aktivovaná při změně hodnoty vlastnosti ReadOnly ovládacího prvku DataGrid - - - - Indicates the background color of the parent rows. - Určuje barvu pozadí nadřazených řádků. - - - - Indicates the color of the text in the parent rows. - Určuje barvu textu nadřazených řádků. - - - - Indicates whether the parent rows show labels for the table and for the columns. - Určuje, zda nadřazené řádky zobrazují popisky pro tabulku a pro sloupce. - - - - Indicates whether the parent rows area is visible. - Určuje, zda je oblast nadřazených řádků viditelná. - - - - Specifies what the default pixel widths of the grid columns are. The default value for PreferredColumnWidth is 75. - Určuje výchozí šířku sloupců mřížky v pixelech. Výchozí hodnotou vlastnosti PreferredColumnWidth je 75. - - - - Indicates the preferred height of the rows. - Určuje upřednostňovanou výšku řádků. - - - - Value {0} Do you want to correct this value? - Hodnota {0} Chcete tuto hodnotu opravit? - - - - Indicates whether rows in the grid can be edited, added, or deleted. - Určuje, zda lze upravit, přidat nebo odstranit řádky mřížky. - - - - Indicates the width of the row headers. - Určuje šířku záhlaví sloupců. - - - - Indicates whether the row headers are visible. - Určuje, zda jsou záhlaví řádků viditelná. - - - - DataGridRow.Height cannot be negative. - Hodnota DataGridRow.Height nemůže být záporná. - - - - DataGridRow cannot have a negative row number. - Vlastnost DataGridRow nemůže obsahovat záporné číslo řádku. - - - - Occurs when the user scrolls either the horizontal or vertical scroll bar. - Vyvolá se v případě, že uživatel posune svislým nebo vodorovným posuvníkem - - - - Indicates the index of the current row. - Určuje index aktuálního řádku. - - - - Indicates the background color of any selected cells or rows. - Určuje barvu pozadí libovolných vybraných buněk nebo řádků. - - - - Indicates the color of the text in any selected cells or rows. - Určuje barvu textu v libovolných vybraných buňkách nebo řádcích. - - - - ListManager can be set using the DataSource and DataMember properties. - Správce ListManager lze nastavit pomocí vlastností DataSource a DataMember. - - - - Position on a null ListManager cannot be set. - Nelze nastavit pozici v prázdném správci ListManager. - - - - CurrentCell cannot be set at this time. Moving your code to the Form.Load event should solve this problem. - Vlastnost CurrentCell nelze nyní nastavit. Potíže by mělo vyřešit přesunutí kódu do procedury události Form.Load. - - - - DataGridTable instance does not exist in the collection. - Instance DataGridTable v této kolekci neexistuje. - - - - DataGridTableStyle that is already parented to another DataGrid cannot be added. - Nelze přidat styl DataGridTableStyle, který je již nastaven jako nadřízený pro jiný objekt DataGrid. - - - - Data grid table styles collection already contains a table style with the same mapping name. - Kolekce stylů tabulek datové mřížky již obsahuje styl tabulky se stejným názvem mapování. - - - - DataGridTableStyle does not support transparent AlternatingBackColor. - Styl DataGridTableStyle nepodporuje průhlednou barvu AlternatingBackColor. - - - - DataGridTableStyle does not support transparent BackColor. - Styl DataGridTableStyle nepodporuje průhlednou barvu BackColor. - - - - DataGridTableStyle does not support transparent HeaderBackColor. - Styl DataGridTableStyle nepodporuje průhlednou barvu HeaderBackColor. - - - - DataGridTableStyle does not support transparent SelectionBackColor. - Styl DataGridTableStyle nepodporuje průhlednou barvu SelectionBackColor. - - - - null rectangle for icon bounds when adding tool tip. - Při přidání popisu tlačítka jsou hranice ikony tvořeny prázdným obdélníkem. - - - - DataGrid control does not support transparent AlternatingBackColor. - Ovládací prvek DataGrid nepodporuje průhlednou barvu AlternatingBackColor. - - - - DataGrid control does not support transparent BackColor. - Ovládací prvek DataGrid nepodporuje průhlednou barvu BackColor. - - - - DataGrid control does not support transparent CaptionBackColor. - Ovládací prvek DataGrid nepodporuje průhlednou barvu CaptionBackColor. - - - - DataGrid control does not support transparent HeaderBackColor. - Ovládací prvek DataGrid nepodporuje průhlednou barvu HeaderBackColor. - - - - DataGrid control does not support transparent ParentRowsBackColor. - Ovládací prvek DataGrid nepodporuje průhlednou barvu ParentRowsBackColor. - - - - DataGrid control does not support transparent SelectionBackColor. - Ovládací prvek DataGrid nepodporuje průhlednou barvu SelectionBackColor. - - - - Data cannot be read from a DataGrid which is not bound to a DataTable. - Nelze načíst data z ovládacího prvku DataGrid, který není vázán k objektu DataTable. - - - - Returns the vertical scroll bar used by the grid. - Vrátí svislý posuvník používaný mřížkou. - - Occurs when the value of the AlternatingRowsDefaultCellStyle property changes. Vyvolá se při změně hodnoty vlastnosti AlternatingRowsDefaultCellStyle. @@ -5657,21 +5172,11 @@ Chcete jej nahradit? Maximální velikost, na niž lze nastavit tento formulář. - - The main menu of the form. This must be set to a component of type MainMenu. - Hlavní nabídka formuláře. Musí být nastavena na součást typu MainMenu. - - Specifies the primary MenuStrip for the Form. This property is used for keyboard activation and automatic merging in MDI. Určuje primární hodnotu MenuStrip pro formulář. Tato vlastnost se používá k aktivování klávesnice a automatickému sloučení v MDI. - - The merged menu of this form, which is used when displaying a single merged MDI menu. - Sloučená nabídka tohoto formuláře, která je použita při zobrazení jedné sloučené nabídky MDI. - - Determines whether a form has a minimize box in the upper-right corner of its caption bar. Určuje, zda formulář má v pravém horním rohu záhlaví minimalizační pole. @@ -7171,26 +6676,6 @@ Trasování zásobníku, kde došlo k neplatné operaci: Formulář, který byl určen jako nadřazený objekt MdiParent pro tento formulář, není typu MdiContainer. - - Occurs when the main menu collapses. - Vyvolá se při sbalení hlavní nabídky. - - - - Gets or sets the ImageList associated with this main menu. - Získá nebo nastaví ovládací prvek ImageList spojený s touto hlavní nabídkou. - - - - Gets or sets a value indicating whether the menu has an image margin. - Získá nebo nastaví hodnotu označující, zda má nabídka okraj pro obrázek. - - - - <No Form> - <No Form> - - Indicates whether the prompt character is valid as input. Označuje, zda je znak příkazového řádku platný jako vstup. @@ -7326,139 +6811,14 @@ Trasování zásobníku, kde došlo k neplatné operaci: Určuje typ objektu, který se má použít k analýze vstupního textu v případě, že ovládací prvek ztratí fokus. - - Parameter must be of type MenuItem. - Parametr musí být typu MenuItem. - - - - Gets or sets the background color of this menu's image margin. - Získá nebo nastaví barvu pozadí okraje pro obrázek v této nabídce. - - - - Indicates if this menu contains any child items. - Určuje, zda tato nabídka obsahuje podřízené položky. - - - - Cannot add MenuItem '{0}'. It already exists as a parent of the current menu item. - Položku MenuItem {0} nelze přidat. Již existuje jako nadřazená položka aktuální položky nabídky. - - - - Indicates whether the item is checked. - Určuje, zda je položka zaškrtnuta. - - - - Indicates whether the item is the default item. - Určuje, zda je položka výchozí položkou. - - - - Indicates whether the item is enabled. - Určuje, zda je položka povolena. - - - - Gets or sets the image to be displayed on this menu item. - Získá nebo nastaví obrázek, který se má zobrazit u této položky nabídky. - - - - Gets or sets the ImageList associated with this menu item. - Získá nebo nastaví ovládací prvek ImageList spojený s touto hlavní nabídkou. - - - - Gets or sets the background color of this menu item's image margin. - Získá nebo nastaví barvu pozadí okraje pro obrázek k této položce nabídky. - - - - True is not a valid value for the Checked property. This is only valid for MenuItems that have no children and are not top-level. - Hodnota True není platnou hodnotou vlastnosti Checked. Je platná pouze pro položky MenuItems, které nemají žádné podřízené položky a nejsou na nejvyšší úrovni. - - - - Determines whether the MDI child window list is appended to this item. - Určuje, zda je k této položce připojen seznam podřízených oken MDI. - - - - Determines the merge order of the item. - Určuje pořadí sloučení položky. - - - - Determines how the item is handled when menus are merged. - Určuje, jakým způsobem je položka zpracována při slučování nabídek. - - - - Occurs when the menu item is selected. - Vyvolá se v případě, že je vybrána položka nabídky. - - - - Occurs before the containing menu is displayed. - Vyvolá se před zobrazením příslušné nabídky. - - - - Occurs when the menu item is selected. - Vyvolá se v případě, že je vybrána položka nabídky. - - - - Indicates if Windows will draw the menu item or if the user will handle the painting. - Určuje, zda položku nabídky nakreslí systém Windows nebo zda bude vykreslení zpracováno uživatelem. - - - - If the item is checked, this value will determine whether the check style is a radio button. - Pokud je položka zaškrtnuta, bude tato hodnota určovat, zda je stylem zaškrtnutí přepínač. - - The shortcut key associated with the menu item. - Klávesová zkratka přiřazená položce nabídky + The shortcut key associated with the menu item. Indicates whether the shorcut key for the menu item is displayed on the item. - Určuje, zda bude v položce nabídky zobrazena klávesová zkratka pro tuto položku. - - - - The caption displayed by the item. - Titulek zobrazený položkou. - - - - Indicates whether the item is visible. - Určuje, zda je položka viditelná. - - - - Retrieves the menu item that contains a list of MDI child windows. - Načte položku nabídky obsahující seznam podřízených oken MDI. - - - - The menu items for the menu. - Příkazy této nabídky - - - - Cannot merge a menu with itself. - Nabídku nelze sloučit se sebou samou. - - - - Indicates if this menu should display right to left - Určuje, zda se tato nabídka má zobrazovat zprava doleva. + Indicates whether the shorcut key for the menu item is displayed on the item. @@ -9976,136 +9336,6 @@ Trasování zásobníku, kde došlo k neplatné operaci: Příliš mnoho volání ResumeUpdateMenuHandles. - - Controls the appearance of the ToolBar control, using values from the ToolBarAppearance enumeration. - Určuje vzhled ovládacího prvku ToolBar a využívá hodnoty výčtu ToolBarAppearance. - - - - Controls whether the ToolBar will automatically size itself based on Button size. - Určuje, zda ovládací prvek ToolBar automaticky změní velikost na základě velikosti prvku Button. - - - - Parameter must be of type ToolBarButton. - Parametr musí být typu ToolBarButton. - - - - Controls what type of border the ToolBar control will have. - Určuje typ ohraničení ovládacího prvku ToolBar. - - - - Occurs whenever a button in the ToolBar is clicked by the user. - Vyvolá se vždy, když uživatel klikne na tlačítko na panelu nástrojů (ToolBar). - - - - Occurs whenever a button with the DropDownButton style is pressed. - Vyvolá se při každém stisknutí tlačítka se stylem DropDownButton. - - - - Controls whether this button responds to user input. - Určuje, zda toto tlačítko bude reagovat na vstup uživatele. - - - - Identifies the image displayed on the button. - Určuje obrázek zobrazovaný na tlačítku. - - - - The drop-down menu for a ToolBarButton must be of type ContextMenu. - Rozevírací nabídka pro ovládací prvek ToolBarButton musí být typu ContextMenu. - - - - The shortcut menu that will appear if this button's style is set to DropDownButton. - Místní nabídka, která bude zobrazena, pokud bude styl tohoto tlačítka nastaven na hodnotu DropDownButton. - - - - References that a non-existent ToolBarButton has been received. - Označuje, že byl přijat neexistující objekt ToolBarButton. - - - - Controls whether the button should be displayed as partially pushed or not, but only if the style of the button is ToggleButton. - Určuje, zda by tlačítko mělo být zobrazeno jako částečně stisknuté, ale pouze v případě, že je styl tlačítka nastaven na hodnotu ToggleButton. - - - - Indicates whether the button is pushed or not. This is most commonly seen for buttons with the TOGGLEBUTTON style. - Určuje, zda tlačítko je nebo není stisknuto. Nejčastěji se používá pro tlačítka se stylem TOGGLEBUTTON. - - - - The size of the buttons on the control if the button contents do not require a larger size. - Velikost tlačítek v ovládacím prvku, pokud obsah tlačítek nevyžaduje větší velikost - - - - Indicates what style of ToolBarButton this will be. - Určuje styl ovládacího prvku ToolBarButton. - - - - The caption to be displayed for this button. - Titulek, který bude zobrazen pro toto tlačítko. - - - - The ToolTip text to be displayed for this button. - Text popisu tlačítka, který bude zobrazen pro toto tlačítko. - - - - Indicates whether this button should be visible. - Určuje, zda toto tlačítko bude viditelné. - - - - The collection of ToolBarButtons that make up this ToolBar. - Kolekce objektů ToolBarButtons, které vytvářejí tento ovládací prvek ToolBar. - - - - Controls whether the ToolBar will display a 3-D line at the top of its client area. - Určuje, zda ovládací prvek ToolBar zobrazí v horní části klientské oblasti prostorovou čáru. - - - - Controls whether the ToolBar will display an arrow on the side of drop-down buttons. - Určuje, zda ovládací prvek ToolBar zobrazí vedle rozevíracích tlačítek šipku. - - - - The ImageList from which this ToolBar will get all of the button images. - Seznam ImageList, z něhož tento ovládací prvek ToolBar získá všechny obrázky tlačítek. - - - - The size of the images within the ToolBar's ImageList. - Velikost obrázků v rámci seznamu ImageList tohoto ovládacího prvku ToolBar. - - - - Indicates whether ToolTips will be shown for each of the buttons, if available. - Určuje, zda budou pro jednotlivá tlačítka zobrazeny popisy tlačítek, jsou-li k dispozici. - - - - Controls how the text is positioned relative to the Image in each button. - Určuje pozici textu vzhledem k obrázku v jednotlivých tlačítkách. - - - - Indicates if more than one row of buttons is allowed. - Určuje, zda je povolen více než jeden řádek tlačítek. - - AllowItemReorder and AllowDrop cannot both be true. Vlastnosti AllowItemReorder a AllowDrop nemohou být současně nastaveny na hodnotu True. diff --git a/src/System.Windows.Forms/src/Resources/xlf/SR.de.xlf b/src/System.Windows.Forms/src/Resources/xlf/SR.de.xlf index 6ed0b5852f9..d7c2f6c40c8 100644 --- a/src/System.Windows.Forms/src/Resources/xlf/SR.de.xlf +++ b/src/System.Windows.Forms/src/Resources/xlf/SR.de.xlf @@ -1217,34 +1217,9 @@ Das übergeordnete Formular des Containersteuerelements. - - Raised when the context menu collapses. - Wird ausgelöst, wenn das Kontextmenü ausgeblendet wird. - - - - Gets or sets the ImageList associated with this context menu. - Ruft die mit diesem Kontextmenü verknüpfte ImageList ab oder legt sie fest. - - - - ContextMenu cannot be shown on an invisible control. - ContextMenu kann nicht auf einem unsichtbarem Steuerelement angezeigt werden. - - - - Gets or sets a value indicating whether the menu has an image margin. - Ruft einen Wert ab oder legt einen Wert fest, der anzeigt, ob das Menü einen Bildrand hat. - - - - The last control that caused this context menu to be displayed. - Das letzte Steuerelement, dass die Anzeige des Kontextmenüs verursacht hat. - - The last control that caused this context menu strip to be displayed. - Das letzte Steuerelement, das die Anzeige dieser Kontextmenüleiste verursacht hat. + The last control that caused this context menu strip to be displayed. @@ -2107,466 +2082,6 @@ RemoveAt wird für die Eigenschaftenbindung nicht unterstützt. - - Indicates whether the grid can be re-sorted by clicking a column header. - Zeigt an, ob das Raster durch Klicken auf den Spaltenheader neu sortiert werden kann. - - - - Indicates the background color of alternating rows for a ledger appearance. - Zeigt die Hintergrundfarbe für abwechselnde Zeilen an (Ledger-Darstellung). - - - - Occurs when the user clicks the Back button on a child table to return to the parent table. - Tritt auf, wenn der Benutzer in einer untergeordneten Tabelle auf die Schaltfläche "Zurück" klickt, um zu der übergeordneten Tabelle zurückzukehren. - - - - Indicates the color of the DataGrid background. - Zeigt die Farbe des DataGrid-Hintergrunds an. - - - - BeginInit() has already been called without an EndInit(). - BeginInit() wurde bereits ohne EndInit() aufgerufen. - - - - Specifies whether the DataGridBoolColumn allows null values. - Gibt an, ob die DataGridBoolColumn NULL-Werte zulässt. - - - - Indicates the border style for the DataGrid. - Gibt die Rahmenart für das DataGrid an. - - - - Navigates back to the parent rows. - Navigiert zu den übergeordneten Zeilen zurück. - - - - Indicates the background color of the top caption. - Gibt die Hintergrundfarbe der oberen Beschriftung an. - - - - Shows/Hides the parent rows for the current set of child rows. - Blendet die übergeordneten Zeilen für die aktuellen untergeordneten Zeilen ein bzw. aus. - - - - Indicates the font of the top caption. - Gibt die Schriftart der oberen Beschriftung an. - - - - Indicates the color of text that appears in the top caption. - Gibt die Textfarbe der oberen Beschriftung an. - - - - Indicates the text displayed in the top caption. - Gibt den Text in der oberen Beschriftung an. - - - - Indicates whether the top caption is visible. - Gibt an, ob die obere Beschriftung sichtbar ist. - - - - DataGridColumn instance does not exist in the collection. - Die DataGridColumn-Instanz ist in der Sammlung nicht vorhanden. - - - - Indicates whether the column headers are visible. - Gibt an, ob die Spaltenheader sichtbar sind. - - - - Position of ListManager must be equal to 'rowNum'. - Die ListManager-Position muss mit rowNum übereinstimmen. - - - - PropertyDescriptor has not been set on this DataGridColumn. - PropertyDescriptor wurde für diese DataGridColumn nicht festgelegt. - - - - Data grid column styles collection already contains a column style with the same mapping name. - Die Sammlung der Spaltenformate des Datenrasters enthält bereits ein Spaltenformat mit diesem Zuordnungsnamen. - - - - DataGridColumnStyle of '{0}' cannot be used because it is not associated with a Property or Column in the DataSource. - Der DataGridColumnStyle {0} kann nicht verwendet werden, da er mit keiner Eigenschaft oder Spalte in der DataSource verknüpft ist. - - - - ColumnWidth must be greater than or equal to 0. - ColumnWidth muss größer oder gleich 0 sein. - - - - The currently selected cell in the DataGrid. - Die zurzeit ausgewählte Zelle im DataGrid. - - - - Indicates a sub-list of the DataSource to show in the DataGrid. - Zeigt eine untergeordnete Liste der DataSource an, um sie im DataGrid anzuzeigen. - - - - Indicates the source of data for the DataGrid. - Zeigt die Datenquelle für das DataGrid an. - - - - User cannot change the contents of the default GridColumnStylesCollection. - Der Benutzer kann den Inhalt der standardmäßigen GridColumnStylesCollection nicht ändern. - - - - Value of this property cannot be changed on the default DataGridTableStyle. - Der Wert dieser Eigenschaft für den standardmäßigen DataGridTableStyle kann nicht geändert werden. - - - - Occurs when the user clicks the "show/hide parent rows" icon. - Tritt auf, wenn der Benutzer auf das Symbol zum Anzeigen/Ausblenden von übergeordneten Zeilen klickt. - - - - Value '{0}' cannot be set to an empty value. - Der Wert {0} kann nicht auf einen leeren Wert festgelegt werden. - - - - Committing the row to the original data store has caused an error. - Fehler beim Durchführen des Commits der Zeile im ursprünglichen Datenspeicher . - - - - DataGrid received an exception at design time. Reset the DataSource and DataMember property on the grid. - DataGrid hat während der Entwurfszeit eine Ausnahme erhalten. Setzen Sie die DataSource- und DataMember-Eigenschaft im Raster zurück. - - - - Program cannot get information about the painting and scrolling region. - Das Programm kann keine Informationen über den Bereich für das Zeichnen und den Bildlauf abrufen. - - - - Indicates the index of the column that is first shown. - Gibt den anfangs angezeigten Index dieser Spalte an. - - - - Indicates whether the grid has a flat appearance. - Zeigt an, ob das Raster flach dargestellt wird. - - - - Indicates the color of the grid lines. - Zeigt die Farbe der Rasterlinien an. - - - - Indicates the style of the grid lines. - Zeigt den Stil der Rasterlinien an. - - - - The collection of DataGridTableStyle objects that the DataGrid can render its data with. - Die Sammlung von DataGridTableStyle-Objekten, mit denen DataGrid seine Daten darstellen kann. - - - - Indicates the background color of the column and row headers. - Zeigt die Hintergrundfarbe der Spalten- und Zeilenheader an. - - - - Indicates the font of the text in the column and row headers. - Zeigt die Schriftart des Texts in den Spalten- und Zeilenheadern an. - - - - Indicates the color of the text in the column and row headers. - Zeigt die Farbe des Texts in den Spalten- und Zeilenheadern an. - - - - Returns the horizontal scroll bar used by the grid. - Gibt die horizontale Schiebeleiste zurück, die vom Raster verwendet wird. - - - - Indicates the color of the text that appears inside the child links. - Gibt die Farbe des Texts an, der in den untergeordneten Verknüpfungen angezeigt wird. - - - - Indicates the color of the text that appears inside a child link when the mouse pointer moves over it. - Gibt die Farbe des Textes an, der in einer untergeordneten Verknüpfung angezeigt wird, wenn der Mauszeiger darüber bewegt wird. - - - - The CurrencyManager that the DataGrid uses to get data from the data source. - Der CurrencyManager, den DataGrid für das Abrufen von Daten aus der Datenquelle verwendet. - - - - Occurs when the user navigates to the child rows or when the user navigates back to the parent rows. - Tritt ein, wenn der Benutzer zu den untergeordneten Zeilen oder zurück zu den übergeordneten Zeilen navigiert. - - - - Indicates whether links to child tables are shown. - Gibt an, ob Verknüpfungen zu untergeordneten Tabellen angezeigt werden. - - - - Occurs when the user clicks on the expansion glyph on the row header. - Tritt ein, wenn der Benutzer auf eine Erweiterungszeichnung im Zeilenheader klickt. - - - - (null) - (NULL) - - - - Event raised when the value of the BackgroundColor property is changed on DataGrid. - Das ausgelöste Ereignis, wenn der Wert der BackgroundColor-Eigenschaft für DataGrid geändert wird. - - - - Event raised when the value of the BorderStyle property is changed on DataGrid. - Das ausgelöste Ereignis, wenn der Wert der BorderStyle-Eigenschaft für DataGrid geändert wird. - - - - Event raised when the value of the CaptionVisible property is changed on DataGrid. - Das ausgelöste Ereignis, wenn der Wert der CaptionVisible-Eigenschaft für DataGrid geändert wird. - - - - Event raised when the value of the CurrentCell property is changed on DataGrid. - Das ausgelöste Ereignis, wenn der Wert der CurrentCell-Eigenschaft für DataGrid geändert wird. - - - - Event raised when the value of the DataSource property is changed on DataGrid. - Das ausgelöste Ereignis, wenn der Wert der DataSource-Eigenschaft für DataGrid geändert wird. - - - - Event raised when the value of the FlatMode property is changed on DataGrid. - Das ausgelöste Ereignis, wenn der Wert der FlatMode-Eigenschaft für DataGrid geändert wird. - - - - Event raised when the value of the NavigationMode property is changed on DataGrid. - Das ausgelöste Ereignis, wenn der Wert der NavigationMode-Eigenschaft für DataGrid geändert wird. - - - - Event raised when the value of the ParentRowsLabelStyle property is changed on DataGrid. - Das ausgelöste Ereignis, wenn der Wert der ParentRowsLabelStyle-Eigenschaft für DataGrid geändert wird. - - - - Event raised when the value of the ParentRowsVisible property is changed on DataGrid. - Das ausgelöste Ereignis, wenn der Wert der ParentRowsVisible-Eigenschaft für DataGrid geändert wird. - - - - Event raised when the value of the ReadOnly property is changed on DataGrid. - Das ausgelöste Ereignis, wenn der Wert der ReadOnly-Eigenschaft für DataGrid geändert wird. - - - - Indicates the background color of the parent rows. - Zeigt die Hintergrundfarbe der übergeordneten Zeilen an. - - - - Indicates the color of the text in the parent rows. - Zeigt die Farbe des Texts in den übergeordneten Zeilen an. - - - - Indicates whether the parent rows show labels for the table and for the columns. - Gibt an, ob die übergeordneten Zeilen Bezeichnungen für die Tabelle oder die Spalten anzeigen. - - - - Indicates whether the parent rows area is visible. - Zeigt an, ob der übergeordnete Zeilenbereich sichtbar ist. - - - - Specifies what the default pixel widths of the grid columns are. The default value for PreferredColumnWidth is 75. - Gibt die Standardpixelbreite der Rasterspalten an. Der Standardwert für PreferredColumnWidth ist 75. - - - - Indicates the preferred height of the rows. - Zeigt die bevorzugte Höhe der Zeilen an. - - - - Value {0} Do you want to correct this value? - Wert {0}. Möchten Sie diesen Wert korrigieren? - - - - Indicates whether rows in the grid can be edited, added, or deleted. - Zeigt an, ob Rasterzeilen bearbeitet, hinzugefügt oder gelöscht werden können. - - - - Indicates the width of the row headers. - Zeigt die Breite der Zeilenheader an. - - - - Indicates whether the row headers are visible. - Zeigt an, ob die Zeilenheader sichtbar sind. - - - - DataGridRow.Height cannot be negative. - DataGridRow.Height kann nicht negativ sein. - - - - DataGridRow cannot have a negative row number. - DataGridRow kann keine negative Zeilennummer haben. - - - - Occurs when the user scrolls either the horizontal or vertical scroll bar. - Tritt ein, wenn der Benutzer den horizontalen oder vertikalen Bildlauf ausführt. - - - - Indicates the index of the current row. - Zeigt den Index der aktuellen Zeile an. - - - - Indicates the background color of any selected cells or rows. - Zeigt die Hintergrundfarbe ausgewählter Zellen oder Zeilen an. - - - - Indicates the color of the text in any selected cells or rows. - Zeigt die Farbe des Texts in ausgewählten Zellen oder Zeilen an. - - - - ListManager can be set using the DataSource and DataMember properties. - ListManager kann mithilfe der DataSource- und DataMember-Eigenschaften festgelegt werden. - - - - Position on a null ListManager cannot be set. - Die Position für einen NULL-ListManager kann nicht festgelegt werden. - - - - CurrentCell cannot be set at this time. Moving your code to the Form.Load event should solve this problem. - CurrentCell kann derzeit nicht festgelegt werden. Verschieben Sie den Code in das Ereignis Form.Load, um das Problem zu beheben. - - - - DataGridTable instance does not exist in the collection. - Die DataGridTable-Instanz ist in der Sammlung nicht vorhanden. - - - - DataGridTableStyle that is already parented to another DataGrid cannot be added. - Ein DataGridTableStyle, der bereits einem anderen DataGrid übergeordnet ist, kann nicht hinzugefügt werden. - - - - Data grid table styles collection already contains a table style with the same mapping name. - In der Tabellenformatsammlung des Datenrasters ist bereits ein Tabellenformat mit diesem Zuordnungsnamen vorhanden. - - - - DataGridTableStyle does not support transparent AlternatingBackColor. - DataGridTableStyle unterstützt die transparente AlternatingBackColor nicht. - - - - DataGridTableStyle does not support transparent BackColor. - DataGridTableStyle unterstützt die transparente BackColor nicht. - - - - DataGridTableStyle does not support transparent HeaderBackColor. - DataGridTableStyle unterstützt die transparente HeaderBackColor nicht. - - - - DataGridTableStyle does not support transparent SelectionBackColor. - DataGridTableStyle unterstützt die transparente SelectionBackColor nicht. - - - - null rectangle for icon bounds when adding tool tip. - NULL-Rechteck für Symbolbegrenzungen beim Hinzufügen der QuickInfo. - - - - DataGrid control does not support transparent AlternatingBackColor. - Das DataGrid-Steuerelement unterstützt die transparente AlternatingBackColor nicht. - - - - DataGrid control does not support transparent BackColor. - Das DataGrid-Steuerelement unterstützt die transparente BackColor nicht. - - - - DataGrid control does not support transparent CaptionBackColor. - Das DataGrid-Steuerelement unterstützt die transparente CaptionBackColor nicht. - - - - DataGrid control does not support transparent HeaderBackColor. - Das DataGrid-Steuerelement unterstützt die transparente HeaderBackColor nicht. - - - - DataGrid control does not support transparent ParentRowsBackColor. - Das DataGrid-Steuerelement unterstützt die transparente ParentRowsBackColor nicht. - - - - DataGrid control does not support transparent SelectionBackColor. - Das DataGrid-Steuerelement unterstützt die transparente SelectionBackColor nicht. - - - - Data cannot be read from a DataGrid which is not bound to a DataTable. - Aus einem DataGrid, das nicht an eine DataTable gebunden ist, können keine Daten gelesen werden. - - - - Returns the vertical scroll bar used by the grid. - Gibt die vertikale Schiebeleiste zurück, die vom Raster verwendet wird. - - Occurs when the value of the AlternatingRowsDefaultCellStyle property changes. Tritt auf, wenn sich der Wert der AlternatingRowsDefaultCellStyle-Eigenschaft ändert. @@ -5657,21 +5172,11 @@ Möchten Sie sie ersetzen? Die Maximalgröße, die das Formular annehmen kann. - - The main menu of the form. This must be set to a component of type MainMenu. - Das Hauptmenü dieses Formulars. Dies muss auf eine Komponente des Typs MainMenu festgelegt werden. - - Specifies the primary MenuStrip for the Form. This property is used for keyboard activation and automatic merging in MDI. Gibt den primären MenuStrip für das Formular an. Diese Eigenschaft wird für die Tastaturaktivierung und das automatische Zusammenführen in MDI verwendet. - - The merged menu of this form, which is used when displaying a single merged MDI menu. - Das zusammengeführte Menü dieses Formulars, das verwendet wird, wenn ein einfaches zusammengeführtes MDI-Menu angezeigt wird. - - Determines whether a form has a minimize box in the upper-right corner of its caption bar. Bestimmt, ob ein Formular ein Minimieren-Feld in der oberen rechten Ecke seiner Titelleiste hat. @@ -7171,26 +6676,6 @@ Stapelüberwachung, in der der unzulässige Vorgang auftrat: Das Formular, das als MdiParent für dieses Formular angegeben wurde, ist kein MdiContainer. - - Occurs when the main menu collapses. - Tritt ein, wenn das Hauptmenü ausgeblendet wird. - - - - Gets or sets the ImageList associated with this main menu. - Ruft die mit dem Hauptmenü verknüpfte ImageList ab oder legt sie fest. - - - - Gets or sets a value indicating whether the menu has an image margin. - Ruft einen Wert ab oder legt einen Wert fest, der anzeigt, ob das Menü einen Bildrand hat. - - - - <No Form> - <No Form> - - Indicates whether the prompt character is valid as input. Zeigt an, ob das Eingabeaufforderungszeichen eine gültige Eingabe ist. @@ -7326,139 +6811,14 @@ Stapelüberwachung, in der der unzulässige Vorgang auftrat: Gibt den Typ des für die Analyse des Eingabetexts zu verwendenden Objekts an, wenn das Steuerelement den Fokus verliert. - - Parameter must be of type MenuItem. - Der Parameter muss den Typ MenuItem haben. - - - - Gets or sets the background color of this menu's image margin. - Ruft die Hintergrundfarbe des Bildrandes für dieses Menü ab oder legt sie fest. - - - - Indicates if this menu contains any child items. - Gibt an, ob dieses Menü untergeordnete Elemente enthält. - - - - Cannot add MenuItem '{0}'. It already exists as a parent of the current menu item. - MenuItem {0} kann nicht hinzugefügt werden, da es bereits als übergeordnetes Menüelement vorhanden ist. - - - - Indicates whether the item is checked. - Gibt an, ob das Element ausgewählt ist. - - - - Indicates whether the item is the default item. - Gibt an, ob das Element das Standardelement ist. - - - - Indicates whether the item is enabled. - Gibt an, ob das Element aktiviert ist. - - - - Gets or sets the image to be displayed on this menu item. - Ruft das für dieses Menüelement anzuzeigende Bild ab oder legt es fest. - - - - Gets or sets the ImageList associated with this menu item. - Ruft das mit der ImageList verknüpfte Menüelement ab oder legt es fest. - - - - Gets or sets the background color of this menu item's image margin. - Ruft die Hintergrundfarbe des Bildrandes für dieses Menü ab oder legt sie fest. - - - - True is not a valid value for the Checked property. This is only valid for MenuItems that have no children and are not top-level. - "True" ist kein gültiger Wert für die Checked-Eigenschaft. Er ist nur für MenuItems gültig, die keine untergeordneten Elemente besitzen und sich nicht auf der obersten Ebene befinden. - - - - Determines whether the MDI child window list is appended to this item. - Bestimmt, ob die MDI-Liste untergeordneter Fenster an dieses Element angehängt wird. - - - - Determines the merge order of the item. - Bestimmt die Zusammenführungsfolge des Elements. - - - - Determines how the item is handled when menus are merged. - Bestimmt, wie das Element beim Zusammenführen von Menüs behandelt wird. - - - - Occurs when the menu item is selected. - Tritt ein, wenn das Menüelement ausgewählt wird. - - - - Occurs before the containing menu is displayed. - Tritt ein, bevor das enthaltende Menü angezeigt wird. - - - - Occurs when the menu item is selected. - Tritt ein, wenn das Menüelement ausgewählt wird. - - - - Indicates if Windows will draw the menu item or if the user will handle the painting. - Zeigt an, ob Windows oder der Benutzer das Menüelement zeichnet. - - - - If the item is checked, this value will determine whether the check style is a radio button. - Wenn das Element aktiviert wird, bestimmt der Wert, ob dafür ein Optionsfeld verwendet wird. - - The shortcut key associated with the menu item. - Die dem Menüelement zugeordnete Tastenkombination. + The shortcut key associated with the menu item. Indicates whether the shorcut key for the menu item is displayed on the item. - Gibt an, ob die Tastenkombination für das Menüelement in dem Element angezeigt wird. - - - - The caption displayed by the item. - Die Beschriftung, die vom Element angezeigt wird. - - - - Indicates whether the item is visible. - Zeigt an, ob das Element sichtbar ist. - - - - Retrieves the menu item that contains a list of MDI child windows. - Fragt das Menüelement ab, das ein Liste untergeordneter MDI-Fenster enthält. - - - - The menu items for the menu. - Die Menüelemente für das Menü. - - - - Cannot merge a menu with itself. - Ein Menü kann nicht mit sich selbst zusammengeführt werden. - - - - Indicates if this menu should display right to left - Zeigt an, ob dieses Menü von rechts nach links angezeigt werden soll. + Indicates whether the shorcut key for the menu item is displayed on the item. @@ -9976,136 +9336,6 @@ Stapelüberwachung, in der der unzulässige Vorgang auftrat: Zu viele Aufrufe an ResumeUpdateMenuHandles. - - Controls the appearance of the ToolBar control, using values from the ToolBarAppearance enumeration. - Steuert die Darstellung des ToolBar-Steuerelements mit Werten aus der ToolBarAppearance-Enumeration. - - - - Controls whether the ToolBar will automatically size itself based on Button size. - Steuert, ob die Größe der ToolBar automatisch basierend auf der Schaltflächengröße geändert wird. - - - - Parameter must be of type ToolBarButton. - Der Parameter muss den Typ ToolBarButton haben. - - - - Controls what type of border the ToolBar control will have. - Steuert den Rahmentyp des ToolBar-Steuerelements. - - - - Occurs whenever a button in the ToolBar is clicked by the user. - Tritt ein, wenn der Benutzer auf eine ToolBar-Schaltfläche klickt. - - - - Occurs whenever a button with the DropDownButton style is pressed. - Tritt ein, wenn auf eine Schaltfläche mit dem Stil DropDownButton geklickt wird. - - - - Controls whether this button responds to user input. - Steuert, ob die Schaltfläche auf Benutzereingaben reagiert. - - - - Identifies the image displayed on the button. - Gibt das auf der Schaltfläche angezeigte Bild an. - - - - The drop-down menu for a ToolBarButton must be of type ContextMenu. - Das DropdownmMenü für einen ToolBarButton muss den Typ ContextMenu haben. - - - - The shortcut menu that will appear if this button's style is set to DropDownButton. - Das Kontextmenü, das angezeigt wird, wenn der Stil der Schaltfläche auf DropDownButton festgelegt ist. - - - - References that a non-existent ToolBarButton has been received. - Gibt an, dass ein nicht vorhandener ToolBarButton empfangen wurde. - - - - Controls whether the button should be displayed as partially pushed or not, but only if the style of the button is ToggleButton. - Steuert, ob die Schaltfläche als partiell gedrückt angezeigt wird (nur wenn der Stil der Schaltfläche auf ToggleButton festgelegt ist). - - - - Indicates whether the button is pushed or not. This is most commonly seen for buttons with the TOGGLEBUTTON style. - Gibt an, ob auf die Schaltfläche geklickt wurde (wird häufig für Schaltflächen mit dem TOGGLEBUTTON-Stil verwendet). - - - - The size of the buttons on the control if the button contents do not require a larger size. - Die Größe der Schaltflächen in dem Steuerelement, wenn für den Inhalt der Schaltfläche keine größere Größe erforderlich ist. - - - - Indicates what style of ToolBarButton this will be. - Gibt den Stil für ToolBarButton an. - - - - The caption to be displayed for this button. - Die Beschriftung, die für diese Schaltfläche angezeigt wird. - - - - The ToolTip text to be displayed for this button. - Die QuickInfo, die für diese Schaltfläche angezeigt wird. - - - - Indicates whether this button should be visible. - Zeigt an, ob diese Schaltfläche sichtbar sein soll. - - - - The collection of ToolBarButtons that make up this ToolBar. - Die ToolBarButtons-Sammlung, die diese ToolBar bildet. - - - - Controls whether the ToolBar will display a 3-D line at the top of its client area. - Steuert, ob in der ToolBar eine 3D-Zeile am oberen Rand des Clientbereichs angezeigt wird. - - - - Controls whether the ToolBar will display an arrow on the side of drop-down buttons. - Steuert, ob in der ToolBar ein Pfeil neben den Dropdown-Schaltflächen angezeigt wird. - - - - The ImageList from which this ToolBar will get all of the button images. - Die ImageList, aus der die ToolBar alle Schaltflächenbilder abruft. - - - - The size of the images within the ToolBar's ImageList. - Die Größe der Bilder in der ImageList der Toolbar. - - - - Indicates whether ToolTips will be shown for each of the buttons, if available. - Gibt an, ob QuickInfos für jede Schaltfläche angezeigt werden, sofern verfügbar. - - - - Controls how the text is positioned relative to the Image in each button. - Steuert, wie der Text relativ zum Bild in jeder Schaltfläche positioniert wird. - - - - Indicates if more than one row of buttons is allowed. - Zeigt an, ob mehr als eine Schaltflächenzeile zulässig ist. - - AllowItemReorder and AllowDrop cannot both be true. AllowItemReorder und AllowDrop können nicht beide "true" sein. diff --git a/src/System.Windows.Forms/src/Resources/xlf/SR.es.xlf b/src/System.Windows.Forms/src/Resources/xlf/SR.es.xlf index 22274f5b853..68d1da453e5 100644 --- a/src/System.Windows.Forms/src/Resources/xlf/SR.es.xlf +++ b/src/System.Windows.Forms/src/Resources/xlf/SR.es.xlf @@ -1217,34 +1217,9 @@ Formulario primario de este control contenedor. - - Raised when the context menu collapses. - Se desencadena cuando se contrae el menú contextual. - - - - Gets or sets the ImageList associated with this context menu. - Obtiene o establece ImageList asociado con este menú contextual. - - - - ContextMenu cannot be shown on an invisible control. - No se puede mostrar ContextMenu en un control invisible. - - - - Gets or sets a value indicating whether the menu has an image margin. - Obtiene o establece un valor que indica si el menú tiene un margen de imagen. - - - - The last control that caused this context menu to be displayed. - Último control que hizo que se mostrara el menú contextual. - - The last control that caused this context menu strip to be displayed. - Último control que hizo que se mostrara la franja de menús contextuales. + The last control that caused this context menu strip to be displayed. @@ -2107,466 +2082,6 @@ El enlace propiedad a propiedad no admite RemoveAt. - - Indicates whether the grid can be re-sorted by clicking a column header. - Indica si se puede reordenar la cuadrícula al hacer clic en el encabezado de una columna. - - - - Indicates the background color of alternating rows for a ledger appearance. - Indica el color de fondo de las filas alternas para una apariencia a doble carta. - - - - Occurs when the user clicks the Back button on a child table to return to the parent table. - Tiene lugar cuando el usuario hace clic en el botón Atrás en la tabla secundaria para volver a la tabla primaria. - - - - Indicates the color of the DataGrid background. - Indica el color de fondo de DataGrid. - - - - BeginInit() has already been called without an EndInit(). - Ya se ha llamado a BeginInit() sin EndInit(). - - - - Specifies whether the DataGridBoolColumn allows null values. - Especifica si DataGridBoolColumn es compatible con valores nulos. - - - - Indicates the border style for the DataGrid. - Indica el estilo de borde de DataGrid. - - - - Navigates back to the parent rows. - Navega hacia atrás hasta las filas primarias. - - - - Indicates the background color of the top caption. - Indica el color de fondo del título superior. - - - - Shows/Hides the parent rows for the current set of child rows. - Muestra u oculta las filas primarias para el conjunto actual de filas secundarias. - - - - Indicates the font of the top caption. - Indica la fuente del título superior. - - - - Indicates the color of text that appears in the top caption. - Indica el color del texto que aparece en el título superior. - - - - Indicates the text displayed in the top caption. - Indica el texto que se muestra en el título superior. - - - - Indicates whether the top caption is visible. - Indica si el título superior es visible. - - - - DataGridColumn instance does not exist in the collection. - La instancia DataGridColumn no existe en la colección. - - - - Indicates whether the column headers are visible. - Indica si los encabezados de la columna son visibles. - - - - Position of ListManager must be equal to 'rowNum'. - La posición de ListManager debe ser igual a 'rowNum'. - - - - PropertyDescriptor has not been set on this DataGridColumn. - No se ha establecido PropertyDescriptor en DataGridColumn. - - - - Data grid column styles collection already contains a column style with the same mapping name. - La colección de estilos para las columnas de la cuadrícula de datos ya contiene un estilo de columna con el mismo nombre de asignación. - - - - DataGridColumnStyle of '{0}' cannot be used because it is not associated with a Property or Column in the DataSource. - No puede utilizar DataGridColumnStyle de '{0}' porque no está asociado con una propiedad o columna en DataSource. - - - - ColumnWidth must be greater than or equal to 0. - ColumnWidth debe ser mayor o igual que 0. - - - - The currently selected cell in the DataGrid. - Celda seleccionada actualmente en DataGrid. - - - - Indicates a sub-list of the DataSource to show in the DataGrid. - Indica una sublista de DataSource para mostrar en DataGrid. - - - - Indicates the source of data for the DataGrid. - Indica el origen de datos para DataGrid. - - - - User cannot change the contents of the default GridColumnStylesCollection. - El usuario no puede cambiar los contenidos de la colección predeterminada GridColumnStylesCollection. - - - - Value of this property cannot be changed on the default DataGridTableStyle. - No se puede cambiar el valor de esta propiedad en DataGridTableStyle predeterminado. - - - - Occurs when the user clicks the "show/hide parent rows" icon. - Se desencadena cuando el usuario hace clic en el icono "mostrar u ocultar filas primarias". - - - - Value '{0}' cannot be set to an empty value. - No se puede establecer el valor '{0}' como un valor vacío. - - - - Committing the row to the original data store has caused an error. - Error al confirmar la fila del almacén de datos original. - - - - DataGrid received an exception at design time. Reset the DataSource and DataMember property on the grid. - DataGrid recibió una excepción en tiempo de diseño. Restablezca las propiedades DataSource y DataMember de la cuadrícula. - - - - Program cannot get information about the painting and scrolling region. - El programa no puede obtener información sobre la zona utilizada para pintura y desplazamiento. - - - - Indicates the index of the column that is first shown. - Indica el índice de la columna que se muestra primero. - - - - Indicates whether the grid has a flat appearance. - Indica si la apariencia de la cuadrícula no tiene relieve. - - - - Indicates the color of the grid lines. - Indica el color de la cuadrícula. - - - - Indicates the style of the grid lines. - Indica el estilo de la cuadrícula. - - - - The collection of DataGridTableStyle objects that the DataGrid can render its data with. - La colección de objetos DataGridTableStyle con los que DataGrid puede presentar sus datos. - - - - Indicates the background color of the column and row headers. - Indica el color de fondo del encabezado de columnas y filas. - - - - Indicates the font of the text in the column and row headers. - Indica la fuente del texto en los encabezados de columna y fila. - - - - Indicates the color of the text in the column and row headers. - Indica el color del texto del encabezado de columnas y filas. - - - - Returns the horizontal scroll bar used by the grid. - Devuelve la barra de desplazamiento horizontal utilizada por la cuadrícula. - - - - Indicates the color of the text that appears inside the child links. - Indica el color del texto que aparece dentro de los vínculos secundarios. - - - - Indicates the color of the text that appears inside a child link when the mouse pointer moves over it. - Indica el color del texto que aparece dentro de un vínculo secundario cuando el puntero del mouse se mueve sobre él. - - - - The CurrencyManager that the DataGrid uses to get data from the data source. - CurrencyManager que DataGrid utiliza para obtener datos desde el origen de datos. - - - - Occurs when the user navigates to the child rows or when the user navigates back to the parent rows. - Tiene lugar cuando el usuario navega a las filas secundarias o cuando navega hacia atrás hasta las filas primarias. - - - - Indicates whether links to child tables are shown. - Indica si se muestran los vínculos a las tablas secundarias. - - - - Occurs when the user clicks on the expansion glyph on the row header. - Tiene lugar cuando el usuario hace clic en el glifo de expansión en el encabezado de fila. - - - - (null) - (null) - - - - Event raised when the value of the BackgroundColor property is changed on DataGrid. - Evento que se desencadena cuando se cambia el valor de la propiedad BackgroundColor de DataGrid. - - - - Event raised when the value of the BorderStyle property is changed on DataGrid. - Evento que se desencadena cuando se cambia el valor de la propiedad BorderStyle de DataGrid. - - - - Event raised when the value of the CaptionVisible property is changed on DataGrid. - Evento que se desencadena cuando se cambia el valor de la propiedad CaptionVisible de DataGrid. - - - - Event raised when the value of the CurrentCell property is changed on DataGrid. - Evento que se desencadena cuando se cambia el valor de la propiedad CurrentCell de DataGrid. - - - - Event raised when the value of the DataSource property is changed on DataGrid. - Evento que se desencadena cuando se cambia el valor de la propiedad DataSource de DataGrid. - - - - Event raised when the value of the FlatMode property is changed on DataGrid. - Evento que se desencadena cuando se cambia el valor de la propiedad FlatMode de DataGrid. - - - - Event raised when the value of the NavigationMode property is changed on DataGrid. - Evento que se desencadena cuando se cambia el valor de la propiedad NavigationMode de DataGrid. - - - - Event raised when the value of the ParentRowsLabelStyle property is changed on DataGrid. - Evento que se desencadena cuando se cambia el valor de la propiedad ParentRowsLabelStyle de DataGrid. - - - - Event raised when the value of the ParentRowsVisible property is changed on DataGrid. - Evento que se desencadena cuando se cambia el valor de la propiedad ParentRowsVisible de DataGrid. - - - - Event raised when the value of the ReadOnly property is changed on DataGrid. - Evento que se desencadena cuando se cambia el valor de la propiedad ReadOnly de DataGrid. - - - - Indicates the background color of the parent rows. - Indica el color de fondo de las filas primarias. - - - - Indicates the color of the text in the parent rows. - Indica el color del texto en las filas primarias. - - - - Indicates whether the parent rows show labels for the table and for the columns. - Indica si las filas primarias muestran etiquetas para la tabla y las columnas. - - - - Indicates whether the parent rows area is visible. - Indica si el área de filas primarias es visible. - - - - Specifies what the default pixel widths of the grid columns are. The default value for PreferredColumnWidth is 75. - Especifica el ancho preferido de píxel de las columnas de la cuadrícula. El valor predeterminado de PreferredColumnWidth es 75. - - - - Indicates the preferred height of the rows. - Indica el alto preferido de las filas. - - - - Value {0} Do you want to correct this value? - Valor {0} ¿Desea corregir este valor? - - - - Indicates whether rows in the grid can be edited, added, or deleted. - Indica si las filas de la cuadrícula se pueden editar, agregar o eliminar. - - - - Indicates the width of the row headers. - Indica el ancho de los encabezados de las filas. - - - - Indicates whether the row headers are visible. - Indica si los encabezados de las filas son visibles. - - - - DataGridRow.Height cannot be negative. - DataGridRow.Height no puede ser negativo. - - - - DataGridRow cannot have a negative row number. - DataGridRow no puede tener un número de filas negativo. - - - - Occurs when the user scrolls either the horizontal or vertical scroll bar. - Tiene lugar cuando el usuario se desplaza mediante la barra de desplazamiento horizontal u vertical. - - - - Indicates the index of the current row. - Indica el índice de la fila actual. - - - - Indicates the background color of any selected cells or rows. - Indica el color de fondo de cualquier celda o fila seleccionada. - - - - Indicates the color of the text in any selected cells or rows. - Indica el color del texto en cualquier celda o fila seleccionada. - - - - ListManager can be set using the DataSource and DataMember properties. - Se puede definir ListManager utilizando las propiedades DataSource y DataMember. - - - - Position on a null ListManager cannot be set. - No se puede establecer la posición en un ListManager nulo. - - - - CurrentCell cannot be set at this time. Moving your code to the Form.Load event should solve this problem. - No se puede establecer CurrentCell ahora. Si cambia el código al evento Form.Load, se solucionará este problema. - - - - DataGridTable instance does not exist in the collection. - La instancia DataGridTable no existe en la colección. - - - - DataGridTableStyle that is already parented to another DataGrid cannot be added. - No se puede agregar DataGridTableStyle que ya es primario de otro DataGrid. - - - - Data grid table styles collection already contains a table style with the same mapping name. - La colección de estilos para las tablas de la cuadrícula de datos ya contiene un estilo de tabla con el mismo nombre de asignación. - - - - DataGridTableStyle does not support transparent AlternatingBackColor. - DataGridTableStyle no admite AlternatingBackColor transparente. - - - - DataGridTableStyle does not support transparent BackColor. - DataGridTableStyle no admite BackColor transparente. - - - - DataGridTableStyle does not support transparent HeaderBackColor. - DataGridTableStyle no admite HeaderBackColor transparente. - - - - DataGridTableStyle does not support transparent SelectionBackColor. - DataGridTableStyle no admite SelectionBackColor transparente. - - - - null rectangle for icon bounds when adding tool tip. - rectángulo nulo para los límites del icono al agregar la información sobre herramientas. - - - - DataGrid control does not support transparent AlternatingBackColor. - El control DataGrid no admite AlternatingBackColor transparente. - - - - DataGrid control does not support transparent BackColor. - El control DataGrid no admite BackColor transparente. - - - - DataGrid control does not support transparent CaptionBackColor. - El control DataGrid no admite CaptionBackColor transparente. - - - - DataGrid control does not support transparent HeaderBackColor. - El control DataGrid no admite HeaderBackColor transparente. - - - - DataGrid control does not support transparent ParentRowsBackColor. - El control DataGrid no admite ParentRowsBackColor transparente. - - - - DataGrid control does not support transparent SelectionBackColor. - El control DataGrid no admite SelectionBackColor transparente. - - - - Data cannot be read from a DataGrid which is not bound to a DataTable. - No se pueden leer los datos de DataGrid que no están enlazados a DataTable. - - - - Returns the vertical scroll bar used by the grid. - Devuelve la barra de desplazamiento vertical utilizada por la cuadrícula. - - Occurs when the value of the AlternatingRowsDefaultCellStyle property changes. Tiene lugar cuando el valor de la propiedad AlternatingRowsDefaultCellStyle cambia. @@ -5657,21 +5172,11 @@ Do you want to replace it? Tamaño máximo al que se puede ajustar el tamaño del formulario. - - The main menu of the form. This must be set to a component of type MainMenu. - Menú principal del formulario. Debe establecerse en un componente de tipo MainMenu. - - Specifies the primary MenuStrip for the Form. This property is used for keyboard activation and automatic merging in MDI. Especifica el MenuStrip principal para el formulario. Esta propiedad se utiliza para la activación del teclado y la combinación automática en MDI. - - The merged menu of this form, which is used when displaying a single merged MDI menu. - Menú combinado de este formulario, que se utiliza para mostrar un sólo menú MDI combinado. - - Determines whether a form has a minimize box in the upper-right corner of its caption bar. Determina si el formulario tiene un cuadro para minimizar en la esquina superior derecha de la barra de título. @@ -7171,26 +6676,6 @@ El seguimiento de la pila donde tuvo lugar la operación no válida fue: El formulario especificado como MdiParent para este formulario no es un contenedor MdiContainer. - - Occurs when the main menu collapses. - Se desencadena cuando el menú principal se contrae. - - - - Gets or sets the ImageList associated with this main menu. - Obtiene o establece la ImageList asociada con este menú principal. - - - - Gets or sets a value indicating whether the menu has an image margin. - Obtiene o establece un valor que indica si el menú tiene un margen de imagen. - - - - <No Form> - <No Form> - - Indicates whether the prompt character is valid as input. Indica si el carácter de petición de datos es válido como entrada. @@ -7326,139 +6811,14 @@ El seguimiento de la pila donde tuvo lugar la operación no válida fue: Especifica el tipo del objeto que se va a utilizar para analizar el texto de entrada cuando el control pierde el foco. - - Parameter must be of type MenuItem. - El parámetro de be ser de tipo MenuItem. - - - - Gets or sets the background color of this menu's image margin. - Obtiene o establece el color de fondo del margen de la imagen de este menú. - - - - Indicates if this menu contains any child items. - Indica si este menú contiene algún elemento secundario. - - - - Cannot add MenuItem '{0}'. It already exists as a parent of the current menu item. - No se puede agregar MenuItem '{0}'. Ya existe como primario del elemento de menú actual. - - - - Indicates whether the item is checked. - Indica si el elemento está activado. - - - - Indicates whether the item is the default item. - Indica si el elemento es el elemento predeterminado. - - - - Indicates whether the item is enabled. - Indica si el elemento está habilitado. - - - - Gets or sets the image to be displayed on this menu item. - Obtiene o establece la imagen que se va a mostrar en este elemento de menú. - - - - Gets or sets the ImageList associated with this menu item. - Obtiene o establece la ImageList asociada con este elemento de menú. - - - - Gets or sets the background color of this menu item's image margin. - Obtiene o establece el color de fondo del margen de la imagen de este elemento de menú. - - - - True is not a valid value for the Checked property. This is only valid for MenuItems that have no children and are not top-level. - True no es un valor válido para la propiedad Checked. Este valor sólo es válido para MenuItems que no tienen elementos secundarios y que no son de nivel superior. - - - - Determines whether the MDI child window list is appended to this item. - Determina si se debe adjuntar a este elemento la lista de ventanas secundarias MDI. - - - - Determines the merge order of the item. - Determina el orden de combinación del elemento. - - - - Determines how the item is handled when menus are merged. - Determina cómo se administra el elemento cuando se combinan menús. - - - - Occurs when the menu item is selected. - Tiene lugar cuando se selecciona el elemento de menú. - - - - Occurs before the containing menu is displayed. - Tiene lugar antes de que se muestre el menú que lo contiene. - - - - Occurs when the menu item is selected. - Tiene lugar cuando se selecciona el elemento de menú. - - - - Indicates if Windows will draw the menu item or if the user will handle the painting. - Indica si Windows se encarga de dibujar el elemento de menú o si es el usuario quién se encarga de dibujarlo. - - - - If the item is checked, this value will determine whether the check style is a radio button. - Si el elemento se activa, este valor determinará si el estilo de activación será un botón de radio. - - The shortcut key associated with the menu item. - Tecla de método abreviado asociada al elemento de menú. + The shortcut key associated with the menu item. Indicates whether the shorcut key for the menu item is displayed on the item. - Indica si la tecla de método abreviado del elemento de menú se muestra en el elemento. - - - - The caption displayed by the item. - Título que muestra el elemento. - - - - Indicates whether the item is visible. - Indica si el elemento es visible. - - - - Retrieves the menu item that contains a list of MDI child windows. - Recupera el elemento de menú que contiene una lista de ventanas secundarias MDI. - - - - The menu items for the menu. - Elementos del menú. - - - - Cannot merge a menu with itself. - No se puede combinar un menú consigo mismo. - - - - Indicates if this menu should display right to left - Indica si se debe mostrar este menú de derecha a izquierda + Indicates whether the shorcut key for the menu item is displayed on the item. @@ -9976,136 +9336,6 @@ El seguimiento de la pila donde tuvo lugar la operación no válida fue: Demasiadas llamadas a ResumeUpdateMenuHandles. - - Controls the appearance of the ToolBar control, using values from the ToolBarAppearance enumeration. - Controla la apariencia del control ToolBar, usando los valores de la enumeración ToolBarAppearance. - - - - Controls whether the ToolBar will automatically size itself based on Button size. - Controla si la barra de herramientas debe cambiar automáticamente de tamaño basándose en el tamaño de los botones. - - - - Parameter must be of type ToolBarButton. - El parámetro debe ser de tipo ToolBarButton. - - - - Controls what type of border the ToolBar control will have. - Controla qué tipo de borde tiene el control de la barra de herramientas. - - - - Occurs whenever a button in the ToolBar is clicked by the user. - Tiene lugar cuando el usuario hace clic en un botón de la barra de herramientas. - - - - Occurs whenever a button with the DropDownButton style is pressed. - Tiene lugar cuando se presiona un botón con estilo DropDownButton. - - - - Controls whether this button responds to user input. - Controla si este botón responde a la entrada del usuario. - - - - Identifies the image displayed on the button. - Identifica la imagen que aparece en el botón. - - - - The drop-down menu for a ToolBarButton must be of type ContextMenu. - El menú desplegable de la colección ToolBarButton debe ser de tipo ContextMenu. - - - - The shortcut menu that will appear if this button's style is set to DropDownButton. - Menú contextual que aparecerá si el estilo de este botón se establece en DropDownButton. - - - - References that a non-existent ToolBarButton has been received. - Se han recibido referencias a un ToolBarButton que no existe. - - - - Controls whether the button should be displayed as partially pushed or not, but only if the style of the button is ToggleButton. - Controla si el botón se debe mostrar como parcialmente presionado, pero sólo si el estilo del botón es ToggleButton. - - - - Indicates whether the button is pushed or not. This is most commonly seen for buttons with the TOGGLEBUTTON style. - Indica si el botón está presionado o no. Lo más normal es encontrarlo en los botones que tienen el estilo TOGGLEBUTTON. - - - - The size of the buttons on the control if the button contents do not require a larger size. - Tamaño de los botones del control si el contenido de los botones no requiere un tamaño mayor. - - - - Indicates what style of ToolBarButton this will be. - Indica qué estilo tendrá ToolBarButton. - - - - The caption to be displayed for this button. - Título que se muestra para este botón. - - - - The ToolTip text to be displayed for this button. - El texto de información sobre herramientas que se va a mostrar para este botón. - - - - Indicates whether this button should be visible. - Indica si este botón debe ser visible. - - - - The collection of ToolBarButtons that make up this ToolBar. - Colección de botones ToolBarButtons que forman esta barra de herramientas. - - - - Controls whether the ToolBar will display a 3-D line at the top of its client area. - Controla si la barra de herramientas mostrará una línea en 3D en la parte superior de su área cliente. - - - - Controls whether the ToolBar will display an arrow on the side of drop-down buttons. - Controla si la barra de herramientas mostrará una flecha junto a los botones de lista desplegable. - - - - The ImageList from which this ToolBar will get all of the button images. - ImageList de la que esta barra de herramientas obtendrá todas las imágenes de los botones. - - - - The size of the images within the ToolBar's ImageList. - Tamaño de las imágenes de ImageList de la barra de herramientas. - - - - Indicates whether ToolTips will be shown for each of the buttons, if available. - Indica si se debe mostrar la información sobre herramientas para cada uno de los botones, si está disponible. - - - - Controls how the text is positioned relative to the Image in each button. - Controla cómo se sitúa el texto en relación con la imagen en cada botón. - - - - Indicates if more than one row of buttons is allowed. - Indica si se permite más de una fila de botones. - - AllowItemReorder and AllowDrop cannot both be true. AllowItemReorder y AllowDrop no pueden ser ambos true. diff --git a/src/System.Windows.Forms/src/Resources/xlf/SR.fr.xlf b/src/System.Windows.Forms/src/Resources/xlf/SR.fr.xlf index 1725c6476fb..0ce7181fb67 100644 --- a/src/System.Windows.Forms/src/Resources/xlf/SR.fr.xlf +++ b/src/System.Windows.Forms/src/Resources/xlf/SR.fr.xlf @@ -1217,34 +1217,9 @@ Le formulaire parent de ce contrôle conteneur. - - Raised when the context menu collapses. - Déclenché lorsque le menu contextuel est réduit. - - - - Gets or sets the ImageList associated with this context menu. - Obtient ou définit le ImageList associé à ce menu contextuel. - - - - ContextMenu cannot be shown on an invisible control. - ContextMenu ne peut pas être affiché sur un contrôle invisible. - - - - Gets or sets a value indicating whether the menu has an image margin. - Obtient ou définit une valeur indiquant si le menu dispose d'une marge d'image. - - - - The last control that caused this context menu to be displayed. - Dernier contrôle ayant provoqué l'affichage de ce menu contextuel. - - The last control that caused this context menu strip to be displayed. - Dernier contrôle ayant provoqué l'affichage de cette bande de menus contextuels. + The last control that caused this context menu strip to be displayed. @@ -2107,466 +2082,6 @@ RemoveAt n'est pas pris en charge pour la liaison de propriété à propriété. - - Indicates whether the grid can be re-sorted by clicking a column header. - Indique si la grille peut être retriée en cliquant sur un en-tête de colonne. - - - - Indicates the background color of alternating rows for a ledger appearance. - Indique la couleur d'arrière-plan des lignes en alternance pour obtenir une apparence livre comptable. - - - - Occurs when the user clicks the Back button on a child table to return to the parent table. - Se produit lors d'un clic sur le bouton Précédent d'une table enfant pour retourner à la table parente. - - - - Indicates the color of the DataGrid background. - Indique la couleur de l'arrière-plan du DataGrid. - - - - BeginInit() has already been called without an EndInit(). - BeginInit() a déjà été appelé sans EndInit(). - - - - Specifies whether the DataGridBoolColumn allows null values. - Indique si DataGridBoolColumn autorise les valeurs null. - - - - Indicates the border style for the DataGrid. - Indique le style de bordure du DataGrid. - - - - Navigates back to the parent rows. - Navigue vers l'arrière jusqu'aux lignes parentes. - - - - Indicates the background color of the top caption. - Indique la couleur d'arrière-plan de la légende supérieure. - - - - Shows/Hides the parent rows for the current set of child rows. - Affiche/masque les lignes parentes pour l'ensemble actuel de lignes enfants. - - - - Indicates the font of the top caption. - Indique la police de la légende supérieure. - - - - Indicates the color of text that appears in the top caption. - Indique la couleur de texte qui s'affiche dans la légende supérieure. - - - - Indicates the text displayed in the top caption. - Indique le texte affiché dans la légende supérieure. - - - - Indicates whether the top caption is visible. - Indique si la légende supérieure est visible. - - - - DataGridColumn instance does not exist in the collection. - L'instance DataGridColumn n'existe pas dans la collection. - - - - Indicates whether the column headers are visible. - Indique si les en-têtes de colonnes sont visibles. - - - - Position of ListManager must be equal to 'rowNum'. - La position de ListManager doit être égale à 'rowNum'. - - - - PropertyDescriptor has not been set on this DataGridColumn. - PropertyDescriptor n'a pas été défini à ce DataGridColumn. - - - - Data grid column styles collection already contains a column style with the same mapping name. - La collection de styles de colonne de la grille de données contient un style de colonne avec le même nom de mappage. - - - - DataGridColumnStyle of '{0}' cannot be used because it is not associated with a Property or Column in the DataSource. - DataGridColumnStyle de '{0}' ne peut pas être utilisé, car il n'est pas associé à une propriété ou à une colonne dans le DataSource. - - - - ColumnWidth must be greater than or equal to 0. - ColumnWidth doit être supérieur ou égal à 0. - - - - The currently selected cell in the DataGrid. - La cellule actuellement sélectionnée dans le DataGrid. - - - - Indicates a sub-list of the DataSource to show in the DataGrid. - Indique une sous-liste du DataSource à afficher dans le DataGrid. - - - - Indicates the source of data for the DataGrid. - Indique la source des données pour le DataGrid. - - - - User cannot change the contents of the default GridColumnStylesCollection. - L'utilisateur ne peut pas changer le contenu de GridColumnStylesCollection par défaut. - - - - Value of this property cannot be changed on the default DataGridTableStyle. - Impossible de changer la valeur de cette propriété pour le DataGridTableStyle par défaut. - - - - Occurs when the user clicks the "show/hide parent rows" icon. - Se produit lors d'un clic de l'utilisateur sur l'icône d'affichage/masquage des lignes parentes. - - - - Value '{0}' cannot be set to an empty value. - Impossible de définir une valeur vide pour '{0}'. - - - - Committing the row to the original data store has caused an error. - Erreur lors de la validation de la ligne avec le magasin de données d'origine. - - - - DataGrid received an exception at design time. Reset the DataSource and DataMember property on the grid. - DataGrid a reçu une exception au moment du design. Réinitialisez les propriétés DataSource et DataMember dans la grille. - - - - Program cannot get information about the painting and scrolling region. - Impossible d'obtenir des informations sur la région utilisée pour la peinture et le défilement. - - - - Indicates the index of the column that is first shown. - Indique l'index de la colonne qui est affichée en premier. - - - - Indicates whether the grid has a flat appearance. - Indique si la grille a une apparence à deux dimensions. - - - - Indicates the color of the grid lines. - Indique la couleur des lignes de la grille. - - - - Indicates the style of the grid lines. - Indique le style des lignes de la grille. - - - - The collection of DataGridTableStyle objects that the DataGrid can render its data with. - La collection d'objets DataGridTableStyle avec lesquels le DataGrid peut afficher ses données. - - - - Indicates the background color of the column and row headers. - Indique la couleur d'arrière-plan des en-têtes de colonnes et de lignes. - - - - Indicates the font of the text in the column and row headers. - Indique la police du texte dans les en-têtes de colonnes et de lignes. - - - - Indicates the color of the text in the column and row headers. - Indique la couleur du texte dans les en-têtes de colonnes et de lignes. - - - - Returns the horizontal scroll bar used by the grid. - Retourne la barre de défilement horizontale utilisée par la grille. - - - - Indicates the color of the text that appears inside the child links. - Indique la couleur du texte qui s'affiche dans les liaisons enfants. - - - - Indicates the color of the text that appears inside a child link when the mouse pointer moves over it. - Indique la couleur du texte qui s'affiche dans une liaison enfant lorsque le pointeur de la souris passe dessus. - - - - The CurrencyManager that the DataGrid uses to get data from the data source. - Le CurrencyManager que le DataGrid utilise pour obtenir des données de la source de données. - - - - Occurs when the user navigates to the child rows or when the user navigates back to the parent rows. - Se produit lorsque l'utilisateur navigue jusqu'aux lignes enfants ou lorsqu'il navigue vers l'arrière jusqu'aux lignes parentes. - - - - Indicates whether links to child tables are shown. - Indique si les liaisons vers les tables enfants s'affichent. - - - - Occurs when the user clicks on the expansion glyph on the row header. - Se produit lorsque l'utilisateur clique sur le glyphe d'expansion de l'en-tête de ligne. - - - - (null) - (null) - - - - Event raised when the value of the BackgroundColor property is changed on DataGrid. - Événement déclenché lorsque la valeur de la propriété BackgroundColor de DataGrid est modifiée. - - - - Event raised when the value of the BorderStyle property is changed on DataGrid. - Événement déclenché lorsque la valeur de la propriété BorderStyle de DataGrid est modifiée. - - - - Event raised when the value of the CaptionVisible property is changed on DataGrid. - Événement déclenché lorsque la valeur de la propriété CaptionVisible de DataGrid est modifiée. - - - - Event raised when the value of the CurrentCell property is changed on DataGrid. - Événement déclenché lorsque la valeur de la propriété CurrentCell de DataGrid est modifiée. - - - - Event raised when the value of the DataSource property is changed on DataGrid. - Événement déclenché lorsque la valeur de la propriété DataSource de DataGrid est modifiée. - - - - Event raised when the value of the FlatMode property is changed on DataGrid. - Événement déclenché lorsque la valeur de la propriété FlatMode de DataGrid est modifiée. - - - - Event raised when the value of the NavigationMode property is changed on DataGrid. - Événement déclenché lorsque la valeur de la propriété NavigationMode de DataGrid est modifiée. - - - - Event raised when the value of the ParentRowsLabelStyle property is changed on DataGrid. - Événement déclenché lorsque la valeur de la propriété ParentRowsLabelStyle de DataGrid est modifiée. - - - - Event raised when the value of the ParentRowsVisible property is changed on DataGrid. - Événement déclenché lorsque la valeur de la propriété ParentRowsVisible de DataGrid est modifiée. - - - - Event raised when the value of the ReadOnly property is changed on DataGrid. - Événement déclenché lorsque la valeur de la propriété ReadOnly de DataGrid est modifiée. - - - - Indicates the background color of the parent rows. - Indique la couleur d'arrière-plan des lignes parentes. - - - - Indicates the color of the text in the parent rows. - Indique la couleur du texte dans les lignes parentes. - - - - Indicates whether the parent rows show labels for the table and for the columns. - Indique si les lignes parentes affichent des étiquettes pour la table et pour les colonnes. - - - - Indicates whether the parent rows area is visible. - Indique si la zone de lignes parentes est visible. - - - - Specifies what the default pixel widths of the grid columns are. The default value for PreferredColumnWidth is 75. - Spécifie les largeurs par défaut en pixels des colonnes de la grille. La valeur par défaut pour PreferredColumnWidth est égale à 75. - - - - Indicates the preferred height of the rows. - Indique la hauteur par défaut des lignes. - - - - Value {0} Do you want to correct this value? - Valeur {0} Voulez-vous corriger cette valeur ? - - - - Indicates whether rows in the grid can be edited, added, or deleted. - Indique si les lignes de la grille peuvent être modifiées, ajoutées ou supprimées. - - - - Indicates the width of the row headers. - Indique la largeur des en-têtes de lignes. - - - - Indicates whether the row headers are visible. - Indique si les en-têtes de lignes sont visibles. - - - - DataGridRow.Height cannot be negative. - DataGridRow.Height ne peut pas avoir une valeur négative. - - - - DataGridRow cannot have a negative row number. - DataGridRow ne peut pas avoir un nombre de lignes négatif. - - - - Occurs when the user scrolls either the horizontal or vertical scroll bar. - Se produit lorsque l'utilisateur fait défiler à l'aide de la barre de défilement horizontale ou verticale. - - - - Indicates the index of the current row. - Indique l'index de la ligne actuelle. - - - - Indicates the background color of any selected cells or rows. - Indique la couleur d'arrière-plan des cellules ou des lignes sélectionnées. - - - - Indicates the color of the text in any selected cells or rows. - Indique la couleur du texte dans les cellules ou les lignes sélectionnées. - - - - ListManager can be set using the DataSource and DataMember properties. - ListManager peut être défini à l'aide des propriétés DataSource et DataMember. - - - - Position on a null ListManager cannot be set. - Impossible de définir la position sur un ListManager null. - - - - CurrentCell cannot be set at this time. Moving your code to the Form.Load event should solve this problem. - Impossible de définir CurrentCell actuellement. Pour résoudre ce problème, déplacez votre code dans Form.Load. - - - - DataGridTable instance does not exist in the collection. - L'instance DataGridTable n'existe pas dans la collection. - - - - DataGridTableStyle that is already parented to another DataGrid cannot be added. - Impossible d'ajouter un DataGridTableStyle déjà enfant d'un autre DataGrid. - - - - Data grid table styles collection already contains a table style with the same mapping name. - La collection de styles de la grille de données contient un style de table avec le même nom de mappage. - - - - DataGridTableStyle does not support transparent AlternatingBackColor. - DataGridTableStyle ne prend pas en charge un AlternatingBackColor transparent. - - - - DataGridTableStyle does not support transparent BackColor. - DataGridTableStyle ne prend pas en charge un BackColor transparent. - - - - DataGridTableStyle does not support transparent HeaderBackColor. - DataGridTableStyle ne prend pas en charge un HeaderBackColor transparent. - - - - DataGridTableStyle does not support transparent SelectionBackColor. - DataGridTableStyle ne prend pas en charge un SelectionBackColor transparent. - - - - null rectangle for icon bounds when adding tool tip. - rectangle null pour les limites d'icône lors de l'ajout d'une info-bulle. - - - - DataGrid control does not support transparent AlternatingBackColor. - Le contrôle DataGrid ne prend pas en charge un AlternatingBackColor transparent. - - - - DataGrid control does not support transparent BackColor. - Le contrôle DataGrid ne prend pas en charge un BackColor transparent. - - - - DataGrid control does not support transparent CaptionBackColor. - Le contrôle DataGrid ne prend pas en charge un CaptionBackColor transparent. - - - - DataGrid control does not support transparent HeaderBackColor. - Le contrôle DataGrid ne prend pas en charge un HeaderBackColor transparent. - - - - DataGrid control does not support transparent ParentRowsBackColor. - Le contrôle DataGrid ne prend pas en charge un ParentRowsBackColor transparent. - - - - DataGrid control does not support transparent SelectionBackColor. - Le contrôle DataGrid ne prend pas en charge un SelectionBackColor transparent. - - - - Data cannot be read from a DataGrid which is not bound to a DataTable. - Les données ne peuvent pas être lues à partir d'un DataGrid qui n'est pas lié à un DataTable. - - - - Returns the vertical scroll bar used by the grid. - Retourne la barre de défilement verticale utilisée par la grille. - - Occurs when the value of the AlternatingRowsDefaultCellStyle property changes. Se produit lorsque la valeur de la propriété AlternatingRowsDefaultCellStyle change. @@ -5657,21 +5172,11 @@ Voulez-vous le remplacer ? La taille maximale à laquelle le formulaire peut être redimensionné. - - The main menu of the form. This must be set to a component of type MainMenu. - Le menu principal du formulaire. Il doit être un composant de type MainMenu. - - Specifies the primary MenuStrip for the Form. This property is used for keyboard activation and automatic merging in MDI. Spécifie le MenuStrip principal du formulaire. Cette propriété est utilisée pour l'activation clavier et la fusion automatique en MDI. - - The merged menu of this form, which is used when displaying a single merged MDI menu. - Le menu fusionné de ce formulaire, qui est utilisé lors de l'affichage d'un menu MDI fusionné. - - Determines whether a form has a minimize box in the upper-right corner of its caption bar. Détermine si un formulaire dispose d'un bouton de réduction dans le coin supérieur droit de sa barre de légende. @@ -7171,26 +6676,6 @@ Cette opération non conforme s'est produite sur la trace de la pile : Le formulaire qui a été spécifié comme étant le MdiParent pour ce formulaire n'est pas un MdiContainer. - - Occurs when the main menu collapses. - Se produit lors de la réduction du menu principal. - - - - Gets or sets the ImageList associated with this main menu. - Obtient ou définit l'ImageList associé à ce menu principal. - - - - Gets or sets a value indicating whether the menu has an image margin. - Obtient ou définit une valeur indiquant si le menu dispose d'une marge d'image. - - - - <No Form> - <No Form> - - Indicates whether the prompt character is valid as input. Indique si le caractère d'invite est valide en tant qu'entrée. @@ -7326,139 +6811,14 @@ Cette opération non conforme s'est produite sur la trace de la pile : Spécifie le Type de l'objet à utiliser pour l'analyse du texte d'entrée lorsque le contrôle perd le focus. - - Parameter must be of type MenuItem. - Le paramètre doit être de type MenuItem. - - - - Gets or sets the background color of this menu's image margin. - Obtient ou définit la couleur d'arrière-plan de la marge d'image de ce menu. - - - - Indicates if this menu contains any child items. - Indique si ce menu contient des éléments enfants. - - - - Cannot add MenuItem '{0}'. It already exists as a parent of the current menu item. - Impossible d'ajouter MenuItem '{0}', car il existe déjà en tant que parent de l'élément de menu actuel. - - - - Indicates whether the item is checked. - Indique si l'élément est coché. - - - - Indicates whether the item is the default item. - Indique si l'élément est l'élément par défaut. - - - - Indicates whether the item is enabled. - Indique si l'élément est activé. - - - - Gets or sets the image to be displayed on this menu item. - Obtient ou définit l'image à afficher sur cet élément de menu. - - - - Gets or sets the ImageList associated with this menu item. - Obtient ou définit l'ImageList associé à cet élément de menu. - - - - Gets or sets the background color of this menu item's image margin. - Obtient ou définit la couleur d'arrière-plan de la marge d'image de cet élément de menu. - - - - True is not a valid value for the Checked property. This is only valid for MenuItems that have no children and are not top-level. - True n'est pas une valeur valide pour la propriété Checked. Elle n'est valide que pour les MenuItems qui n'ont pas d'enfants et ne sont pas de niveau supérieur. - - - - Determines whether the MDI child window list is appended to this item. - Détermine si la liste des fenêtres enfants MDI est ajoutée à cet élément. - - - - Determines the merge order of the item. - Détermine l'ordre de fusion de l'élément. - - - - Determines how the item is handled when menus are merged. - Détermine la façon dont l'élément est géré lors de la fusion de menus. - - - - Occurs when the menu item is selected. - Se produit lorsque l'élément de menu est sélectionné. - - - - Occurs before the containing menu is displayed. - Se produit avant l'affichage du menu contenant. - - - - Occurs when the menu item is selected. - Se produit lorsque l'élément de menu est sélectionné. - - - - Indicates if Windows will draw the menu item or if the user will handle the painting. - Indique si Windows doit dessiner l'élément de menu ou si l'utilisateur gère la peinture. - - - - If the item is checked, this value will determine whether the check style is a radio button. - Si l'élément est activé, cette valeur détermine si le style de sélection est une case d'option. - - The shortcut key associated with the menu item. - La touche de raccourci associée à l'élément de menu. + The shortcut key associated with the menu item. Indicates whether the shorcut key for the menu item is displayed on the item. - Indique si la touche de raccourci pour l'élément de menu est affichée sur l'élément. - - - - The caption displayed by the item. - La légende affichée par l'élément. - - - - Indicates whether the item is visible. - Indique si l'élément est visible. - - - - Retrieves the menu item that contains a list of MDI child windows. - Extrait l'élément de menu qui contient une liste des fenêtres enfants MDI. - - - - The menu items for the menu. - Les éléments de menu pour le menu. - - - - Cannot merge a menu with itself. - Impossible de fusionner un menu avec lui-même. - - - - Indicates if this menu should display right to left - Indique si ce menu doit s'afficher de droite à gauche + Indicates whether the shorcut key for the menu item is displayed on the item. @@ -9976,136 +9336,6 @@ Cette opération non conforme s'est produite sur la trace de la pile : Trop d'appels vers ResumeUpdateMenuHandles. - - Controls the appearance of the ToolBar control, using values from the ToolBarAppearance enumeration. - Contrôle l'apparence du contrôle ToolBar, en utilisant les valeurs de l'énumération ToolBarAppearance. - - - - Controls whether the ToolBar will automatically size itself based on Button size. - Contrôle si la barre d'outils est automatiquement redimensionnée en fonction de la taille des boutons. - - - - Parameter must be of type ToolBarButton. - Le paramètre doit être de type ToolBarButton. - - - - Controls what type of border the ToolBar control will have. - Contrôle le type de bordure du contrôle ToolBar. - - - - Occurs whenever a button in the ToolBar is clicked by the user. - Se produit lorsqu'un utilisateur clique sur un bouton du ToolBar. - - - - Occurs whenever a button with the DropDownButton style is pressed. - Se produit lorsqu'un bouton de style DropDownButton est enfoncé. - - - - Controls whether this button responds to user input. - Contrôle si ce bouton répond aux entrées d'utilisateur. - - - - Identifies the image displayed on the button. - Identifie l'image affichée sur ce bouton. - - - - The drop-down menu for a ToolBarButton must be of type ContextMenu. - Le type d'un menu déroulant d'un ToolBarButton doit être ContextMenu. - - - - The shortcut menu that will appear if this button's style is set to DropDownButton. - Le menu contextuel qui s'affiche si le style du bouton a la valeur DropDownButton. - - - - References that a non-existent ToolBarButton has been received. - Indique qu'un ToolBarButton inexistant a été reçu. - - - - Controls whether the button should be displayed as partially pushed or not, but only if the style of the button is ToggleButton. - Contrôle si le bouton doit être affiché comme étant partiellement enfoncé, mais uniquement si le style du bouton est ToggleButton. - - - - Indicates whether the button is pushed or not. This is most commonly seen for buttons with the TOGGLEBUTTON style. - Indique si le bouton est ou non enfoncé. Utilisé pour les boutons avec le style TOGGLEBUTTON. - - - - The size of the buttons on the control if the button contents do not require a larger size. - La taille des boutons du contrôle, si le contenu du bouton ne nécessite pas une taille plus grande. - - - - Indicates what style of ToolBarButton this will be. - Indique le style du ToolBarButton. - - - - The caption to be displayed for this button. - La légende à afficher pour ce bouton. - - - - The ToolTip text to be displayed for this button. - Le texte ToolTip à afficher pour ce bouton. - - - - Indicates whether this button should be visible. - Indique si ce bouton doit être visible. - - - - The collection of ToolBarButtons that make up this ToolBar. - La collection de ToolBarButtons qui composent ce ToolBar. - - - - Controls whether the ToolBar will display a 3-D line at the top of its client area. - Contrôle si le ToolBar affiche une ligne 3D en haut de la zone cliente. - - - - Controls whether the ToolBar will display an arrow on the side of drop-down buttons. - Contrôle si le ToolBar affiche une flèche sur le côté des boutons déroulants. - - - - The ImageList from which this ToolBar will get all of the button images. - Le ImageList à partir duquel ce ToolBar obtient toutes les images de boutons. - - - - The size of the images within the ToolBar's ImageList. - La taille des images dans le ImageList du ToolBar. - - - - Indicates whether ToolTips will be shown for each of the buttons, if available. - Indique si des info-bulles sont affichées pour chaque bouton, si elles sont disponibles. - - - - Controls how the text is positioned relative to the Image in each button. - Contrôle la façon dont le texte est positionné par rapport à l'image dans chaque bouton. - - - - Indicates if more than one row of buttons is allowed. - Indique si plusieurs lignes de boutons sont autorisées. - - AllowItemReorder and AllowDrop cannot both be true. AllowItemReorder et AllowDrop ne peuvent pas être true en même temps. diff --git a/src/System.Windows.Forms/src/Resources/xlf/SR.it.xlf b/src/System.Windows.Forms/src/Resources/xlf/SR.it.xlf index a9eb773e9ce..d56555db2c7 100644 --- a/src/System.Windows.Forms/src/Resources/xlf/SR.it.xlf +++ b/src/System.Windows.Forms/src/Resources/xlf/SR.it.xlf @@ -1217,34 +1217,9 @@ Form padre di questo controllo contenitore. - - Raised when the context menu collapses. - Generato quando si comprime il menu di scelta rapida. - - - - Gets or sets the ImageList associated with this context menu. - Ottiene o imposta il componente ImageList associato a questo menu di scelta rapida. - - - - ContextMenu cannot be shown on an invisible control. - Impossibile visualizzare il menu di scelta rapida su un controllo invisibile. - - - - Gets or sets a value indicating whether the menu has an image margin. - Ottiene o imposta un valore che indica se è presente un margine nell'immagine del menu. - - - - The last control that caused this context menu to be displayed. - Ultimo controllo che ha comportato la visualizzazione di questo menu di scelta rapida. - - The last control that caused this context menu strip to be displayed. - Ultimo controllo che ha causato la visualizzazione di questo elenco di menu di scelta rapida. + The last control that caused this context menu strip to be displayed. @@ -2107,466 +2082,6 @@ RemoveAt non è supportato per l'associazione da proprietà a proprietà. - - Indicates whether the grid can be re-sorted by clicking a column header. - Indica se è possibile riordinare la griglia facendo clic sull'intestazione di una colonna. - - - - Indicates the background color of alternating rows for a ledger appearance. - Indica il colore di sfondo a righe alterne per ottenere l'effetto registro. - - - - Occurs when the user clicks the Back button on a child table to return to the parent table. - Generato quando l'utente fa clic sul pulsante Indietro in una tabella figlio per tornare alla tabella padre. - - - - Indicates the color of the DataGrid background. - Indica il colore di sfondo del controllo DataGrid. - - - - BeginInit() has already been called without an EndInit(). - BeginInit() è già stato chiamato senza EndInit(). - - - - Specifies whether the DataGridBoolColumn allows null values. - Specifica se DataGridBoolColumn ammette valori null. - - - - Indicates the border style for the DataGrid. - Indica lo stile del bordo del controllo DataGrid. - - - - Navigates back to the parent rows. - Torna alle righe padre. - - - - Indicates the background color of the top caption. - Indica il colore di sfondo del titolo. - - - - Shows/Hides the parent rows for the current set of child rows. - Mostra o nasconde le righe padre del set di righe figlio corrente. - - - - Indicates the font of the top caption. - Indica il tipo di carattere del titolo. - - - - Indicates the color of text that appears in the top caption. - Indica il colore del testo del titolo. - - - - Indicates the text displayed in the top caption. - Indica il testo del titolo. - - - - Indicates whether the top caption is visible. - Indica se il titolo è visibile. - - - - DataGridColumn instance does not exist in the collection. - L'istanza DataGridColumn non esiste nella raccolta. - - - - Indicates whether the column headers are visible. - Indica se le intestazioni di colonna sono visibili. - - - - Position of ListManager must be equal to 'rowNum'. - La posizione di ListManager deve essere uguale a 'rowNum'. - - - - PropertyDescriptor has not been set on this DataGridColumn. - PropertyDescriptor non è stato impostato per questo DataGridColumn. - - - - Data grid column styles collection already contains a column style with the same mapping name. - La raccolta degli stili di colonna della griglia dei dati contiene già uno stile di colonna con lo stesso nome di mapping. - - - - DataGridColumnStyle of '{0}' cannot be used because it is not associated with a Property or Column in the DataSource. - La classe DataGridColumnStyle di '{0}' non può essere utilizzata perché non è associata a una proprietà o a una colonna in DataSource. - - - - ColumnWidth must be greater than or equal to 0. - ColumnWidth deve essere maggiore o uguale a 0. - - - - The currently selected cell in the DataGrid. - La cella correntemente selezionata del DataGrid. - - - - Indicates a sub-list of the DataSource to show in the DataGrid. - Indica un sottoelenco del DataSource da mostrare nel DataGrid. - - - - Indicates the source of data for the DataGrid. - Indica l'origine dati del DataGrid. - - - - User cannot change the contents of the default GridColumnStylesCollection. - All'utente non è consentito modificare il contenuto della classe GridColumnStylesCollection predefinita. - - - - Value of this property cannot be changed on the default DataGridTableStyle. - Impossibile modificare il valore della proprietà nella classe DataGridTableStyle predefinita. - - - - Occurs when the user clicks the "show/hide parent rows" icon. - Generato quando l'utente fa clic sull'icona che consente di mostrare o nascondere le righe padre. - - - - Value '{0}' cannot be set to an empty value. - Impossibile impostare '{0}' su un valore vuoto. - - - - Committing the row to the original data store has caused an error. - Errore durante il commit della riga all'archivio dati originale. - - - - DataGrid received an exception at design time. Reset the DataSource and DataMember property on the grid. - DataGrid ha ricevuto un'eccezione in fase di progettazione. Reimpostare le proprietà DataSource e DataMember sulla griglia. - - - - Program cannot get information about the painting and scrolling region. - Impossibile ottenere informazioni circa l'area utilizzata per il disegno e lo scorrimento. - - - - Indicates the index of the column that is first shown. - Indica l'indice della prima colonna visualizzata. - - - - Indicates whether the grid has a flat appearance. - Indica se la griglia si presenta piatta. - - - - Indicates the color of the grid lines. - Indica il colore delle linee della griglia. - - - - Indicates the style of the grid lines. - Indica lo stile delle linee della griglia. - - - - The collection of DataGridTableStyle objects that the DataGrid can render its data with. - La raccolta di oggetti DataGridTableStyle mediante i quali DataGrid può eseguire il rendering dei dati. - - - - Indicates the background color of the column and row headers. - Indica il colore di sfondo delle intestazioni di colonna e di riga. - - - - Indicates the font of the text in the column and row headers. - Indica il tipo di carattere del testo delle intestazioni di colonna e di riga. - - - - Indicates the color of the text in the column and row headers. - Indica il colore del testo delle intestazioni di colonna e di riga. - - - - Returns the horizontal scroll bar used by the grid. - Restituisce la barra di scorrimento orizzontale utilizzata dalla griglia. - - - - Indicates the color of the text that appears inside the child links. - Indica il colore del testo che appare all'interno dei collegamenti figlio. - - - - Indicates the color of the text that appears inside a child link when the mouse pointer moves over it. - Indica il colore del testo che appare all'interno di un collegamento figlio al passaggio del mouse. - - - - The CurrencyManager that the DataGrid uses to get data from the data source. - Oggetto CurrencyManager utilizzato da DataGrid per ottenere i dati dall'origine dati. - - - - Occurs when the user navigates to the child rows or when the user navigates back to the parent rows. - Generato quando l'utente passa alle righe figlio o torna alle righe padre. - - - - Indicates whether links to child tables are shown. - Indica se i collegamenti alle tabelle figlio sono visualizzati. - - - - Occurs when the user clicks on the expansion glyph on the row header. - Generato quando l'utente fa clic sull'icona di espansione dell'intestazione della colonna. - - - - (null) - (null) - - - - Event raised when the value of the BackgroundColor property is changed on DataGrid. - Evento generato quando il valore della proprietà BackgroundColor viene modificato su DataGrid. - - - - Event raised when the value of the BorderStyle property is changed on DataGrid. - Evento generato quando il valore della proprietà BorderStyle del controllo DataGrid viene modificato. - - - - Event raised when the value of the CaptionVisible property is changed on DataGrid. - Evento generato quando il valore della proprietà CaptionVisible del controllo DataGrid viene modificato. - - - - Event raised when the value of the CurrentCell property is changed on DataGrid. - Evento generato quando il valore della proprietà CurrentCell del controllo DataGrid viene modificato. - - - - Event raised when the value of the DataSource property is changed on DataGrid. - Evento generato quando il valore della proprietà DataSource del controllo DataGrid viene modificato. - - - - Event raised when the value of the FlatMode property is changed on DataGrid. - Evento generato quando il valore della proprietà FlatMode del controllo DataGrid viene modificato. - - - - Event raised when the value of the NavigationMode property is changed on DataGrid. - Evento generato quando il valore della proprietà NavigationMode del controllo DataGrid viene modificato. - - - - Event raised when the value of the ParentRowsLabelStyle property is changed on DataGrid. - Evento generato quando il valore della proprietà ParentRowsLabelStyle del controllo DataGrid viene modificato. - - - - Event raised when the value of the ParentRowsVisible property is changed on DataGrid. - Evento generato quando il valore della proprietà ParentRowsVisible del controllo DataGrid viene modificato. - - - - Event raised when the value of the ReadOnly property is changed on DataGrid. - Evento generato quando il valore della proprietà ReadOnly del controllo DataGrid viene modificato. - - - - Indicates the background color of the parent rows. - Indica il colore di sfondo delle righe padre. - - - - Indicates the color of the text in the parent rows. - Indica il colore del testo delle righe padre. - - - - Indicates whether the parent rows show labels for the table and for the columns. - Indica se le righe padre mostrano etichette per la tabella e le colonne. - - - - Indicates whether the parent rows area is visible. - Indica se l'area delle righe padre è visibile. - - - - Specifies what the default pixel widths of the grid columns are. The default value for PreferredColumnWidth is 75. - Specifica la larghezza predefinita in pixel delle colonne della griglia. Il valore predefinito di PreferredColumnWidth è 75. - - - - Indicates the preferred height of the rows. - Indica l'altezza preferenziale delle righe. - - - - Value {0} Do you want to correct this value? - Valore {0}. Correggere il valore? - - - - Indicates whether rows in the grid can be edited, added, or deleted. - Indica se è possibile modificare, aggiungere o eliminare le righe della griglia. - - - - Indicates the width of the row headers. - Indica la larghezza delle intestazioni di riga. - - - - Indicates whether the row headers are visible. - Indica se le intestazioni di riga sono visibili. - - - - DataGridRow.Height cannot be negative. - DataGridRow.Height non può assumere un valore negativo. - - - - DataGridRow cannot have a negative row number. - DataGridRow non può avere un numero di righe negativo. - - - - Occurs when the user scrolls either the horizontal or vertical scroll bar. - Generato quando l'utente utilizza la barra di scorrimento orizzontale o verticale. - - - - Indicates the index of the current row. - Indica l'indice della riga corrente. - - - - Indicates the background color of any selected cells or rows. - Indica il colore di sfondo delle celle o delle righe selezionate. - - - - Indicates the color of the text in any selected cells or rows. - Indica il colore del testo delle celle o delle righe selezionate. - - - - ListManager can be set using the DataSource and DataMember properties. - È possibile impostare ListManager utilizzando le proprietà DataSource e DataMember. - - - - Position on a null ListManager cannot be set. - Impossibile impostare la posizione su un ListManager null. - - - - CurrentCell cannot be set at this time. Moving your code to the Form.Load event should solve this problem. - Impossibile impostare CurrentCell in questo momento. Per risolvere il problema, spostare il codice nell'evento Form.Load. - - - - DataGridTable instance does not exist in the collection. - L'istanza DataGridTable non esiste nella raccolta. - - - - DataGridTableStyle that is already parented to another DataGrid cannot be added. - Impossibile aggiungere un DataGridTableStyle che ha già un altro DataGrid come padre. - - - - Data grid table styles collection already contains a table style with the same mapping name. - La raccolta degli stili di tabella della griglia dei dati contiene uno stile di tabella con lo stesso nome di mapping. - - - - DataGridTableStyle does not support transparent AlternatingBackColor. - DataGridTableStyle non supporta colori di sfondo alternativi (AlternatingBackColor) trasparenti. - - - - DataGridTableStyle does not support transparent BackColor. - DataGridTableStyle non supporta colori di sfondo (BackColor) trasparenti. - - - - DataGridTableStyle does not support transparent HeaderBackColor. - DataGridTableStyle supporta colori di sfondo dell'intestazione trasparenti. - - - - DataGridTableStyle does not support transparent SelectionBackColor. - DataGridTableStyle non supporta colori di sfondo della selezione trasparenti. - - - - null rectangle for icon bounds when adding tool tip. - Rettangolo null per i limiti dell'icona durante l'aggiunta della descrizione comandi. - - - - DataGrid control does not support transparent AlternatingBackColor. - Il controllo DataGrid non supporta colori di sfondo alternativi (AlternatingBackColor) trasparenti. - - - - DataGrid control does not support transparent BackColor. - Il controllo DataGrid non supporta colori di sfondo (BackColor) trasparenti. - - - - DataGrid control does not support transparent CaptionBackColor. - Il controllo DataGrid non supporta colori di sfondo del titolo trasparenti. - - - - DataGrid control does not support transparent HeaderBackColor. - Il controllo DataGrid non supporta colori di sfondo dell'intestazione trasparenti. - - - - DataGrid control does not support transparent ParentRowsBackColor. - Il controllo DataGrid non supporta colori di sfondo trasparenti per l'area delle righe padre. - - - - DataGrid control does not support transparent SelectionBackColor. - Il controllo DataGrid non supporta colori di sfondo della selezione trasparenti. - - - - Data cannot be read from a DataGrid which is not bound to a DataTable. - Impossibile leggere dati da un DataGrid non associato a un DataTable. - - - - Returns the vertical scroll bar used by the grid. - Restituisce le barre di scorrimento verticali utilizzate dalla griglia. - - Occurs when the value of the AlternatingRowsDefaultCellStyle property changes. Generato quando il valore della proprietà AlternatingRowsDefaultCellStyle cambia. @@ -5657,21 +5172,11 @@ Sostituirlo? La dimensione massima che il form può assumere. - - The main menu of the form. This must be set to a component of type MainMenu. - Il menu principale del form. Deve essere impostato su un componente di tipo MainMenu. - - Specifies the primary MenuStrip for the Form. This property is used for keyboard activation and automatic merging in MDI. Specifica il MenuStrip principale per il form. Questa proprietà consente l'attivazione della tastiera e il merge automatico in MDI. - - The merged menu of this form, which is used when displaying a single merged MDI menu. - Il menu sottoposto a merge di questo form, utilizzato quando si visualizza un menu MDI singolo sottoposto a merge. - - Determines whether a form has a minimize box in the upper-right corner of its caption bar. Determina se un form dispone di un pulsante di riduzione a icona nella parte superiore destra della barra del titolo. @@ -7171,26 +6676,6 @@ Traccia dello stack da cui si è verificata l'operazione non valida: Il form specificato come MdiParent per questo form non è un MdiContainer. - - Occurs when the main menu collapses. - Generato quando si comprime il menu principale. - - - - Gets or sets the ImageList associated with this main menu. - Ottiene o imposta il componente ImageList associato al menu principale. - - - - Gets or sets a value indicating whether the menu has an image margin. - Ottiene o imposta un valore che indica se è presente un margine nell'immagine del menu. - - - - <No Form> - <No Form> - - Indicates whether the prompt character is valid as input. Indica se il carattere di prompt è valido come input. @@ -7326,139 +6811,14 @@ Traccia dello stack da cui si è verificata l'operazione non valida: Specifica il tipo di oggetto da utilizzare per l'analisi del testo di input quando il controllo perde lo stato attivo. - - Parameter must be of type MenuItem. - Il parametro deve essere di tipo MenuItem. - - - - Gets or sets the background color of this menu's image margin. - Ottiene o imposta il colore di sfondo del margine dell'immagine del menu. - - - - Indicates if this menu contains any child items. - Indica se questo menu contiene elementi figlio. - - - - Cannot add MenuItem '{0}'. It already exists as a parent of the current menu item. - Impossibile aggiungere il MenuItem '{0}', perché esiste già ed è l'elemento padre della voce di menu corrente. - - - - Indicates whether the item is checked. - Indica se l'elemento è selezionato. - - - - Indicates whether the item is the default item. - Indica se l'elemento è l'elemento predefinito. - - - - Indicates whether the item is enabled. - Indica se l'elemento è abilitato. - - - - Gets or sets the image to be displayed on this menu item. - Ottiene o imposta l'immagine da visualizzare per la voce di menu corrente. - - - - Gets or sets the ImageList associated with this menu item. - Ottiene o imposta il componente ImageList associato alla voce di menu corrente. - - - - Gets or sets the background color of this menu item's image margin. - Ottiene o imposta il colore di sfondo del margine dell'immagine della voce di menu corrente. - - - - True is not a valid value for the Checked property. This is only valid for MenuItems that have no children and are not top-level. - True non è un valore valido per la proprietà Checked. Tale valore è valido solo per un MenuItem che non ha elementi figlio e non è di livello principale. - - - - Determines whether the MDI child window list is appended to this item. - Determina se l'elenco delle finestre figlio MDI viene accodato a questo elemento. - - - - Determines the merge order of the item. - Determina l'ordine di merge dell'elemento. - - - - Determines how the item is handled when menus are merged. - Determina come viene gestito l'elemento in caso di merge di menu. - - - - Occurs when the menu item is selected. - Generato quando la voce di menu viene selezionata. - - - - Occurs before the containing menu is displayed. - Generato prima della visualizzazione del menu che lo contiene. - - - - Occurs when the menu item is selected. - Generato quando la voce di menu viene selezionata. - - - - Indicates if Windows will draw the menu item or if the user will handle the painting. - Indica se il disegno dell'elemento di menu viene eseguito da Windows o dall'utente. - - - - If the item is checked, this value will determine whether the check style is a radio button. - Se la voce è selezionata, questo valore indica se lo stile di selezione è un pulsante di opzione. - - The shortcut key associated with the menu item. - Il tasto di scelta rapida associato alla voce di menu. + The shortcut key associated with the menu item. Indicates whether the shorcut key for the menu item is displayed on the item. - Indica se il tasto di scelta rapida della voce di menu viene visualizzato sulla voce. - - - - The caption displayed by the item. - La didascalia visualizzata dall'elemento. - - - - Indicates whether the item is visible. - Indica se l'elemento è visibile. - - - - Retrieves the menu item that contains a list of MDI child windows. - Recupera la voce di menu che contiene un elenco di finestre figlio MDI. - - - - The menu items for the menu. - Le voci del menu. - - - - Cannot merge a menu with itself. - Impossibile eseguire il merge di un menu con se stesso. - - - - Indicates if this menu should display right to left - Indica se visualizzare questo menu da destra a sinistra. + Indicates whether the shorcut key for the menu item is displayed on the item. @@ -9976,136 +9336,6 @@ Traccia dello stack da cui si è verificata l'operazione non valida: Troppe chiamate a ResumeUpdateMenuHandles. - - Controls the appearance of the ToolBar control, using values from the ToolBarAppearance enumeration. - Determina l'aspetto del controllo ToolBar utilizzando i valori dell'enumerazione ToolBarAppearance. - - - - Controls whether the ToolBar will automatically size itself based on Button size. - Determina se viene effettuato il ridimensionamento automatico del controllo ToolBar in base alla dimensione del controllo Button. - - - - Parameter must be of type ToolBarButton. - Il parametro deve essere di tipo ToolBarButton. - - - - Controls what type of border the ToolBar control will have. - Determina il tipo di bordo del controllo ToolBar. - - - - Occurs whenever a button in the ToolBar is clicked by the user. - Generato quando l'utente fa clic su un pulsante del controllo ToolBar. - - - - Occurs whenever a button with the DropDownButton style is pressed. - Generato quando si fa clic su un pulsante con lo stile DropDownButton. - - - - Controls whether this button responds to user input. - Determina se questo pulsante risponde all'input dell'utente. - - - - Identifies the image displayed on the button. - Identifica l'immagine visualizzata sul pulsante. - - - - The drop-down menu for a ToolBarButton must be of type ContextMenu. - Il menu a discesa di ToolBarButton deve essere di tipo ContextMenu. - - - - The shortcut menu that will appear if this button's style is set to DropDownButton. - Il menu di scelta rapida che verrà visualizzato se lo stile di questo pulsante è DropDownButton. - - - - References that a non-existent ToolBarButton has been received. - Ricevuto ToolBarButton inesistente. - - - - Controls whether the button should be displayed as partially pushed or not, but only if the style of the button is ToggleButton. - Se lo stile del pulsante è ToggleButton, determina se il pulsante deve essere visualizzato come parzialmente premuto. - - - - Indicates whether the button is pushed or not. This is most commonly seen for buttons with the TOGGLEBUTTON style. - Indica se il pulsante è premuto. Normalmente si utilizza con pulsanti con lo stile TOGGLEBUTTON. - - - - The size of the buttons on the control if the button contents do not require a larger size. - La dimensione dei pulsanti del controllo se il contenuto dei pulsanti non richiede una dimensione maggiore. - - - - Indicates what style of ToolBarButton this will be. - Indica lo stile del controllo ToolBarButton. - - - - The caption to be displayed for this button. - La didascalia da visualizzare per questo pulsante. - - - - The ToolTip text to be displayed for this button. - Il testo di ToolTip da visualizzare per questo pulsante. - - - - Indicates whether this button should be visible. - Indica se questo pulsante deve essere visibile. - - - - The collection of ToolBarButtons that make up this ToolBar. - La raccolta di controlli ToolBarButton che appartengono a questo controllo ToolBar. - - - - Controls whether the ToolBar will display a 3-D line at the top of its client area. - Determina se la barra degli strumenti visualizzerà una riga 3D nella parte superiore della propria area client. - - - - Controls whether the ToolBar will display an arrow on the side of drop-down buttons. - Determina se nel controllo ToolBar verrà visualizzata una freccia accanto ai pulsanti a discesa. - - - - The ImageList from which this ToolBar will get all of the button images. - ImageList da cui questo controllo ToolBar recupera tutte le immagini dei pulsanti. - - - - The size of the images within the ToolBar's ImageList. - La dimensione delle immagini in ImageList di ToolBar. - - - - Indicates whether ToolTips will be shown for each of the buttons, if available. - Indica se visualizzare componenti ToolTip per ciascun pulsante, se disponibili. - - - - Controls how the text is positioned relative to the Image in each button. - Determina in che modo verrà posizionato il testo dei pulsanti rispetto all'immagine. - - - - Indicates if more than one row of buttons is allowed. - Indica se è consentita più di una riga di pulsanti. - - AllowItemReorder and AllowDrop cannot both be true. Le proprietà AllowItemReorder e AllowDrop non possono avere entrambe valore true. diff --git a/src/System.Windows.Forms/src/Resources/xlf/SR.ja.xlf b/src/System.Windows.Forms/src/Resources/xlf/SR.ja.xlf index 16c293aeab7..600089d2b6a 100644 --- a/src/System.Windows.Forms/src/Resources/xlf/SR.ja.xlf +++ b/src/System.Windows.Forms/src/Resources/xlf/SR.ja.xlf @@ -1217,34 +1217,9 @@ このコンテナー コントロールの親フォームです。 - - Raised when the context menu collapses. - コンテキスト メニューが縮小するときに発生します。 - - - - Gets or sets the ImageList associated with this context menu. - このコンテキスト メニューに関連付けられた ImageList を取得および設定します。 - - - - ContextMenu cannot be shown on an invisible control. - 非表示のコントロールでは、ContextMenu を表示できません。 - - - - Gets or sets a value indicating whether the menu has an image margin. - メニューがイメージの余白を持つかどうかを示す値を取得または設定します。 - - - - The last control that caused this context menu to be displayed. - このコンテキスト メニューを最後に表示させたコントロールです。 - - The last control that caused this context menu strip to be displayed. - このコンテキスト メニュー ストリップを最後に表示させたコントロールです。 + The last control that caused this context menu strip to be displayed. @@ -2107,466 +2082,6 @@ RemoveAt は、プロパティからプロパティへの バインドに対してサポートされていません。 - - Indicates whether the grid can be re-sorted by clicking a column header. - 列ヘッダーをクリックして、グリッドを再度並べ替えられるかどうかを示します。 - - - - Indicates the background color of alternating rows for a ledger appearance. - 帳簿の表示方法で、交互に色が変更される列の背景色を示します。 - - - - Occurs when the user clicks the Back button on a child table to return to the parent table. - 子テーブル上の [戻る] をクリックして親テーブルに戻ったときに発生します。 - - - - Indicates the color of the DataGrid background. - DataGrid の背景色を示します。 - - - - BeginInit() has already been called without an EndInit(). - EndInit() なしに、BeginInit() は既に呼び出されました。 - - - - Specifies whether the DataGridBoolColumn allows null values. - DataGridBoolColumn が Null 値を許容するかどうかを指定します。 - - - - Indicates the border style for the DataGrid. - DataGrid の境界線スタイルを示します。 - - - - Navigates back to the parent rows. - 親行に戻ります。 - - - - Indicates the background color of the top caption. - 上部のキャプションの背景色を示します。 - - - - Shows/Hides the parent rows for the current set of child rows. - 現在の子行のセットを表示/非表示にします。 - - - - Indicates the font of the top caption. - 上部のキャプションのフォントを示します。 - - - - Indicates the color of text that appears in the top caption. - 上部のキャプションに表示されるテキストの色を示します。 - - - - Indicates the text displayed in the top caption. - 上部のキャプションに表示されるテキストを示します。 - - - - Indicates whether the top caption is visible. - 上部のキャプションが表示可能かどうかを示します。 - - - - DataGridColumn instance does not exist in the collection. - DataGridColumn インスタンスはコレクションに存在しません。 - - - - Indicates whether the column headers are visible. - 列ヘッダーを表示するかどうかを示します。 - - - - Position of ListManager must be equal to 'rowNum'. - ListManager の位置は 'rowNum' と同じでなければなりません。 - - - - PropertyDescriptor has not been set on this DataGridColumn. - PropertyDescriptor はこの DataGridColumn で設定されていません。 - - - - Data grid column styles collection already contains a column style with the same mapping name. - データ グリッドの列スタイル コレクションには、既に同じマップ名の列スタイルが含まれています。 - - - - DataGridColumnStyle of '{0}' cannot be used because it is not associated with a Property or Column in the DataSource. - '{0}' の DataGridColumnStyle は、DataSource でプロパティまたは列に関連付けられていないため、使用できません。 - - - - ColumnWidth must be greater than or equal to 0. - ColumnWidth は 0 以上でなければなりません。 - - - - The currently selected cell in the DataGrid. - DataGrid で現在選択されているセルです。 - - - - Indicates a sub-list of the DataSource to show in the DataGrid. - DataGrid で表示する DataSource のサブリストを示します。 - - - - Indicates the source of data for the DataGrid. - DataGrid のデータのソースを示します。 - - - - User cannot change the contents of the default GridColumnStylesCollection. - ユーザーは、既定の GridColumnStylesCollection の内容を変更できません。 - - - - Value of this property cannot be changed on the default DataGridTableStyle. - 既定の DataGridTableStyle でこのプロパティの値を変更できません。 - - - - Occurs when the user clicks the "show/hide parent rows" icon. - [親行の表示/非表示] アイコンをクリックしたときに発生します。 - - - - Value '{0}' cannot be set to an empty value. - 値 '{0}' を空の値に設定できません。 - - - - Committing the row to the original data store has caused an error. - オリジナルのデータ ストアに行をコミットして、エラーが発生しました。 - - - - DataGrid received an exception at design time. Reset the DataSource and DataMember property on the grid. - DataGrid はデザイン時に例外を受け取りました。グリッドの DataSource と DataMember プロパティを再設定してください。 - - - - Program cannot get information about the painting and scrolling region. - 描画およびスクロールに使われる領域に関する情報をプログラムで取得できませんでした。 - - - - Indicates the index of the column that is first shown. - 最初に表示される列のインデックスを示します。 - - - - Indicates whether the grid has a flat appearance. - グリッドの外観をフラットにするかどうかを示します。 - - - - Indicates the color of the grid lines. - グリッド線の色を示します。 - - - - Indicates the style of the grid lines. - グリッド線のスタイルを示します。 - - - - The collection of DataGridTableStyle objects that the DataGrid can render its data with. - DataGrid がそのデータを表示できる DataGridTableStyle オブジェクトのコレクションです。 - - - - Indicates the background color of the column and row headers. - 列と行のヘッダーの背景色を示します。 - - - - Indicates the font of the text in the column and row headers. - 列と行のヘッダーのテキストのフォントを示します。 - - - - Indicates the color of the text in the column and row headers. - 列と行のヘッダーのテキストの色を示します。 - - - - Returns the horizontal scroll bar used by the grid. - グリッドが使用する水平スクロール バーを返します。 - - - - Indicates the color of the text that appears inside the child links. - 子リンク内部に表示されるテキストの色を示します。 - - - - Indicates the color of the text that appears inside a child link when the mouse pointer moves over it. - マウス ポインターが移動したときに子リンク内に表示されるテキストの色を示します。 - - - - The CurrencyManager that the DataGrid uses to get data from the data source. - DataGrid がデータ ソースからデータを取得するために使用する CurrencyManager です。 - - - - Occurs when the user navigates to the child rows or when the user navigates back to the parent rows. - ユーザーが子行に移動したときまたは親行に戻ったときに発生します。 - - - - Indicates whether links to child tables are shown. - 子テーブルへのリンクを表示するかどうかを示します。 - - - - Occurs when the user clicks on the expansion glyph on the row header. - ユーザーが行ヘッダーの拡張グラフィックスをクリックしたときに発生します。 - - - - (null) - (なし) - - - - Event raised when the value of the BackgroundColor property is changed on DataGrid. - BackgroundColor プロパティの値が DataGrid で変更されたときに発生するイベントです。 - - - - Event raised when the value of the BorderStyle property is changed on DataGrid. - BorderStyle プロパティの値が DataGrid で変更されたときに発生するイベントです。 - - - - Event raised when the value of the CaptionVisible property is changed on DataGrid. - CaptionVisible プロパティの値が DataGrid で変更されたときに発生するイベントです。 - - - - Event raised when the value of the CurrentCell property is changed on DataGrid. - CurrentCell プロパティの値が DataGrid で変更されたときに発生するイベントです。 - - - - Event raised when the value of the DataSource property is changed on DataGrid. - DataSource プロパティの値が DataGrid で変更されたときに発生するイベントです。 - - - - Event raised when the value of the FlatMode property is changed on DataGrid. - FlatMode プロパティの値が DataGrid で変更されたときに発生するイベントです。 - - - - Event raised when the value of the NavigationMode property is changed on DataGrid. - NavigationMode プロパティの値が DataGrid で変更されたときに発生するイベントです。 - - - - Event raised when the value of the ParentRowsLabelStyle property is changed on DataGrid. - ParentRowsLabelStyle プロパティの値が DataGrid で変更されたときに発生するイベントです。 - - - - Event raised when the value of the ParentRowsVisible property is changed on DataGrid. - ParentRowsVisible プロパティの値が DataGrid で変更されたときに発生するイベントです。 - - - - Event raised when the value of the ReadOnly property is changed on DataGrid. - ReadOnly プロパティの値が DataGrid で変更されたときに発生するイベントです。 - - - - Indicates the background color of the parent rows. - 親の行の背景色を示します。 - - - - Indicates the color of the text in the parent rows. - 親の行のテキストの色を示します。 - - - - Indicates whether the parent rows show labels for the table and for the columns. - 親の行がテーブルと列のラベルを表示するかどうかを示します。 - - - - Indicates whether the parent rows area is visible. - 親の行領域を表示するかどうかを示します。 - - - - Specifies what the default pixel widths of the grid columns are. The default value for PreferredColumnWidth is 75. - グリッド コラムの既定のピクセル幅を指定します。PreferredColumnWidth の既定値は 75 です。 - - - - Indicates the preferred height of the rows. - 行の適切な高さを示します。 - - - - Value {0} Do you want to correct this value? - 値 {0} を修正しますか? - - - - Indicates whether rows in the grid can be edited, added, or deleted. - グリッドの行を編集、追加、削除できるかどうかを示します。 - - - - Indicates the width of the row headers. - 行ヘッダーの幅を示します。 - - - - Indicates whether the row headers are visible. - 行ヘッダーが表示されているかどうかを示します。 - - - - DataGridRow.Height cannot be negative. - DataGridRow.Height を負の値にすることはできません。 - - - - DataGridRow cannot have a negative row number. - DataGridRow に負の値の行番号を指定することはできません。 - - - - Occurs when the user scrolls either the horizontal or vertical scroll bar. - ユーザーが水平または垂直スクロール バーをスクロールしたときに発生します。 - - - - Indicates the index of the current row. - 現在の行のインデックスを示します。 - - - - Indicates the background color of any selected cells or rows. - 選択されているセルまたは行の背景色を示します。 - - - - Indicates the color of the text in any selected cells or rows. - 選択されているセルまたは行のテキストの色を示します。 - - - - ListManager can be set using the DataSource and DataMember properties. - ListManager は DataSource および DataMember プロパティを使用して設定することができます。 - - - - Position on a null ListManager cannot be set. - Null の ListManager で位置を設定できません。 - - - - CurrentCell cannot be set at this time. Moving your code to the Form.Load event should solve this problem. - CurrentCell は現時点では設定できません。この問題を解決するには、コードを Form.Load イベントに移動してください。 - - - - DataGridTable instance does not exist in the collection. - DataGridTable インスタンスはコレクションに存在しません。 - - - - DataGridTableStyle that is already parented to another DataGrid cannot be added. - 既に別の DataGrid の親になっている DataGridTableStyle を追加することはできません。 - - - - Data grid table styles collection already contains a table style with the same mapping name. - このデータ グリッドのテーブル スタイル コレクションには既に同じマップ名のテーブル スタイルが含まれています。 - - - - DataGridTableStyle does not support transparent AlternatingBackColor. - DataGridTableStyle は、透明色の AlternatingBackColor をサポートしません。 - - - - DataGridTableStyle does not support transparent BackColor. - DataGridTableStyle は、透明色の BackColor をサポートしません。 - - - - DataGridTableStyle does not support transparent HeaderBackColor. - DataGridTableStyle は、透明色の HeaderBackColor をサポートしません。 - - - - DataGridTableStyle does not support transparent SelectionBackColor. - DataGridTableStyle は、透明色の SelectionBackColor をサポートしません。 - - - - null rectangle for icon bounds when adding tool tip. - ツールヒントを追加する場合に作成されるアイコンの境界線の Null 四角形です。 - - - - DataGrid control does not support transparent AlternatingBackColor. - DataGrid コントロールは、透明色の AlternatingBackColor をサポートしません。 - - - - DataGrid control does not support transparent BackColor. - DataGrid コントロールは、透明色の BackColor をサポートしません。 - - - - DataGrid control does not support transparent CaptionBackColor. - DataGrid コントロールは、透明色の CaptionBackColor をサポートしません。 - - - - DataGrid control does not support transparent HeaderBackColor. - DataGrid コントロールは、透明色の HeaderBackColor をサポートしません。 - - - - DataGrid control does not support transparent ParentRowsBackColor. - DataGrid コントロールは、透明色の ParentRowsBackColor をサポートしません。 - - - - DataGrid control does not support transparent SelectionBackColor. - DataGrid コントロールは、透明色の SelectionBackColor をサポートしません。 - - - - Data cannot be read from a DataGrid which is not bound to a DataTable. - DataTable にバインドされていない DataGrid からデータを読み取ることができません。 - - - - Returns the vertical scroll bar used by the grid. - グリッドが使用する垂直スクロール バーを返します。 - - Occurs when the value of the AlternatingRowsDefaultCellStyle property changes. AlternatingRowsDefaultCellStyle プロパティの値が変更したときに発生します。 @@ -5657,21 +5172,11 @@ Do you want to replace it? サイズを変更するときのフォームの最大値です。 - - The main menu of the form. This must be set to a component of type MainMenu. - フォームのメイン メニューです。このメニューを型 MainMenu のコンポーネントに設定しなければなりません。 - - Specifies the primary MenuStrip for the Form. This property is used for keyboard activation and automatic merging in MDI. フォームの主要な MenuStrip を指定します。このプロパティは、キーボードのアクティブ化および MDI での自動マージのために使用されます。 - - The merged menu of this form, which is used when displaying a single merged MDI menu. - 単一のマージされた MDI メニューを表示するときに使用される、このフォームのマージされたメニューです。 - - Determines whether a form has a minimize box in the upper-right corner of its caption bar. フォームがキャプション バーの右上に最小化ボタンを指定するかどうかを決定します。 @@ -7171,26 +6676,6 @@ Stack trace where the illegal operation occurred was: このフォームの MdiParent として指定されたフォームは MdiContainer ではありません。 - - Occurs when the main menu collapses. - メイン メニューが縮小するときに発生します。 - - - - Gets or sets the ImageList associated with this main menu. - このメイン メニューに関連付けられた ImageList を取得または設定します。 - - - - Gets or sets a value indicating whether the menu has an image margin. - メニューがイメージの余白を持つかどうかを示す値を取得または設定します。 - - - - <No Form> - <No Form> - - Indicates whether the prompt character is valid as input. プロンプト文字が入力として有効であるかどうかを示します。 @@ -7326,139 +6811,14 @@ Stack trace where the illegal operation occurred was: コントロールがフォーカスを失ったときに、入力テキストを解析するために使用されるオブジェクトの型を指定します。 - - Parameter must be of type MenuItem. - パラメーターは、型 MenuItem でなければなりません - - - - Gets or sets the background color of this menu's image margin. - このメニューのイメージの余白の背景色を取得または設定します。 - - - - Indicates if this menu contains any child items. - メニューが子のアイテムを含んでいるかどうかどうかを示します。 - - - - Cannot add MenuItem '{0}'. It already exists as a parent of the current menu item. - MenuItem '{0}' を追加できません。現在のメニュー項目の親として既に存在します。 - - - - Indicates whether the item is checked. - アイテムがチェックされているかどうかを示します。 - - - - Indicates whether the item is the default item. - アイテムが既定のアイテムかどうかを示します。 - - - - Indicates whether the item is enabled. - アイテムが有効にされているかどうかを示します。 - - - - Gets or sets the image to be displayed on this menu item. - このメニュー項目で表示されるイメージを取得または設定します。 - - - - Gets or sets the ImageList associated with this menu item. - このメニュー項目に関連付けられた ImageList を取得または設定します。 - - - - Gets or sets the background color of this menu item's image margin. - このメニュー項目のイメージの余白の背景色を取得または設定します。 - - - - True is not a valid value for the Checked property. This is only valid for MenuItems that have no children and are not top-level. - True は Checked プロパティの有効な値ではありません。 子がなく、トップレベルでない MenuItem に対してのみ有効です。 - - - - Determines whether the MDI child window list is appended to this item. - MDI 子ウィンドウのリストをこの項目に追加するかどうかを決定します。 - - - - Determines the merge order of the item. - アイテムをマージする順序を決定します。 - - - - Determines how the item is handled when menus are merged. - メニューがマージされるときに項目を処理する方法を決定します。 - - - - Occurs when the menu item is selected. - メニュー項目が選択されたときに発生します。 - - - - Occurs before the containing menu is displayed. - メニューが表示される前に発生します。 - - - - Occurs when the menu item is selected. - メニュー項目が選択されたときに発生します。 - - - - Indicates if Windows will draw the menu item or if the user will handle the painting. - Windows がメニュー項目を描画するか、ユーザーが描画を行うかを示します。 - - - - If the item is checked, this value will determine whether the check style is a radio button. - この項目がチェックされると、この値は、チェック スタイルをオプション ボタンにするかどうかを決定します。 - - The shortcut key associated with the menu item. - メニュー項目に関連付けられたショートカット キーです。 + The shortcut key associated with the menu item. Indicates whether the shorcut key for the menu item is displayed on the item. - メニュー項目のショートカット キーをアイテムに表示するかどうかを示します。 - - - - The caption displayed by the item. - アイテムによって表示されたタイトルです。 - - - - Indicates whether the item is visible. - アイテムを表示するかどうかを示します。 - - - - Retrieves the menu item that contains a list of MDI child windows. - MDI 子ウィンドウのリストを含むメニュー項目を取得します。 - - - - The menu items for the menu. - メニューのメニュー項目です。 - - - - Cannot merge a menu with itself. - メニューをそれ自体にマージできません。 - - - - Indicates if this menu should display right to left - このメニューが右から左に表示されるかどうかを示します。 + Indicates whether the shorcut key for the menu item is displayed on the item. @@ -9976,136 +9336,6 @@ Stack trace where the illegal operation occurred was: ResumeUpdateMenuHandles への呼び出しが多すぎます。 - - Controls the appearance of the ToolBar control, using values from the ToolBarAppearance enumeration. - ToolBarAppearance 列挙 からの値を用いて、ToolBar コントロールの外観を制御します。 - - - - Controls whether the ToolBar will automatically size itself based on Button size. - ボタンのサイズに基づいて、ツール バーのサイズを自動的に変更するかどうかを制御します。 - - - - Parameter must be of type ToolBarButton. - パラメーターは型 ToolBarButton でなければなりません。 - - - - Controls what type of border the ToolBar control will have. - ツール バー コントロールの境界線の種類を設定します。 - - - - Occurs whenever a button in the ToolBar is clicked by the user. - ユーザーがツール バーのボタンをクリックしたときに発生します。 - - - - Occurs whenever a button with the DropDownButton style is pressed. - DropDownButton スタイルのボタンがクリックされたときに発生します。 - - - - Controls whether this button responds to user input. - このボタンがユーザーの入力に応答するかどうかを制御します。 - - - - Identifies the image displayed on the button. - ボタンに表示されたイメージを識別します。 - - - - The drop-down menu for a ToolBarButton must be of type ContextMenu. - ToolBarButton のドロップダウン メニューは ContextMenu 型でなければなりません。 - - - - The shortcut menu that will appear if this button's style is set to DropDownButton. - このボタンのスタイルが DropDownButton に設定されている場合に表示されるショートカット メニューです。 - - - - References that a non-existent ToolBarButton has been received. - 存在しない ToolBarButton を受け取ったことを示します。 - - - - Controls whether the button should be displayed as partially pushed or not, but only if the style of the button is ToggleButton. - ボタンの種類が ToggleButton の場合のみ、ボタンが部分的にクリックされたとして表示するかどうかを制御します。 - - - - Indicates whether the button is pushed or not. This is most commonly seen for buttons with the TOGGLEBUTTON style. - ボタンをクリックしたかどうかを示します。TOGGLEBUTTON スタイルのボタンによく使われます。 - - - - The size of the buttons on the control if the button contents do not require a larger size. - ボタンの内容により大きなサイズが必要でない場合の、コントロール上のボタンのサイズです。 - - - - Indicates what style of ToolBarButton this will be. - ToolBarButton のスタイルを示します。 - - - - The caption to be displayed for this button. - このボタンに表示されるキャプションです。 - - - - The ToolTip text to be displayed for this button. - このボタンに表示されるツールヒント テキストです。 - - - - Indicates whether this button should be visible. - このボタンを表示するかどうかを示します。 - - - - The collection of ToolBarButtons that make up this ToolBar. - このツール バーを構成する ToolBarButtons のコレクションです。 - - - - Controls whether the ToolBar will display a 3-D line at the top of its client area. - ツール バーがこのクライアント領域の上に 3D の線を表示するかどうかを設定します。 - - - - Controls whether the ToolBar will display an arrow on the side of drop-down buttons. - ツール バーがドロップダウン ボタンの横に矢印を表示するかどうかを制御します。 - - - - The ImageList from which this ToolBar will get all of the button images. - ツール バーがすべてボタンのイメージを取得する ImageList です。 - - - - The size of the images within the ToolBar's ImageList. - ツール バーの ImageList 内にある、イメージのサイズです。 - - - - Indicates whether ToolTips will be shown for each of the buttons, if available. - ツールヒントがある場合に、それぞれのボタンでそれを表示するかどうかを示します。 - - - - Controls how the text is positioned relative to the Image in each button. - 各ボタンのイメージに対して、テキストがどのように表示されるか制御します。 - - - - Indicates if more than one row of buttons is allowed. - 複数行のボタンを許可するかどうかを示します。 - - AllowItemReorder and AllowDrop cannot both be true. AllowItemReorder と AllowDrop の両方を true にすることはできません。 diff --git a/src/System.Windows.Forms/src/Resources/xlf/SR.ko.xlf b/src/System.Windows.Forms/src/Resources/xlf/SR.ko.xlf index d35c34c5a4a..09e16f122d0 100644 --- a/src/System.Windows.Forms/src/Resources/xlf/SR.ko.xlf +++ b/src/System.Windows.Forms/src/Resources/xlf/SR.ko.xlf @@ -1217,34 +1217,9 @@ 이 컨테이너 컨트롤의 부모 폼입니다. - - Raised when the context menu collapses. - 상황에 맞는 메뉴가 축소될 때 발생합니다. - - - - Gets or sets the ImageList associated with this context menu. - 이 상황에 맞는 메뉴에 연결된 ImageList를 가져오거나 설정합니다. - - - - ContextMenu cannot be shown on an invisible control. - 보이지 않는 컨트롤에 ContextMenu를 표시할 수 없습니다. - - - - Gets or sets a value indicating whether the menu has an image margin. - 메뉴에 이미지 여백이 있는지 여부를 나타내는 값을 가져오거나 설정합니다. - - - - The last control that caused this context menu to be displayed. - 상황에 맞는 메뉴를 표시한 마지막 컨트롤입니다. - - The last control that caused this context menu strip to be displayed. - 상황에 맞는 메뉴 스트립을 표시한 마지막 컨트롤입니다. + The last control that caused this context menu strip to be displayed. @@ -2107,466 +2082,6 @@ RemoveAt은 속성에 대하여 속성 바인딩을 지원하지 않습니다. - - Indicates whether the grid can be re-sorted by clicking a column header. - 열 머리글을 클릭하여 표를 다시 정렬할 수 있는지 여부를 나타냅니다. - - - - Indicates the background color of alternating rows for a ledger appearance. - 장부 형식의 화면 표시에서 교대로 반복되는 행의 배경색을 나타냅니다. - - - - Occurs when the user clicks the Back button on a child table to return to the parent table. - 부모 테이블로 돌아가기 위해 자식 테이블에서 [뒤로] 단추를 클릭할 때 발생합니다. - - - - Indicates the color of the DataGrid background. - DataGrid 배경색을 나타냅니다. - - - - BeginInit() has already been called without an EndInit(). - EndInit() 없이 BeginInit()가 이미 호출되었습니다. - - - - Specifies whether the DataGridBoolColumn allows null values. - DataGridBoolColumn에 null 값이 허용되는지 여부를 지정합니다. - - - - Indicates the border style for the DataGrid. - DataGrid의 테두리 스타일을 나타냅니다. - - - - Navigates back to the parent rows. - 부모 행으로 다시 탐색합니다. - - - - Indicates the background color of the top caption. - 위쪽 캡션의 배경색을 나타냅니다. - - - - Shows/Hides the parent rows for the current set of child rows. - 현재 자식 행 집합에 대한 부모 행을 숨기거나 표시합니다. - - - - Indicates the font of the top caption. - 위쪽 캡션의 글꼴을 나타냅니다. - - - - Indicates the color of text that appears in the top caption. - 위쪽 캡션에 나타나는 텍스트 색을 나타냅니다. - - - - Indicates the text displayed in the top caption. - 위쪽 캡션에 표시되는 텍스트를 나타냅니다. - - - - Indicates whether the top caption is visible. - 위쪽 캡션의 표시 여부를 나타냅니다. - - - - DataGridColumn instance does not exist in the collection. - 컬렉션에 DataGridColumn 인스턴스가 없습니다. - - - - Indicates whether the column headers are visible. - 열 머리글 표시 여부를 나타냅니다. - - - - Position of ListManager must be equal to 'rowNum'. - ListManager 위치는 'rowNum'과 같아야 합니다. - - - - PropertyDescriptor has not been set on this DataGridColumn. - 이 DataGridColumn에 PropertyDescriptor가 설정되어 있지 않습니다. - - - - Data grid column styles collection already contains a column style with the same mapping name. - 데이터 표 열 스타일 컬렉션에 매핑 이름이 같은 열 스타일이 이미 있습니다. - - - - DataGridColumnStyle of '{0}' cannot be used because it is not associated with a Property or Column in the DataSource. - '{0}'의 DataGridColumnStyle은 DataSource의 속성 또는 열과 연결되어 있지 않으므로 사용할 수 없습니다. - - - - ColumnWidth must be greater than or equal to 0. - ColumnWidth는 0보다 크거나 같아야 합니다. - - - - The currently selected cell in the DataGrid. - DataGrid에서 현재 선택한 셀입니다. - - - - Indicates a sub-list of the DataSource to show in the DataGrid. - DataGrid에 표시할 DataSource의 하위 목록을 나타냅니다. - - - - Indicates the source of data for the DataGrid. - DataGrid의 데이터 소스를 나타냅니다. - - - - User cannot change the contents of the default GridColumnStylesCollection. - 사용자는 기본 GridColumnStylesCollection의 내용을 변경할 수 없습니다. - - - - Value of this property cannot be changed on the default DataGridTableStyle. - 기본 DataGridTableStyle에서 이 속성의 값을 변경할 수 없습니다. - - - - Occurs when the user clicks the "show/hide parent rows" icon. - "부모 행 표시/숨기기" 아이콘을 클릭할 때 발생합니다. - - - - Value '{0}' cannot be set to an empty value. - '{0}' 값을 빈 값으로 설정할 수 없습니다. - - - - Committing the row to the original data store has caused an error. - 행을 원래 데이터 저장소에 커밋해서 오류가 발생했습니다. - - - - DataGrid received an exception at design time. Reset the DataSource and DataMember property on the grid. - 디자인 타임에 DataGrid에 예외가 발생했습니다. DataSource 및 DataMember 속성을 다시 설정하십시오. - - - - Program cannot get information about the painting and scrolling region. - 프로그램에서 그리기 및 스크롤 영역에 대한 정보를 가져올 수 없습니다. - - - - Indicates the index of the column that is first shown. - 처음 표시되는 열의 인덱스를 나타냅니다. - - - - Indicates whether the grid has a flat appearance. - 표가 평면 모양인지 여부를 나타냅니다. - - - - Indicates the color of the grid lines. - 모눈선의 색을 나타냅니다. - - - - Indicates the style of the grid lines. - 모눈선 스타일을 나타냅니다. - - - - The collection of DataGridTableStyle objects that the DataGrid can render its data with. - DataGrid가 데이터를 렌더링할 때 사용할 수 있는 DataGridTableStyle 개체의 컬렉션입니다. - - - - Indicates the background color of the column and row headers. - 열 및 행 머리글의 배경색을 나타냅니다. - - - - Indicates the font of the text in the column and row headers. - 열 및 행 머리글의 텍스트 글꼴을 나타냅니다. - - - - Indicates the color of the text in the column and row headers. - 열 및 행 머리글의 텍스트 색을 나타냅니다. - - - - Returns the horizontal scroll bar used by the grid. - 표에서 사용하는 가로 스크롤 막대를 반환합니다. - - - - Indicates the color of the text that appears inside the child links. - 자식 링크 내에 나타나는 텍스트 색을 나타냅니다. - - - - Indicates the color of the text that appears inside a child link when the mouse pointer moves over it. - 마우스 포인터가 자식 링크 위로 이동할 때 자식 링크 내부에 표시되는 텍스트의 색을 나타냅니다. - - - - The CurrencyManager that the DataGrid uses to get data from the data source. - 데이터 소스에서 데이터를 가져오기 위해 DataGrid에서 사용하는 CurrencyManager입니다. - - - - Occurs when the user navigates to the child rows or when the user navigates back to the parent rows. - 사용자가 자식 행을 탐색하거나 다시 부모 행을 탐색할 때 발생합니다. - - - - Indicates whether links to child tables are shown. - 자식 테이블에 대한 링크를 표시할지 여부를 나타냅니다. - - - - Occurs when the user clicks on the expansion glyph on the row header. - 사용자가 행 머리글의 확장 문자를 클릭할 때 발생합니다. - - - - (null) - (null) - - - - Event raised when the value of the BackgroundColor property is changed on DataGrid. - DataGrid에서 BackgroundColor 속성 값이 변경될 때 발생하는 이벤트입니다. - - - - Event raised when the value of the BorderStyle property is changed on DataGrid. - BorderStyle 속성 값이 DataGrid에서 변경되면 이벤트가 발생합니다. - - - - Event raised when the value of the CaptionVisible property is changed on DataGrid. - CaptionVisible 속성 값이 DataGrid에서 변경되면 이벤트가 발생합니다. - - - - Event raised when the value of the CurrentCell property is changed on DataGrid. - CurrentCell 속성 값이 DataGrid에서 변경되면 이벤트가 발생합니다. - - - - Event raised when the value of the DataSource property is changed on DataGrid. - DataSource 속성 값이 DataGrid에서 변경되면 이벤트가 발생합니다. - - - - Event raised when the value of the FlatMode property is changed on DataGrid. - FlatMode 속성 값이 DataGrid에서 변경되면 이벤트가 발생합니다. - - - - Event raised when the value of the NavigationMode property is changed on DataGrid. - NavigationMode 속성 값이 DataGrid에서 변경되면 이벤트가 발생합니다. - - - - Event raised when the value of the ParentRowsLabelStyle property is changed on DataGrid. - ParentRowsLabelStyle 속성 값이 DataGrid에서 변경되면 이벤트가 발생합니다. - - - - Event raised when the value of the ParentRowsVisible property is changed on DataGrid. - ParentRowsVisible 속성 값이 DataGrid에서 변경되면 이벤트가 발생합니다. - - - - Event raised when the value of the ReadOnly property is changed on DataGrid. - ReadOnly 속성 값이 DataGrid에서 변경되면 이벤트가 발생합니다. - - - - Indicates the background color of the parent rows. - 부모 행의 배경색을 나타냅니다. - - - - Indicates the color of the text in the parent rows. - 부모 행의 텍스트 색을 나타냅니다. - - - - Indicates whether the parent rows show labels for the table and for the columns. - 부모 행에 테이블 및 열 레이블을 표시할지 여부를 나타냅니다. - - - - Indicates whether the parent rows area is visible. - 부모 행 영역의 표시 여부를 나타냅니다. - - - - Specifies what the default pixel widths of the grid columns are. The default value for PreferredColumnWidth is 75. - 표 형태 창 열의 기본 픽셀 너비를 지정합니다. PreferredColumnWidth의 기본값은 75입니다. - - - - Indicates the preferred height of the rows. - 행의 기본 설정 높이를 나타냅니다. - - - - Value {0} Do you want to correct this value? - 값 {0} 이 값을 수정하시겠습니까? - - - - Indicates whether rows in the grid can be edited, added, or deleted. - 표의 행을 편집, 추가 또는 삭제할 수 있는지 여부를 나타냅니다. - - - - Indicates the width of the row headers. - 행 머리글 너비를 나타냅니다. - - - - Indicates whether the row headers are visible. - 행 머리글 표시 여부를 나타냅니다. - - - - DataGridRow.Height cannot be negative. - DataGridRow.Height는 음수일 수 없습니다. - - - - DataGridRow cannot have a negative row number. - DataGridRow의 행 번호는 음수일 수 없습니다. - - - - Occurs when the user scrolls either the horizontal or vertical scroll bar. - 사용자가 가로 또는 세로 스크롤 막대를 스크롤할 때 발생합니다. - - - - Indicates the index of the current row. - 현재 행의 인덱스를 나타냅니다. - - - - Indicates the background color of any selected cells or rows. - 선택한 셀 또는 행의 배경색을 나타냅니다. - - - - Indicates the color of the text in any selected cells or rows. - 선택한 셀 또는 행의 텍스트 색을 나타냅니다. - - - - ListManager can be set using the DataSource and DataMember properties. - DataSource 및 DataMember 속성을 사용하여 ListManager를 설정할 수 있습니다. - - - - Position on a null ListManager cannot be set. - null ListManager에서의 위치를 설정할 수 없습니다. - - - - CurrentCell cannot be set at this time. Moving your code to the Form.Load event should solve this problem. - 지금 CurrentCell을 설정할 수 없습니다. 코드를 Form.Load 이벤트로 옮기십시오. - - - - DataGridTable instance does not exist in the collection. - 컬렉션에 DataGridTable 인스턴스가 없습니다. - - - - DataGridTableStyle that is already parented to another DataGrid cannot be added. - 이미 다른 DataGrid의 부모인 DataGridTableStyle을 추가할 수 없습니다. - - - - Data grid table styles collection already contains a table style with the same mapping name. - 데이터 표 테이블 스타일 컬렉션에 매핑 이름이 같은 테이블 스타일이 이미 있습니다. - - - - DataGridTableStyle does not support transparent AlternatingBackColor. - DataGridTableStyle은 투명 AlternatingBackColor를 지원하지 않습니다. - - - - DataGridTableStyle does not support transparent BackColor. - DataGridTableStyle은 투명 BackColor를 지원하지 않습니다. - - - - DataGridTableStyle does not support transparent HeaderBackColor. - DataGridTableStyle은 투명 HeaderBackColor를 지원하지 않습니다. - - - - DataGridTableStyle does not support transparent SelectionBackColor. - DataGridTableStyle은 투명 SelectionBackColor를 지원하지 않습니다. - - - - null rectangle for icon bounds when adding tool tip. - 도구 설명을 추가할 때 사용하는 아이콘 범위의 null 사각형입니다. - - - - DataGrid control does not support transparent AlternatingBackColor. - DataGrid 컨트롤은 투명 AlternatingBackColor를 지원하지 않습니다. - - - - DataGrid control does not support transparent BackColor. - DataGrid 컨트롤은 투명 BackColor를 지원하지 않습니다. - - - - DataGrid control does not support transparent CaptionBackColor. - DataGrid 컨트롤은 투명 CaptionBackColor를 지원하지 않습니다. - - - - DataGrid control does not support transparent HeaderBackColor. - DataGrid 컨트롤은 투명 HeaderBackColor를 지원하지 않습니다. - - - - DataGrid control does not support transparent ParentRowsBackColor. - DataGrid 컨트롤은 투명 ParentRowsBackColor를 지원하지 않습니다. - - - - DataGrid control does not support transparent SelectionBackColor. - DataGrid 컨트롤은 투명 SelectionBackColor를 지원하지 않습니다. - - - - Data cannot be read from a DataGrid which is not bound to a DataTable. - DataTable에 바인딩되지 않은 DataGrid에서 데이터를 읽을 수 없습니다. - - - - Returns the vertical scroll bar used by the grid. - 표에서 사용하는 세로 스크롤 막대를 반환합니다. - - Occurs when the value of the AlternatingRowsDefaultCellStyle property changes. AlternatingRowsDefaultCellStyle 속성 값이 변경될 때 발생합니다. @@ -5657,21 +5172,11 @@ Do you want to replace it? 조정할 수 있는 폼의 최대 크기입니다. - - The main menu of the form. This must be set to a component of type MainMenu. - 폼의 주 메뉴이며, MainMenu 형식의 구성 요소로 설정해야 합니다. - - Specifies the primary MenuStrip for the Form. This property is used for keyboard activation and automatic merging in MDI. 폼의 주 MenuStrip을 지정합니다. 이 속성은 MDI에서 자동 병합 및 키보드 활성화에 사용됩니다. - - The merged menu of this form, which is used when displaying a single merged MDI menu. - 병합된 단일 MDI 메뉴를 표시할 때 사용되는 이 폼의 병합 메뉴입니다. - - Determines whether a form has a minimize box in the upper-right corner of its caption bar. 폼의 캡션 표시줄 오른쪽 위 모퉁이에 최소화 상자를 포함할지 여부를 결정합니다. @@ -7171,26 +6676,6 @@ Stack trace where the illegal operation occurred was: 이 폼의 MdiParent로 지정한 폼이 MdiContainer가 아닙니다. - - Occurs when the main menu collapses. - 주 메뉴가 축소될 때 발생합니다. - - - - Gets or sets the ImageList associated with this main menu. - 이 주 메뉴와 연결된 ImageList를 가져오거나 설정합니다. - - - - Gets or sets a value indicating whether the menu has an image margin. - 메뉴에 이미지 여백이 있는지 여부를 나타내는 값을 가져오거나 설정합니다. - - - - <No Form> - <No Form> - - Indicates whether the prompt character is valid as input. 프롬프트 문자가 입력으로 올바른지 여부를 나타냅니다. @@ -7326,139 +6811,14 @@ Stack trace where the illegal operation occurred was: 컨트롤이 포커스를 잃을 때 입력 텍스트를 구문 분석하는 데 사용할 개체의 형식을 지정합니다. - - Parameter must be of type MenuItem. - 매개 변수는 MenuItem 형식이어야 합니다. - - - - Gets or sets the background color of this menu's image margin. - 이 메뉴의 이미지 여백 배경색을 가져오거나 설정합니다. - - - - Indicates if this menu contains any child items. - 이 메뉴에 자식 항목이 있는지 여부를 나타냅니다. - - - - Cannot add MenuItem '{0}'. It already exists as a parent of the current menu item. - MenuItem '{0}'을(를) 추가할 수 없습니다. 현재 메뉴 항목의 부모로 이미 존재합니다. - - - - Indicates whether the item is checked. - 항목의 선택 상태를 나타냅니다. - - - - Indicates whether the item is the default item. - 해당 항목이 기본 항목인지 여부를 나타냅니다. - - - - Indicates whether the item is enabled. - 항목의 사용 여부를 나타냅니다. - - - - Gets or sets the image to be displayed on this menu item. - 이 메뉴 항목에 표시될 이미지를 가져오거나 설정합니다. - - - - Gets or sets the ImageList associated with this menu item. - 이 메뉴 항목과 연결된 ImageList를 가져오거나 설정합니다. - - - - Gets or sets the background color of this menu item's image margin. - 이 메뉴 항목의 이미지 여백 배경색을 가져오거나 설정합니다. - - - - True is not a valid value for the Checked property. This is only valid for MenuItems that have no children and are not top-level. - True는 Checked 속성에 사용할 수 없습니다. 자식이 없고 최상위가 아닌 MenuItem에만 사용할 수 있습니다. - - - - Determines whether the MDI child window list is appended to this item. - 이 항목에 MDI 자식 창 목록을 추가할지 여부를 결정합니다. - - - - Determines the merge order of the item. - 항목의 병합 순서를 결정합니다. - - - - Determines how the item is handled when menus are merged. - 메뉴를 병합하는 경우 항목을 처리하는 방법을 결정합니다. - - - - Occurs when the menu item is selected. - 메뉴 항목을 선택할 때 발생합니다. - - - - Occurs before the containing menu is displayed. - 포함하는 메뉴가 표시되기 전에 발생합니다. - - - - Occurs when the menu item is selected. - 메뉴 항목을 선택할 때 발생합니다. - - - - Indicates if Windows will draw the menu item or if the user will handle the painting. - Windows에서 메뉴 항목을 그릴지 또는 사용자가 그리기를 처리할지 나타냅니다. - - - - If the item is checked, this value will determine whether the check style is a radio button. - 항목이 선택되는 경우 이 값은 선택 스타일이 라디오 단추인지 여부를 결정합니다. - - The shortcut key associated with the menu item. - 메뉴 항목에 연결된 바로 가기 키입니다. + The shortcut key associated with the menu item. Indicates whether the shorcut key for the menu item is displayed on the item. - 메뉴 항목의 바로 가기 키가 항목에 표시되는지 여부를 나타냅니다. - - - - The caption displayed by the item. - 항목에 표시할 캡션입니다. - - - - Indicates whether the item is visible. - 항목의 표시 여부를 나타냅니다. - - - - Retrieves the menu item that contains a list of MDI child windows. - MDI 자식 창 목록을 포함하는 메뉴 항목을 검색합니다. - - - - The menu items for the menu. - 메뉴의 메뉴 항목입니다. - - - - Cannot merge a menu with itself. - 메뉴를 메뉴 자체와 병합할 수 없습니다. - - - - Indicates if this menu should display right to left - 메뉴를 오른쪽에서 왼쪽으로 표시할지 여부를 나타냅니다. + Indicates whether the shorcut key for the menu item is displayed on the item. @@ -9976,136 +9336,6 @@ Stack trace where the illegal operation occurred was: ResumeUpdateMenuHandles에 대한 호출이 너무 많습니다. - - Controls the appearance of the ToolBar control, using values from the ToolBarAppearance enumeration. - ToolBarAppearance 열거형의 값을 사용하여 ToolBar 컨트롤의 모양을 제어합니다. - - - - Controls whether the ToolBar will automatically size itself based on Button size. - 단추 크기에 따라 도구 모음의 크기를 자동으로 조정할지 여부를 제어합니다. - - - - Parameter must be of type ToolBarButton. - 매개 변수는 ToolBarButton 형식이어야 합니다. - - - - Controls what type of border the ToolBar control will have. - ToolBar 컨트롤의 테두리 형식을 제어합니다. - - - - Occurs whenever a button in the ToolBar is clicked by the user. - 사용자가 ToolBar의 단추를 클릭할 때마다 발생합니다. - - - - Occurs whenever a button with the DropDownButton style is pressed. - DropDownButton 스타일의 단추를 누를 때마다 발생합니다. - - - - Controls whether this button responds to user input. - 이 단추가 사용자 입력에 응답하는지 여부를 제어합니다. - - - - Identifies the image displayed on the button. - 단추에 표시되는 이미지를 식별합니다. - - - - The drop-down menu for a ToolBarButton must be of type ContextMenu. - ToolBarButton의 드롭다운 메뉴는 ContextMenu 형식이어야 합니다. - - - - The shortcut menu that will appear if this button's style is set to DropDownButton. - 이 단추의 스타일을 DropDownButton으로 설정하면 표시되는 바로 가기 메뉴입니다. - - - - References that a non-existent ToolBarButton has been received. - 존재하지 않는 ToolBarButton에 대한 참조를 받았습니다. - - - - Controls whether the button should be displayed as partially pushed or not, but only if the style of the button is ToggleButton. - 단추 스타일이 ToggleButton인 경우에 한하여 단추를 부분적으로 눌린 상태로 표시할지 여부를 제어합니다. - - - - Indicates whether the button is pushed or not. This is most commonly seen for buttons with the TOGGLEBUTTON style. - 단추의 누름 상태를 나타내며, 대개 TOGGLEBUTTON 스타일의 단추에서 볼 수 있습니다. - - - - The size of the buttons on the control if the button contents do not require a larger size. - 단추 크기가 단추 내용에 적합한 경우 컨트롤에 표시될 단추의 크기입니다. - - - - Indicates what style of ToolBarButton this will be. - 구현될 ToolBarButton 스타일을 나타냅니다. - - - - The caption to be displayed for this button. - 이 단추에 표시할 캡션입니다. - - - - The ToolTip text to be displayed for this button. - 이 단추에 표시할 ToolTip 텍스트입니다. - - - - Indicates whether this button should be visible. - 이 단추를 표시할지 여부를 나타냅니다. - - - - The collection of ToolBarButtons that make up this ToolBar. - 이 ToolBar를 구성하는 ToolBarButtons 컬렉션입니다. - - - - Controls whether the ToolBar will display a 3-D line at the top of its client area. - 도구 모음에서 클라이언트 영역의 맨 위에 3D 선을 표시할지 여부를 제어합니다. - - - - Controls whether the ToolBar will display an arrow on the side of drop-down buttons. - 도구 모음에서 드롭다운 단추 옆에 화살표를 표시할지 여부를 제어합니다. - - - - The ImageList from which this ToolBar will get all of the button images. - 이 ToolBar에서 모든 단추 이미지를 가져올 ImageList입니다. - - - - The size of the images within the ToolBar's ImageList. - 도구 모음의 ImageList에 있는 이미지의 크기입니다. - - - - Indicates whether ToolTips will be shown for each of the buttons, if available. - 도구 설명을 사용할 수 있는 경우 각 단추의 도구 설명을 표시할지 여부를 나타냅니다. - - - - Controls how the text is positioned relative to the Image in each button. - 각 단추에서 이미지를 기준으로 하여 텍스트를 배치하는 방법을 제어합니다. - - - - Indicates if more than one row of buttons is allowed. - 두 행 이상의 단추를 사용할 수 있는지 여부를 나타냅니다. - - AllowItemReorder and AllowDrop cannot both be true. AllowItemReorder 및 AllowDrop이 모두 true일 수 없습니다. diff --git a/src/System.Windows.Forms/src/Resources/xlf/SR.pl.xlf b/src/System.Windows.Forms/src/Resources/xlf/SR.pl.xlf index b82077fa54b..0bafbeaf276 100644 --- a/src/System.Windows.Forms/src/Resources/xlf/SR.pl.xlf +++ b/src/System.Windows.Forms/src/Resources/xlf/SR.pl.xlf @@ -1217,34 +1217,9 @@ Formularz nadrzędny tego formantu kontenera. - - Raised when the context menu collapses. - Występuje po zwinięciu menu kontekstowego. - - - - Gets or sets the ImageList associated with this context menu. - Pobiera lub ustawia listę ImageList skojarzoną z tym menu kontekstowym. - - - - ContextMenu cannot be shown on an invisible control. - Nie można pokazać elementu ContextMenu w niewidocznym formancie. - - - - Gets or sets a value indicating whether the menu has an image margin. - Pobiera lub ustawia wartość wskazującą, czy menu ma margines obrazu. - - - - The last control that caused this context menu to be displayed. - Ostatni formant, który spowodował wyświetlenie tego menu kontekstowego. - - The last control that caused this context menu strip to be displayed. - Ostatni formant, który spowodował wyświetlenie tego paska menu kontekstowego. + The last control that caused this context menu strip to be displayed. @@ -2107,466 +2082,6 @@ Element RemoveAt nie jest obsługiwany dla powiązań właściwości z właściwością - - Indicates whether the grid can be re-sorted by clicking a column header. - Wskazuje, czy można ponownie posortować siatkę, klikając nagłówek kolumny. - - - - Indicates the background color of alternating rows for a ledger appearance. - Określa kolor tła przemiennych wierszy nadających wygląd księgi rachunkowej. - - - - Occurs when the user clicks the Back button on a child table to return to the parent table. - Występuje, gdy użytkownik kliknie przycisk Wstecz w tabeli podrzędnej w celu powrotu do tabeli nadrzędnej. - - - - Indicates the color of the DataGrid background. - Określa kolor tła elementu DataGrid. - - - - BeginInit() has already been called without an EndInit(). - Wywołano już element BeginInit() bez elementu EndInit(). - - - - Specifies whether the DataGridBoolColumn allows null values. - Określa, czy element DataGridBoolColumn dopuszcza wartości zerowe. - - - - Indicates the border style for the DataGrid. - Określa styl obramowania elementu DataGrid. - - - - Navigates back to the parent rows. - Nawiguje wstecz do wierszy nadrzędnych. - - - - Indicates the background color of the top caption. - Określa kolor tła górnego podpisu. - - - - Shows/Hides the parent rows for the current set of child rows. - Pokazuje/ukrywa wiersze nadrzędne danego zestawu wierszy podrzędnych. - - - - Indicates the font of the top caption. - Określa czcionkę górnego podpisu. - - - - Indicates the color of text that appears in the top caption. - Określa kolor tekstu pojawiającego się w górnym podpisie. - - - - Indicates the text displayed in the top caption. - Określa tekst wyświetlany w górnym podpisie. - - - - Indicates whether the top caption is visible. - Wskazuje, czy górny obszar jest widoczny. - - - - DataGridColumn instance does not exist in the collection. - Wystąpienie DataGridColumn nie istnieje w tej kolekcji. - - - - Indicates whether the column headers are visible. - Wskazuje, czy nagłówki kolumn są widoczne. - - - - Position of ListManager must be equal to 'rowNum'. - Pozycja elementu ListManager musi być równa wartości rowNum. - - - - PropertyDescriptor has not been set on this DataGridColumn. - Dla tego elementu DataGridColumn nie skonfigurowano elementu PropertyDescriptor. - - - - Data grid column styles collection already contains a column style with the same mapping name. - Kolekcja styli kolumn siatki danych już zawiera styl kolumny o tej samej nazwie mapowania. - - - - DataGridColumnStyle of '{0}' cannot be used because it is not associated with a Property or Column in the DataSource. - Nie można użyć elementu DataGridColumnStyle '{0}', ponieważ nie jest on skojarzony z żadną właściwością ani kolumną elementu DataSource. - - - - ColumnWidth must be greater than or equal to 0. - Wartość ColumnWidth musi być większa lub równa 0. - - - - The currently selected cell in the DataGrid. - Aktualnie zaznaczona komórka w elemencie DataGrid. - - - - Indicates a sub-list of the DataSource to show in the DataGrid. - Określa listę podrzędną elementu DataSource, która ma być wyświetlana w elemencie DataGrid. - - - - Indicates the source of data for the DataGrid. - Określa źródło danych dla elementu DataGrid. - - - - User cannot change the contents of the default GridColumnStylesCollection. - Użytkownik nie może zmienić zawartości domyślnej kolekcji GridColumnStylesCollection. - - - - Value of this property cannot be changed on the default DataGridTableStyle. - Wartości tej właściwości nie można zmienić w domyślnym parametrze DataGridTableStyle. - - - - Occurs when the user clicks the "show/hide parent rows" icon. - Występuje po kliknięciu przez użytkownika ikony „show/hide parent rows”. - - - - Value '{0}' cannot be set to an empty value. - Wartości „{0}” nie można ustawić tak, aby była pusta. - - - - Committing the row to the original data store has caused an error. - Błąd podczas przekazywania wiersza do oryginalnego magazynu danych. - - - - DataGrid received an exception at design time. Reset the DataSource and DataMember property on the grid. - Element DataGrid odebrał wyjątek w czasie projektowania. Zresetuj właściwości DataSource i DataMember na siatce. - - - - Program cannot get information about the painting and scrolling region. - Program nie może pobrać informacji o regionie rysowania i przewijania. - - - - Indicates the index of the column that is first shown. - Określa indeks kolumny wyświetlanej jako pierwsza. - - - - Indicates whether the grid has a flat appearance. - Wskazuje, czy siatka ma wygląd płaski. - - - - Indicates the color of the grid lines. - Określa kolor linii siatki. - - - - Indicates the style of the grid lines. - Określa styl linii siatki. - - - - The collection of DataGridTableStyle objects that the DataGrid can render its data with. - Kolekcja obiektów DataGridTableStyle, za pomocą których element DataGrid może renderować swoje dane. - - - - Indicates the background color of the column and row headers. - Określa kolor tła nagłówków kolumn i wierszy. - - - - Indicates the font of the text in the column and row headers. - Określa czcionkę w nagłówkach kolumn i wierszy. - - - - Indicates the color of the text in the column and row headers. - Określa kolor tekstu w nagłówkach kolumn i wierszy. - - - - Returns the horizontal scroll bar used by the grid. - Przywraca poziomy pasek przewijania używany przez siatkę. - - - - Indicates the color of the text that appears inside the child links. - Określa kolor tekstu pojawiającego się w łączach podrzędnych. - - - - Indicates the color of the text that appears inside a child link when the mouse pointer moves over it. - Wskazuje kolor tekstu wyświetlanego w łączu podrzędnym, gdy przesuwany jest nad nim wskaźnik myszy. - - - - The CurrencyManager that the DataGrid uses to get data from the data source. - Element CurrencyManager używany przez element DataGrid do pobierania danych ze źródła danych. - - - - Occurs when the user navigates to the child rows or when the user navigates back to the parent rows. - Występuje, gdy użytkownik nawiguje do wierszy podrzędnych lub gdy użytkownik nawiguje wstecz do wierszy nadrzędnych. - - - - Indicates whether links to child tables are shown. - Wskazuje, czy łącza są widoczne dla tabel podrzędnych. - - - - Occurs when the user clicks on the expansion glyph on the row header. - Występuje, gdy użytkownik kliknie ikonę rozwijania w nagłówku wiersza. - - - - (null) - (null) - - - - Event raised when the value of the BackgroundColor property is changed on DataGrid. - Zdarzenie wywoływane, gdy wartość właściwości BackgroundColor w elemencie DataGrid zostanie zmieniona. - - - - Event raised when the value of the BorderStyle property is changed on DataGrid. - Zdarzenie wywoływane, gdy wartość właściwości BorderStyle w elemencie DataGrid zostanie zmieniona. - - - - Event raised when the value of the CaptionVisible property is changed on DataGrid. - Zdarzenie wywoływane, gdy wartość właściwości CaptionVisible w elemencie DataGrid zostanie zmieniona. - - - - Event raised when the value of the CurrentCell property is changed on DataGrid. - Zdarzenie wywoływane, gdy wartość właściwości CurrentCell w elemencie DataGrid zostanie zmieniona. - - - - Event raised when the value of the DataSource property is changed on DataGrid. - Zdarzenie wywoływane, gdy wartość właściwości DataSource w elemencie DataGrid zostanie zmieniona. - - - - Event raised when the value of the FlatMode property is changed on DataGrid. - Zdarzenie wywoływane, gdy wartość właściwości FlatMode w elemencie DataGrid zostanie zmieniona. - - - - Event raised when the value of the NavigationMode property is changed on DataGrid. - Zdarzenie wywoływane, gdy wartość właściwości NavigationMode w elemencie DataGrid zostanie zmieniona. - - - - Event raised when the value of the ParentRowsLabelStyle property is changed on DataGrid. - Zdarzenie wywoływane, gdy wartość właściwości ParentRowsLabelStyle w elemencie DataGrid zostanie zmieniona. - - - - Event raised when the value of the ParentRowsVisible property is changed on DataGrid. - Zdarzenie wywoływane, gdy wartość właściwości ParentRowsVisible w elemencie DataGrid zostanie zmieniona. - - - - Event raised when the value of the ReadOnly property is changed on DataGrid. - Zdarzenie wywoływane, gdy wartość właściwości ReadOnly w elemencie DataGrid zostanie zmieniona. - - - - Indicates the background color of the parent rows. - Wskazuje kolor tła wierszy nadrzędnych. - - - - Indicates the color of the text in the parent rows. - Wskazuje kolor tekstu w wierszach nadrzędnych. - - - - Indicates whether the parent rows show labels for the table and for the columns. - Wskazuje, czy wiersze nadrzędne pokazują etykiety dla tabeli i dla kolumn. - - - - Indicates whether the parent rows area is visible. - Wskazuje, czy obszar wierszy nadrzędnych jest widoczny. - - - - Specifies what the default pixel widths of the grid columns are. The default value for PreferredColumnWidth is 75. - Określa domyślną szerokość kolumn siatki w pikselach. Wartością domyślną elementu PreferredColumnWidth jest 75. - - - - Indicates the preferred height of the rows. - Wskazuje preferowaną wysokość wierszy. - - - - Value {0} Do you want to correct this value? - Wartość {0} Czy chcesz poprawić tę wartość? - - - - Indicates whether rows in the grid can be edited, added, or deleted. - Wskazuje, czy wiersze siatki mogą być edytowane, dodawane lub usuwane. - - - - Indicates the width of the row headers. - Określa szerokość nagłówków wierszy. - - - - Indicates whether the row headers are visible. - Wskazuje, czy nagłówki wierszy są widoczne. - - - - DataGridRow.Height cannot be negative. - Wartość elementu DataGridRow.Height nie może być ujemna. - - - - DataGridRow cannot have a negative row number. - Element DataGridRow nie może mieć ujemnej liczby wierszy. - - - - Occurs when the user scrolls either the horizontal or vertical scroll bar. - Występuje, gdy użytkownik przewija poziomy lub pionowy pasek przewijania. - - - - Indicates the index of the current row. - Wskazuje indeks bieżącego wiersza. - - - - Indicates the background color of any selected cells or rows. - Określa kolor tła zaznaczonych komórek lub wierszy. - - - - Indicates the color of the text in any selected cells or rows. - Określa kolor tekstu w zaznaczonych komórkach lub wierszach. - - - - ListManager can be set using the DataSource and DataMember properties. - Element ListManager można skonfigurować przy użyciu właściwości DataSource i DataMember. - - - - Position on a null ListManager cannot be set. - Nie można ustawić pozycji w zerowym obiekcie ListManager. - - - - CurrentCell cannot be set at this time. Moving your code to the Form.Load event should solve this problem. - Nie można teraz skonfigurować elementu CurrentCell. Aby rozwiązać ten problem, przenieś kod do elementu Form.Load. - - - - DataGridTable instance does not exist in the collection. - Wystąpienie elementu DataGridTable nie istnieje w kolekcji. - - - - DataGridTableStyle that is already parented to another DataGrid cannot be added. - Nie można dodać elementu DataGridTableStyle, który już jest nadrzędny w stosunku do innego obiektu DataGrid. - - - - Data grid table styles collection already contains a table style with the same mapping name. - Kolekcja stylów tabeli siatki danych zawiera już styl tabeli o tej samej nazwie mapowania. - - - - DataGridTableStyle does not support transparent AlternatingBackColor. - Element DataGridTableStyle nie obsługuje przezroczystego elementu AlternatingBackColor. - - - - DataGridTableStyle does not support transparent BackColor. - Element DataGridTableStyle nie obsługuje przezroczystego elementu BackColor. - - - - DataGridTableStyle does not support transparent HeaderBackColor. - Element DataGridTableStyle nie obsługuje przezroczystego elementu HeaderBackColor. - - - - DataGridTableStyle does not support transparent SelectionBackColor. - Element DataGridTableStyle nie obsługuje przezroczystego elementu SelectionBackColor. - - - - null rectangle for icon bounds when adding tool tip. - zerowy prostokąt obramowania ikony podczas dodawania etykiety. - - - - DataGrid control does not support transparent AlternatingBackColor. - Formant DataGrid nie obsługuje przezroczystego elementu AlternatingBackColor. - - - - DataGrid control does not support transparent BackColor. - Formant DataGrid nie obsługuje przezroczystego elementu BackColor. - - - - DataGrid control does not support transparent CaptionBackColor. - Formant DataGrid nie obsługuje przezroczystego elementu CaptionBackColor. - - - - DataGrid control does not support transparent HeaderBackColor. - Formant DataGrid nie obsługuje przezroczystego elementu HeaderBackColor. - - - - DataGrid control does not support transparent ParentRowsBackColor. - Formant DataGrid nie obsługuje przezroczystego elementu ParentRowsBackColor. - - - - DataGrid control does not support transparent SelectionBackColor. - Formant DataGrid nie obsługuje przezroczystego elementu SelectionBackColor. - - - - Data cannot be read from a DataGrid which is not bound to a DataTable. - Nie można odczytać danych z elementu DataGrid nie związanego z elementem DataTable. - - - - Returns the vertical scroll bar used by the grid. - Zwraca pionowy pasek przewijania używany w siatce. - - Occurs when the value of the AlternatingRowsDefaultCellStyle property changes. Występuje, gdy wartość właściwości AlternatingRowsDefaultCellStyle zostanie zmieniona. @@ -5657,21 +5172,11 @@ Czy chcesz go zamienić? Maksymalny rozmiar, do jakiego może być powiększony formularz. - - The main menu of the form. This must be set to a component of type MainMenu. - Menu główne formularza. Musi być ustawione na składnik typu MainMenu. - - Specifies the primary MenuStrip for the Form. This property is used for keyboard activation and automatic merging in MDI. Określa podstawowy element MenuStrip dla elementu Form. Ta właściwość jest używana do aktywacji klawiatury i automatycznego scalania w interfejsie MDI. - - The merged menu of this form, which is used when displaying a single merged MDI menu. - Menu scalone formularza służące do wyświetlania pojedynczego scalonego menu MDI. - - Determines whether a form has a minimize box in the upper-right corner of its caption bar. Określa, czy w prawym górnym rogu paska podpisu formularza znajduje się pole minimalizacji. @@ -7171,26 +6676,6 @@ Stos śledzenia, w którym wystąpiła zabroniona operacja: Formularz, który został określony jako MdiParent dla tego formularza, nie jest elementem MdiContainer. - - Occurs when the main menu collapses. - Występuje, gdy menu główne zostanie zwinięte. - - - - Gets or sets the ImageList associated with this main menu. - Pobiera lub ustawia element ImageList skojarzony z tym menu głównym. - - - - Gets or sets a value indicating whether the menu has an image margin. - Pobiera lub ustawia wartość wskazującą, czy menu ma margines obrazu. - - - - <No Form> - <No Form> - - Indicates whether the prompt character is valid as input. Wskazuje, czy znak monitu jest prawidłowym wprowadzanym znakiem. @@ -7326,139 +6811,14 @@ Stos śledzenia, w którym wystąpiła zabroniona operacja: Określa typ obiektu używanego do analizowania tekstu wejściowego, gdy formant utraci fokus. - - Parameter must be of type MenuItem. - Parametr musi być typu MenuItem. - - - - Gets or sets the background color of this menu's image margin. - Pobiera lub ustawia kolor tła marginesu obrazu tego menu. - - - - Indicates if this menu contains any child items. - Wskazuje, czy menu zawiera pozycje podrzędne. - - - - Cannot add MenuItem '{0}'. It already exists as a parent of the current menu item. - Nie można dodać elementu MenuItem '{0}', gdyż istnieje on już jako element nadrzędny dla bieżącego elementu menu. - - - - Indicates whether the item is checked. - Wskazuje, czy element został zaznaczony. - - - - Indicates whether the item is the default item. - Wskazuje, czy element jest elementem domyślnym. - - - - Indicates whether the item is enabled. - Wskazuje, czy element jest włączony. - - - - Gets or sets the image to be displayed on this menu item. - Pobiera lub ustawia obraz do wyświetlania w tym elemencie menu. - - - - Gets or sets the ImageList associated with this menu item. - Pobiera lub ustawia listę ImageList skojarzoną z tym elementem menu. - - - - Gets or sets the background color of this menu item's image margin. - Pobiera lub ustawia kolor tła dla marginesu obrazu tego menu. - - - - True is not a valid value for the Checked property. This is only valid for MenuItems that have no children and are not top-level. - Wartość True (prawda) nie jest prawidłową wartością właściwości Checked. Wartość True jest prawidłową wartością tylko dla elementów MenuItems, które nie mają elementów podrzędnych i nie są na najwyższym poziomie. - - - - Determines whether the MDI child window list is appended to this item. - Określa, czy lista okien elementów podrzędnych MDI jest dołączona do tego elementu. - - - - Determines the merge order of the item. - Określa kolejność scalania elementów. - - - - Determines how the item is handled when menus are merged. - Określa sposób obsługi elementu podczas scalania menu. - - - - Occurs when the menu item is selected. - Występuje, gdy zostanie zaznaczony element menu. - - - - Occurs before the containing menu is displayed. - Występuje przed wyświetleniem menu zawierającego ten element. - - - - Occurs when the menu item is selected. - Występuje, gdy zostanie zaznaczony element menu. - - - - Indicates if Windows will draw the menu item or if the user will handle the painting. - Wskazuje, czy system Windows narysuje pozycję menu, czy użytkownik wykona rysowanie. - - - - If the item is checked, this value will determine whether the check style is a radio button. - Jeżeli element jest zaznaczony, ta wartość określa, czy stylem zaznaczenia jest przycisk radiowy. - - The shortcut key associated with the menu item. - Klawisz skrótu skojarzony z elementem menu. + The shortcut key associated with the menu item. Indicates whether the shorcut key for the menu item is displayed on the item. - Wskazuje, czy skrót do elementu menu będzie wyświetlany. - - - - The caption displayed by the item. - Podpis wyświetlany przez element. - - - - Indicates whether the item is visible. - Wskazuje, czy element jest widoczny. - - - - Retrieves the menu item that contains a list of MDI child windows. - Pobiera element menu zawierający listę okien podrzędnych MDI. - - - - The menu items for the menu. - Elementy menu dla menu. - - - - Cannot merge a menu with itself. - Nie można scalić menu z nim samym. - - - - Indicates if this menu should display right to left - Wskazuje, czy menu powinno być wyświetlane od prawej do lewej + Indicates whether the shorcut key for the menu item is displayed on the item. @@ -9976,136 +9336,6 @@ Stos śledzenia, w którym wystąpiła zabroniona operacja: Zbyt wiele odwołań do elementu ResumeUpdateMenuHandles. - - Controls the appearance of the ToolBar control, using values from the ToolBarAppearance enumeration. - Steruje wyglądem formantu ToolBar przy użyciu wartości z wyliczenia ToolBarAppearance. - - - - Controls whether the ToolBar will automatically size itself based on Button size. - Określa, czy rozmiar formantu ToolBar będzie zmieniał się automatycznie na podstawie rozmiaru elementu Button. - - - - Parameter must be of type ToolBarButton. - Parametr musi być typu ToolBarButton. - - - - Controls what type of border the ToolBar control will have. - Określa typ obramowania formantu ToolBar. - - - - Occurs whenever a button in the ToolBar is clicked by the user. - Występuje za każdym razem, gdy użytkownik kliknie przycisk w formancie ToolBar. - - - - Occurs whenever a button with the DropDownButton style is pressed. - Występuje zawsze, gdy zostanie naciśnięty przycisk o stylu DropDownButton. - - - - Controls whether this button responds to user input. - Określa, czy przycisk odpowiada na działania użytkownika. - - - - Identifies the image displayed on the button. - Identyfikuje obraz wyświetlany na przycisku. - - - - The drop-down menu for a ToolBarButton must be of type ContextMenu. - Menu rozwijane elementu ToolBarButton musi być typu ContextMenu. - - - - The shortcut menu that will appear if this button's style is set to DropDownButton. - Menu kontekstowe pojawiające się, jeśli styl przycisku jest ustawiony na DropDownButton. - - - - References that a non-existent ToolBarButton has been received. - Odebrano odwołania do nieistniejącego elementu ToolBarButton. - - - - Controls whether the button should be displayed as partially pushed or not, but only if the style of the button is ToggleButton. - Określa, czy przycisk powinien być wyświetlany jako częściowo naciśnięty, czy nie, ale tylko wtedy, gdy stylem przycisku jest ToggleButton. - - - - Indicates whether the button is pushed or not. This is most commonly seen for buttons with the TOGGLEBUTTON style. - Wskazuje, czy przycisk jest naciśnięty, czy nie. Najczęściej występuje w przyciskach ze stylem TOGGLEBUTTON. - - - - The size of the buttons on the control if the button contents do not require a larger size. - Rozmiar przycisków w formancie, gdy zawartość formantu nie wymaga większego rozmiaru. - - - - Indicates what style of ToolBarButton this will be. - Wskazuje styl elementu ToolBarButton. - - - - The caption to be displayed for this button. - Podpis wyświetlany dla przycisku. - - - - The ToolTip text to be displayed for this button. - Tekst elementu ToolTip wyświetlany na tym przycisku. - - - - Indicates whether this button should be visible. - Wskazuje, czy przycisk powinien być widoczny. - - - - The collection of ToolBarButtons that make up this ToolBar. - Kolekcja elementów ToolBarButton, które tworzą ten element ToolBar. - - - - Controls whether the ToolBar will display a 3-D line at the top of its client area. - Określa, czy u góry obszaru klienckiego elementu ToolBar ma być wyświetlana linia 3W. - - - - Controls whether the ToolBar will display an arrow on the side of drop-down buttons. - Określa, czy obok przycisków rozwijanych w elemencie ToolBar będą wyświetlane strzałki. - - - - The ImageList from which this ToolBar will get all of the button images. - Element ImageList, z którego element ToolBar pobierze wszystkie obrazy dla przycisków. - - - - The size of the images within the ToolBar's ImageList. - Rozmiary obrazów w elemencie ImageList elementu ToolBar. - - - - Indicates whether ToolTips will be shown for each of the buttons, if available. - Wskazuje, czy elementy ToolTip mają być pokazywane na każdym przycisku, jeśli są dostępne. - - - - Controls how the text is positioned relative to the Image in each button. - Określa, jak rozmieszczany jest tekst względem obrazu na każdym przycisku. - - - - Indicates if more than one row of buttons is allowed. - Wskazuje, czy dopuszczalny jest więcej niż jeden wiersz przycisków. - - AllowItemReorder and AllowDrop cannot both be true. Wartości AllowItemReorder i AllowDrop nie mogą być jednocześnie prawdziwe. diff --git a/src/System.Windows.Forms/src/Resources/xlf/SR.pt-BR.xlf b/src/System.Windows.Forms/src/Resources/xlf/SR.pt-BR.xlf index 450da311f21..7bc5013d9ef 100644 --- a/src/System.Windows.Forms/src/Resources/xlf/SR.pt-BR.xlf +++ b/src/System.Windows.Forms/src/Resources/xlf/SR.pt-BR.xlf @@ -1217,34 +1217,9 @@ O formulário pai deste controle de recipiente. - - Raised when the context menu collapses. - Gerado quando o menu contextual é recolhido. - - - - Gets or sets the ImageList associated with this context menu. - Obtém ou define a ImageList associada ao menu contextual. - - - - ContextMenu cannot be shown on an invisible control. - ContextMenu não pode ser mostrado em um controle invisível. - - - - Gets or sets a value indicating whether the menu has an image margin. - Obtém ou define um valor indicando se o menu tem uma margem de imagem. - - - - The last control that caused this context menu to be displayed. - O último controle que exibiu este menu contextual. - - The last control that caused this context menu strip to be displayed. - O último controle que fez esta faixa de menus contextuais ser exibida. + The last control that caused this context menu strip to be displayed. @@ -2107,466 +2082,6 @@ RemoveAt não oferece suporte para associação de propriedade a propriedade. - - Indicates whether the grid can be re-sorted by clicking a column header. - Indica se a grade pode ser reclassificada ao clicar no cabeçalho de uma coluna. - - - - Indicates the background color of alternating rows for a ledger appearance. - Indica a cor da tela de fundo das linhas alternadas para obter uma aparência de livro razão. - - - - Occurs when the user clicks the Back button on a child table to return to the parent table. - Ocorre quando o usuário clica no botão Voltar em uma tabela filho para retornar à tabela pai. - - - - Indicates the color of the DataGrid background. - Indica a cor da tela de fundo de DataGrid. - - - - BeginInit() has already been called without an EndInit(). - BeginInit() já foi chamado sem EndInit(). - - - - Specifies whether the DataGridBoolColumn allows null values. - Especifica se DataGridBoolColumn permite valores nulos. - - - - Indicates the border style for the DataGrid. - Indica o estilo de borda para DataGrid. - - - - Navigates back to the parent rows. - Navega de volta para as linhas pai. - - - - Indicates the background color of the top caption. - Indica a cor da tela de fundo da legenda superior. - - - - Shows/Hides the parent rows for the current set of child rows. - Mostra/oculta as linhas pai do conjunto atual de linhas filho. - - - - Indicates the font of the top caption. - Indica a fonte da legenda superior. - - - - Indicates the color of text that appears in the top caption. - Indica a cor do texto exibido na legenda superior. - - - - Indicates the text displayed in the top caption. - Indica o texto exibido na legenda superior. - - - - Indicates whether the top caption is visible. - Indica se a legenda superior está visível. - - - - DataGridColumn instance does not exist in the collection. - A instância de DataGridColumn não existe na coleção. - - - - Indicates whether the column headers are visible. - Indica se os cabeçalhos de coluna estão visíveis. - - - - Position of ListManager must be equal to 'rowNum'. - A posição de ListManager deve ser igual a 'rowNum'. - - - - PropertyDescriptor has not been set on this DataGridColumn. - PropertyDescriptor não foi definido nesta DataGridColumn. - - - - Data grid column styles collection already contains a column style with the same mapping name. - A coleção de estilos de coluna de grade de dados já contém um estilo de coluna com o mesmo nome de mapeamento. - - - - DataGridColumnStyle of '{0}' cannot be used because it is not associated with a Property or Column in the DataSource. - DataGridColumnStyle de '{0}' não pode ser usado porque não está associado a uma propriedade ou coluna em DataSource. - - - - ColumnWidth must be greater than or equal to 0. - ColumnWidth deve ser maior ou igual a 0. - - - - The currently selected cell in the DataGrid. - A célula selecionada atualmente em DataGrid. - - - - Indicates a sub-list of the DataSource to show in the DataGrid. - Indica uma sublista de DataSource para mostrar em DataGrid. - - - - Indicates the source of data for the DataGrid. - Indica a fonte de dados para DataGrid. - - - - User cannot change the contents of the default GridColumnStylesCollection. - O usuário não pode alterar o conteúdo da GridColumnStylesCollection padrão. - - - - Value of this property cannot be changed on the default DataGridTableStyle. - Não é possível alterar o valor da propriedade no DataGridTableStyle padrão. - - - - Occurs when the user clicks the "show/hide parent rows" icon. - Ocorre quando o usuário clica no ícone para "mostrar/ocultar linhas pai". - - - - Value '{0}' cannot be set to an empty value. - '{0}' não pode ser definido como um valor em branco. - - - - Committing the row to the original data store has caused an error. - A confirmação da linha no repositório de dados original causou um erro. - - - - DataGrid received an exception at design time. Reset the DataSource and DataMember property on the grid. - DataGrid recebeu uma exceção em tempo de criação. Redefina as propriedades DataSource e DataMember na grade. - - - - Program cannot get information about the painting and scrolling region. - O programa não pode obter informações sobre a região de pintura e rolagem. - - - - Indicates the index of the column that is first shown. - Indica o índice da coluna a ser mostrada primeiro. - - - - Indicates whether the grid has a flat appearance. - Indica se a grade tem uma aparência plana. - - - - Indicates the color of the grid lines. - Indica a cor das linhas de grade. - - - - Indicates the style of the grid lines. - Indica o estilo das linhas de grade. - - - - The collection of DataGridTableStyle objects that the DataGrid can render its data with. - A coleção de objetos DataGridTableStyle com os quais DataGrid pode renderizar seus dados. - - - - Indicates the background color of the column and row headers. - Indica a cor da tela de fundo de cabeçalhos de colunas e linhas. - - - - Indicates the font of the text in the column and row headers. - Indica a fonte do texto em cabeçalhos de colunas e linhas. - - - - Indicates the color of the text in the column and row headers. - Indica a cor do texto em cabeçalhos de colunas e linhas. - - - - Returns the horizontal scroll bar used by the grid. - Retorna a barra de rolagem horizontal usada pela grade. - - - - Indicates the color of the text that appears inside the child links. - Indica a cor do texto exibido dentro de vínculos filho. - - - - Indicates the color of the text that appears inside a child link when the mouse pointer moves over it. - Indica a cor do texto exibido dentro de um vínculo filho quando o ponteiro do mouse se move sobre ele. - - - - The CurrencyManager that the DataGrid uses to get data from the data source. - CurrencyManager que DataGrid usa para obter dados da fonte de dados. - - - - Occurs when the user navigates to the child rows or when the user navigates back to the parent rows. - Ocorre quando o usuário navega para as linhas filho ou quando navega de volta para as linhas pai. - - - - Indicates whether links to child tables are shown. - Indica se vínculos para tabelas filho são mostrados. - - - - Occurs when the user clicks on the expansion glyph on the row header. - Ocorre quando o usuário clica no glifo de expansão no cabeçalho da linha. - - - - (null) - (nulo) - - - - Event raised when the value of the BackgroundColor property is changed on DataGrid. - Evento gerado quando o valor da propriedade BackgroundColor é alterado em DataGrid. - - - - Event raised when the value of the BorderStyle property is changed on DataGrid. - Evento gerado quando o valor da propriedade BorderStyle é alterado em DataGrid. - - - - Event raised when the value of the CaptionVisible property is changed on DataGrid. - Evento gerado quando o valor da propriedade CaptionVisible é alterado em DataGrid. - - - - Event raised when the value of the CurrentCell property is changed on DataGrid. - Evento gerado quando o valor da propriedade CurrentCell é alterado em DataGrid. - - - - Event raised when the value of the DataSource property is changed on DataGrid. - Evento gerado quando o valor da propriedade DataSource é alterado em DataGrid. - - - - Event raised when the value of the FlatMode property is changed on DataGrid. - Evento gerado quando o valor da propriedade FlatMode é alterado em DataGrid. - - - - Event raised when the value of the NavigationMode property is changed on DataGrid. - Evento gerado quando o valor da propriedade NavigationMode é alterado em DataGrid. - - - - Event raised when the value of the ParentRowsLabelStyle property is changed on DataGrid. - Evento gerado quando o valor da propriedade ParentRowsLabelStyle é alterado em DataGrid. - - - - Event raised when the value of the ParentRowsVisible property is changed on DataGrid. - Evento gerado quando o valor da propriedade ParentRowsVisible é alterado em DataGrid. - - - - Event raised when the value of the ReadOnly property is changed on DataGrid. - Evento gerado quando o valor da propriedade ReadOnly é alterado em DataGrid. - - - - Indicates the background color of the parent rows. - Indica a cor da tela de fundo das linhas pai. - - - - Indicates the color of the text in the parent rows. - Indica a cor do texto nas linhas pai. - - - - Indicates whether the parent rows show labels for the table and for the columns. - Indica se as linhas pai mostram os rótulos para a tabela e as colunas. - - - - Indicates whether the parent rows area is visible. - Indica se a área de linhas pai está visível. - - - - Specifies what the default pixel widths of the grid columns are. The default value for PreferredColumnWidth is 75. - Especifica quais são as larguras de pixel padrão de colunas de grade. O valor padrão para PreferredColumnWidth é 75. - - - - Indicates the preferred height of the rows. - Indica a altura preferencial das linhas. - - - - Value {0} Do you want to correct this value? - Valor {0} Deseja corrigir esse valor? - - - - Indicates whether rows in the grid can be edited, added, or deleted. - Indica se as linhas na grade podem ser editadas, adicionadas ou excluídas. - - - - Indicates the width of the row headers. - Indica a largura dos cabeçalhos de linha. - - - - Indicates whether the row headers are visible. - Indica se os cabeçalhos de linha estão visíveis. - - - - DataGridRow.Height cannot be negative. - DataGridRow.Height não pode ser negativo. - - - - DataGridRow cannot have a negative row number. - DataGridRow não pode ter um número de linha negativo. - - - - Occurs when the user scrolls either the horizontal or vertical scroll bar. - Ocorre quando o usuário usa a barra de rolagem horizontal ou verticalmente. - - - - Indicates the index of the current row. - Indica o índice da linha atual. - - - - Indicates the background color of any selected cells or rows. - Indica a cor da tela de fundo de qualquer linha ou célula selecionada. - - - - Indicates the color of the text in any selected cells or rows. - Indica a cor do texto de qualquer linha ou célula selecionada. - - - - ListManager can be set using the DataSource and DataMember properties. - ListManager pode ser definido usando as propriedades DataSource e DataMember. - - - - Position on a null ListManager cannot be set. - A posição em um ListManager nulo não pode ser definida. - - - - CurrentCell cannot be set at this time. Moving your code to the Form.Load event should solve this problem. - CurrentCell não pode ser definido neste momento. Mova o código para o evento Form.Load para solucionar este problema. - - - - DataGridTable instance does not exist in the collection. - A instância de DataGridTable não existe na coleção. - - - - DataGridTableStyle that is already parented to another DataGrid cannot be added. - Não é possível adicionar um DataGridTableStyle que já é pai de outro DataGrid. - - - - Data grid table styles collection already contains a table style with the same mapping name. - A coleção de estilos de tabela de grade de dados já contém um estilo de tabela com o mesmo nome de mapeamento. - - - - DataGridTableStyle does not support transparent AlternatingBackColor. - DataGridTableStyle não dá suporte a AlternatingBackColor transparente. - - - - DataGridTableStyle does not support transparent BackColor. - DataGridTableStyle não dá suporte a BackColor transparente. - - - - DataGridTableStyle does not support transparent HeaderBackColor. - DataGridTableStyle não dá suporte a HeaderBackColor transparente. - - - - DataGridTableStyle does not support transparent SelectionBackColor. - DataGridTableStyle não dá suporte a SelectionBackColor transparente. - - - - null rectangle for icon bounds when adding tool tip. - Retângulo nulo para limites do ícone ao adicionar dica de ferramenta. - - - - DataGrid control does not support transparent AlternatingBackColor. - O controle DataGrid não dá suporte a AlternatingBackColor transparente. - - - - DataGrid control does not support transparent BackColor. - O controle DataGrid não dá suporte a BackColor transparente. - - - - DataGrid control does not support transparent CaptionBackColor. - O controle DataGrid não dá suporte a CaptionBackColor transparente. - - - - DataGrid control does not support transparent HeaderBackColor. - O controle DataGrid não dá suporte a HeaderBackColor transparente. - - - - DataGrid control does not support transparent ParentRowsBackColor. - O controle DataGrid não dá suporte a ParentRowsBackColor transparente. - - - - DataGrid control does not support transparent SelectionBackColor. - O controle DataGrid não dá suporte a SelectionBackColor transparente. - - - - Data cannot be read from a DataGrid which is not bound to a DataTable. - Os dados não podem ser lidos de um DataGrid que não está associado a um DataTable. - - - - Returns the vertical scroll bar used by the grid. - Retorna a barra de rolagem vertical usada pela grade. - - Occurs when the value of the AlternatingRowsDefaultCellStyle property changes. Ocorre quando o valor da propriedade AlternatingRowsDefaultCellStyle é alterado. @@ -5657,21 +5172,11 @@ Deseja substituí-lo? O tamanho máximo para redimensionamento do formulário. - - The main menu of the form. This must be set to a component of type MainMenu. - O menu principal do formulário. É necessário defini-lo como um componente do tipo MainMenu. - - Specifies the primary MenuStrip for the Form. This property is used for keyboard activation and automatic merging in MDI. Especifica a MenuStrip primário do formulário. Essa propriedade é usada para ativação do teclado e mesclagem automática em MDI. - - The merged menu of this form, which is used when displaying a single merged MDI menu. - O menu mesclado deste formulário, que é usado ao exibir um único menu MDI mesclado. - - Determines whether a form has a minimize box in the upper-right corner of its caption bar. Determina se um formulário tem uma caixa de minimização no canto superior direito de sua barra de legenda. @@ -7171,26 +6676,6 @@ Rastreamento de pilha em que a operação ilegal ocorreu: O formulário especificado para ser o MdiParent deste formulário não é um MdiContainer. - - Occurs when the main menu collapses. - Ocorre quando o menu principal é recolhido. - - - - Gets or sets the ImageList associated with this main menu. - Obtém ou define ImageList associada ao menu principal. - - - - Gets or sets a value indicating whether the menu has an image margin. - Obtém ou define um valor indicando se o menu tem uma margem de imagem. - - - - <No Form> - <No Form> - - Indicates whether the prompt character is valid as input. Indica se o caractere de prompt é válido como entrada. @@ -7326,139 +6811,14 @@ Rastreamento de pilha em que a operação ilegal ocorreu: Especifica o Tipo de objeto a ser usado para análise do texto de entrada quando o controle perde o foco. - - Parameter must be of type MenuItem. - O parâmetro deve ser do tipo MenuItem. - - - - Gets or sets the background color of this menu's image margin. - Obtém ou define a cor da tela de fundo da margem da imagem deste menu. - - - - Indicates if this menu contains any child items. - Indica se este menu contém algum item filho. - - - - Cannot add MenuItem '{0}'. It already exists as a parent of the current menu item. - Não é possível adicionar MenuItem '{0}'. Ele já existe como pai do item de menu atual. - - - - Indicates whether the item is checked. - Indica se o item está selecionado. - - - - Indicates whether the item is the default item. - Indica se o item é o item padrão. - - - - Indicates whether the item is enabled. - Indica se o item está ativado. - - - - Gets or sets the image to be displayed on this menu item. - Obtém ou define a imagem a ser exibida neste item de menu. - - - - Gets or sets the ImageList associated with this menu item. - Obtém ou define ImageList associada ao item de menu. - - - - Gets or sets the background color of this menu item's image margin. - Obtém ou define a cor da tela de fundo de margem da imagem deste item de menu. - - - - True is not a valid value for the Checked property. This is only valid for MenuItems that have no children and are not top-level. - True não é um valor válido para a propriedade Checked. Este só é válido para MenuItems que não têm filhos e não são de nível superior. - - - - Determines whether the MDI child window list is appended to this item. - Determina se a lista de janelas filho MDI está anexada a este item. - - - - Determines the merge order of the item. - Determina a ordem de mesclagem do item. - - - - Determines how the item is handled when menus are merged. - Determina como o item é tratado na mesclagem de menus. - - - - Occurs when the menu item is selected. - Ocorre quando o item de menu é selecionado. - - - - Occurs before the containing menu is displayed. - Ocorre antes que o menu recipiente seja exibido. - - - - Occurs when the menu item is selected. - Ocorre quando o item de menu é selecionado. - - - - Indicates if Windows will draw the menu item or if the user will handle the painting. - Indica se Windows desenhará o item de menu ou se o usuário tratará a pintura. - - - - If the item is checked, this value will determine whether the check style is a radio button. - Se o item estiver marcado, o valor determinará se o estilo de verificação é um botão de seleção. - - The shortcut key associated with the menu item. - A tecla de atalho associada ao item de menu. + The shortcut key associated with the menu item. Indicates whether the shorcut key for the menu item is displayed on the item. - Indica se a tecla de atalho para o item de menu é exibida no item. - - - - The caption displayed by the item. - A legenda exibida pelo item. - - - - Indicates whether the item is visible. - Indica se o item está visível. - - - - Retrieves the menu item that contains a list of MDI child windows. - Recupera o item de menu que contém uma lista de janelas filho MDI. - - - - The menu items for the menu. - Os itens de menu para o menu. - - - - Cannot merge a menu with itself. - Não é possível mesclar um menu com ele mesmo. - - - - Indicates if this menu should display right to left - Indica se este menu deve ser exibido da direita para a esquerda + Indicates whether the shorcut key for the menu item is displayed on the item. @@ -9976,136 +9336,6 @@ Rastreamento de pilha em que a operação ilegal ocorreu: Número excessivo de chamadas para ResumeUpdateMenuHandles. - - Controls the appearance of the ToolBar control, using values from the ToolBarAppearance enumeration. - Controla a aparência do controle ToolBar, usando os valores de enumeração ToolBarAppearance. - - - - Controls whether the ToolBar will automatically size itself based on Button size. - Controla se ToolBar será dimensionado automaticamente com base no tamanho do botão. - - - - Parameter must be of type ToolBarButton. - O parâmetro deve ser do tipo ToolBarButton. - - - - Controls what type of border the ToolBar control will have. - Controla o tipo de borda que o controle ToolBar terá. - - - - Occurs whenever a button in the ToolBar is clicked by the user. - Ocorre sempre que um botão em ToolBar é clicado pelo usuário. - - - - Occurs whenever a button with the DropDownButton style is pressed. - Ocorre sempre que um botão com o estilo DropDownButton é pressionado. - - - - Controls whether this button responds to user input. - Controla se este botão responde à entrada do usuário. - - - - Identifies the image displayed on the button. - Identifica a imagem exibida no botão. - - - - The drop-down menu for a ToolBarButton must be of type ContextMenu. - O menu suspenso para um ToolBarButton deve ser do tipo ContextMenu. - - - - The shortcut menu that will appear if this button's style is set to DropDownButton. - O menu de atalho a ser exibido se o estilo deste botão for definido como DropDownButton. - - - - References that a non-existent ToolBarButton has been received. - Referências de que um ToolBarButton inexistente foi recebido. - - - - Controls whether the button should be displayed as partially pushed or not, but only if the style of the button is ToggleButton. - Controla se o botão deve ser exibido como parcialmente pressionado ou não, mas somente se o estilo do botão for ToggleButton. - - - - Indicates whether the button is pushed or not. This is most commonly seen for buttons with the TOGGLEBUTTON style. - Indica se o botão está pressionado ou não. Isso é mais comum para botões com estilo TOGGLEBUTTON. - - - - The size of the buttons on the control if the button contents do not require a larger size. - O tamanho dos botões no controle se o conteúdo do botão não exigir um tamanho maior. - - - - Indicates what style of ToolBarButton this will be. - Indica o estilo de ToolBarButton a ser usado. - - - - The caption to be displayed for this button. - A legenda a ser exibida para este botão. - - - - The ToolTip text to be displayed for this button. - O texto de dica de ferramenta a ser exibido para este botão. - - - - Indicates whether this button should be visible. - Indica se este botão deve estar visível. - - - - The collection of ToolBarButtons that make up this ToolBar. - A coleção de ToolBarButtons que compõe este ToolBar. - - - - Controls whether the ToolBar will display a 3-D line at the top of its client area. - Controla se ToolBar exibirá uma linha em 3D na parte superior de sua área cliente. - - - - Controls whether the ToolBar will display an arrow on the side of drop-down buttons. - Controla se ToolBar exibirá uma seta na lateral dos botões suspensos. - - - - The ImageList from which this ToolBar will get all of the button images. - ImageList do qual este ToolBar obterá todas as imagens de botões. - - - - The size of the images within the ToolBar's ImageList. - O tamanho das imagens dentro de ImageList de ToolBar. - - - - Indicates whether ToolTips will be shown for each of the buttons, if available. - Indica se dicas de ferramenta serão mostradas para cada um dos botões, se disponíveis. - - - - Controls how the text is positioned relative to the Image in each button. - Controla como o texto é posicionado em relação à imagem em cada botão. - - - - Indicates if more than one row of buttons is allowed. - Indica se é permitida mais de uma linha de botões. - - AllowItemReorder and AllowDrop cannot both be true. AllowItemReorder e AllowDrop não podem ser verdadeiros. diff --git a/src/System.Windows.Forms/src/Resources/xlf/SR.ru.xlf b/src/System.Windows.Forms/src/Resources/xlf/SR.ru.xlf index 6bdc33c51b0..f9b20cc7683 100644 --- a/src/System.Windows.Forms/src/Resources/xlf/SR.ru.xlf +++ b/src/System.Windows.Forms/src/Resources/xlf/SR.ru.xlf @@ -1217,34 +1217,9 @@ Родительская форма данного вмещающего элемента управления. - - Raised when the context menu collapses. - Вызывается при сворачивании контекстного меню. - - - - Gets or sets the ImageList associated with this context menu. - Получает или устанавливает ImageList для данного контекстного меню. - - - - ContextMenu cannot be shown on an invisible control. - Невозможно отобразить ContextMenu в невидимом элементе управления. - - - - Gets or sets a value indicating whether the menu has an image margin. - Получает или задает значение, определяющее наличие в меню полей изображения. - - - - The last control that caused this context menu to be displayed. - Последний элемент управления, вызывавший отображение этого контекстного меню. - - The last control that caused this context menu strip to be displayed. - Последний элемент управления, вызвавший отображение полосы данного контекстного меню. + The last control that caused this context menu strip to be displayed. @@ -2107,466 +2082,6 @@ Метод RemoveAt не поддерживается для привязки свойства к другому свойству. - - Indicates whether the grid can be re-sorted by clicking a column header. - Указывает, можно ли пересортировать таблицу, щелкнув заголовок столбца. - - - - Indicates the background color of alternating rows for a ledger appearance. - Указывает цвет фона чередующихся строк для оформления разными цветами. - - - - Occurs when the user clicks the Back button on a child table to return to the parent table. - Возникает, когда пользователь нажимает кнопку "Назад" в дочерней таблице, чтобы вернуться в родительскую таблицу. - - - - Indicates the color of the DataGrid background. - Указывает фоновый цвет DataGrid. - - - - BeginInit() has already been called without an EndInit(). - Метод BeginInit() был вызван ранее без вызова метода EndInit(). - - - - Specifies whether the DataGridBoolColumn allows null values. - Указывает, допускаются ли для DataGridBoolColumn неопределенные значения. - - - - Indicates the border style for the DataGrid. - Указывает стиль границы для DataGrid. - - - - Navigates back to the parent rows. - Выполняет возврат к родительским строкам. - - - - Indicates the background color of the top caption. - Указывает фоновый цвет для верхнего заголовка. - - - - Shows/Hides the parent rows for the current set of child rows. - Отображает/Скрывает родительские строки для текущего набора дочерних строк. - - - - Indicates the font of the top caption. - Указывает шрифт для верхнего заголовка. - - - - Indicates the color of text that appears in the top caption. - Указывает цвет текста, отображаемого в верхнем заголовке. - - - - Indicates the text displayed in the top caption. - Указывает текст, отображаемый в верхнем заголовке. - - - - Indicates whether the top caption is visible. - Указывает, является ли верхний заголовок видимым. - - - - DataGridColumn instance does not exist in the collection. - Экземпляр DataGridColumn отсутствует в данной коллекции. - - - - Indicates whether the column headers are visible. - Указывает, видимы ли заголовки столбцов. - - - - Position of ListManager must be equal to 'rowNum'. - Позиция ListManager должна равняться 'rowNum'. - - - - PropertyDescriptor has not been set on this DataGridColumn. - Для этого DataGridColumn не задано свойство PropertyDescriptor. - - - - Data grid column styles collection already contains a column style with the same mapping name. - Коллекция стилей столбцов сетки данных уже содержит стиль столбца с данным именем сопоставления. - - - - DataGridColumnStyle of '{0}' cannot be used because it is not associated with a Property or Column in the DataSource. - Использование DataGridColumnStyle для'{0}' невозможно, так как оно не связано со свойством или столбцом в DataSource. - - - - ColumnWidth must be greater than or equal to 0. - Значение ColumnWidth должно быть больше или равно нулю. - - - - The currently selected cell in the DataGrid. - Ячейка, выбранная в данный момент в DataGrid. - - - - Indicates a sub-list of the DataSource to show in the DataGrid. - Указывает подсписок DataSource для отображения в DataGrid. - - - - Indicates the source of data for the DataGrid. - Указывает источник данных для DataGrid. - - - - User cannot change the contents of the default GridColumnStylesCollection. - Пользователь не может изменять содержимое GridColumnStylesCollection по умолчанию. - - - - Value of this property cannot be changed on the default DataGridTableStyle. - Изменение данного свойства для DataGridTableStyle по умолчанию невозможно. - - - - Occurs when the user clicks the "show/hide parent rows" icon. - Возникает, когда пользователь щелкает значок "Отображать/Скрывать родительские строки". - - - - Value '{0}' cannot be set to an empty value. - Значение '{0}' не может быть пустым. - - - - Committing the row to the original data store has caused an error. - Ошибка при передаче строки в хранилище исходных данных. - - - - DataGrid received an exception at design time. Reset the DataSource and DataMember property on the grid. - DataGrid получила исключение во время разработки. Переустановите свойства DataSource и DataMember для сетки. - - - - Program cannot get information about the painting and scrolling region. - Программа не может получить информацию об области прорисовки и прокрутки. - - - - Indicates the index of the column that is first shown. - Указывает индекс столбца, отображаемого первым. - - - - Indicates whether the grid has a flat appearance. - Указывает, отображается ли сетка двумерной. - - - - Indicates the color of the grid lines. - Указывает цвет линий сетки. - - - - Indicates the style of the grid lines. - Указывает стиль линий сетки. - - - - The collection of DataGridTableStyle objects that the DataGrid can render its data with. - Коллекция объектов DataGridTableStyle, в соответствии с которыми DataGrid может отображать данные. - - - - Indicates the background color of the column and row headers. - Указывает фоновый цвет заголовков столбцов и строк. - - - - Indicates the font of the text in the column and row headers. - Указывает шрифт текста в заголовках столбцов и строк. - - - - Indicates the color of the text in the column and row headers. - Указывает цвет текста в заголовках столбцов и строк. - - - - Returns the horizontal scroll bar used by the grid. - Возвращает горизонтальную полосу прокрутки, используемую для данной сетки. - - - - Indicates the color of the text that appears inside the child links. - Указывает цвет текста, отображаемого в дочерних ссылках. - - - - Indicates the color of the text that appears inside a child link when the mouse pointer moves over it. - Указывает цвет текста, отображаемого в дочерних ссылках, при наведении на них указателя мыши. - - - - The CurrencyManager that the DataGrid uses to get data from the data source. - Функция CurrencyManager, которую DataGrid использует для получения данных от источника данных. - - - - Occurs when the user navigates to the child rows or when the user navigates back to the parent rows. - Возникает при переходе к дочерним строкам или при переходе обратно к родительским строкам. - - - - Indicates whether links to child tables are shown. - Указывает, отображаются ли ссылки на дочерние таблицы. - - - - Occurs when the user clicks on the expansion glyph on the row header. - Возникает, когда пользователь щелкает значок расширения в заголовке строки. - - - - (null) - (null) - - - - Event raised when the value of the BackgroundColor property is changed on DataGrid. - Событие возникает, когда в DataGrid изменяется значение свойства BackgroundColor. - - - - Event raised when the value of the BorderStyle property is changed on DataGrid. - Событие возникает, когда в DataGrid изменяется значение свойства BorderStyle. - - - - Event raised when the value of the CaptionVisible property is changed on DataGrid. - Событие возникает, когда в DataGrid изменяется значение свойства CaptionVisible. - - - - Event raised when the value of the CurrentCell property is changed on DataGrid. - Событие возникает, когда в DataGrid изменяется значение свойства CurrentCell. - - - - Event raised when the value of the DataSource property is changed on DataGrid. - Событие возникает, когда в DataGrid изменяется значение свойства DataSource. - - - - Event raised when the value of the FlatMode property is changed on DataGrid. - Событие возникает, когда в DataGrid изменяется значение свойства FlatMode. - - - - Event raised when the value of the NavigationMode property is changed on DataGrid. - Событие возникает, когда в DataGrid изменяется значение свойства NavigationMode. - - - - Event raised when the value of the ParentRowsLabelStyle property is changed on DataGrid. - Событие возникает, когда в DataGrid изменяется значение свойства ParentRowsLabelStyle. - - - - Event raised when the value of the ParentRowsVisible property is changed on DataGrid. - Событие возникает, когда в DataGrid изменяется значение свойства ParentRowsVisible. - - - - Event raised when the value of the ReadOnly property is changed on DataGrid. - Событие возникает, когда в DataGrid изменяется значение свойства ReadOnly. - - - - Indicates the background color of the parent rows. - Указывает фоновый цвет для родительских строк. - - - - Indicates the color of the text in the parent rows. - Указывает цвет текста в родительских строках. - - - - Indicates whether the parent rows show labels for the table and for the columns. - Указывает, отображаются ли в родительских строках подписи к данной таблице и к столбцам. - - - - Indicates whether the parent rows area is visible. - Указывает, видима ли область родительских строк. - - - - Specifies what the default pixel widths of the grid columns are. The default value for PreferredColumnWidth is 75. - Задает ширину (в пикселях) столбцов сетки по умолчанию. Значение по умолчанию для PreferredColumnWidth равно 75. - - - - Indicates the preferred height of the rows. - Указывает предпочтительную высоту строк. - - - - Value {0} Do you want to correct this value? - Значение {0} Исправить это значение? - - - - Indicates whether rows in the grid can be edited, added, or deleted. - Указывает, разрешается ли редактировать, добавлять и удалять строки в сетке. - - - - Indicates the width of the row headers. - Указывает ширину заголовков строк. - - - - Indicates whether the row headers are visible. - Указывает, видимы ли заголовки строк. - - - - DataGridRow.Height cannot be negative. - Значение DataGridRow.Height не может быть отрицательным. - - - - DataGridRow cannot have a negative row number. - Номер строки DataGridRow не может быть отрицательным. - - - - Occurs when the user scrolls either the horizontal or vertical scroll bar. - Возникает при прокрутке либо горизонтальной, либо вертикальной полосы прокрутки. - - - - Indicates the index of the current row. - Указывает индекс текущей строки. - - - - Indicates the background color of any selected cells or rows. - Указывает цвет фона в любых выбранных столбцах или строках. - - - - Indicates the color of the text in any selected cells or rows. - Указывает цвет текста в любых выбранных столбцах или строках. - - - - ListManager can be set using the DataSource and DataMember properties. - ListManager можно установить с помощью свойств DataSource и DataMember. - - - - Position on a null ListManager cannot be set. - Невозможно установить позицию для пустого ListManager. - - - - CurrentCell cannot be set at this time. Moving your code to the Form.Load event should solve this problem. - В текущий момент невозможно установить CurrentCell. Ошибку можно устранить, переместив код в событие Form.Load. - - - - DataGridTable instance does not exist in the collection. - Экземпляр DataGridTable отсутствует в данной коллекции. - - - - DataGridTableStyle that is already parented to another DataGrid cannot be added. - Добавление DataGridTableStyle, который уже является дочерним для другого DataGrid, не допускается. - - - - Data grid table styles collection already contains a table style with the same mapping name. - Коллекция стилей таблиц сетки данных уже содержит таблицу с данным именем сопоставления. - - - - DataGridTableStyle does not support transparent AlternatingBackColor. - DataGridTableStyle не поддерживает прозрачный AlternatingBackColor. - - - - DataGridTableStyle does not support transparent BackColor. - DataGridTableStyle не поддерживает прозрачный BackColor. - - - - DataGridTableStyle does not support transparent HeaderBackColor. - DataGridTableStyle не поддерживает прозрачный HeaderBackColor. - - - - DataGridTableStyle does not support transparent SelectionBackColor. - DataGridTableStyle не поддерживает прозрачный SelectionBackColor. - - - - null rectangle for icon bounds when adding tool tip. - неопределенный прямоугольник для границ значка при добавлении подсказки. - - - - DataGrid control does not support transparent AlternatingBackColor. - Элемент управления DataGrid не поддерживает прозрачный AlternatingBackColor. - - - - DataGrid control does not support transparent BackColor. - Элемент управления DataGrid не поддерживает прозрачный BackColor. - - - - DataGrid control does not support transparent CaptionBackColor. - Элемент управления DataGrid не поддерживает прозрачный CaptionBackColor. - - - - DataGrid control does not support transparent HeaderBackColor. - Элемент управления DataGrid не поддерживает прозрачный HeaderBackColor. - - - - DataGrid control does not support transparent ParentRowsBackColor. - Элемент управления DataGrid не поддерживает прозрачный ParentRowsBackColor. - - - - DataGrid control does not support transparent SelectionBackColor. - Элемент управления DataGrid не поддерживает прозрачный SelectionBackColor. - - - - Data cannot be read from a DataGrid which is not bound to a DataTable. - Невозможно считать данные из DataGrid, не имеющего привязки к DataTable. - - - - Returns the vertical scroll bar used by the grid. - Возвращает вертикальную полосу прокрутки, используемую для данной сетки. - - Occurs when the value of the AlternatingRowsDefaultCellStyle property changes. Возникает при изменении значения свойства AlternatingRowsDefaultCellStyle. @@ -5658,21 +5173,11 @@ Do you want to replace it? Максимальный размер, который может иметь форма. - - The main menu of the form. This must be set to a component of type MainMenu. - Главное меню формы. Должно присваиваться компоненту типа MainMenu. - - Specifies the primary MenuStrip for the Form. This property is used for keyboard activation and automatic merging in MDI. Определяет для Form первичный MenuStrip. Данное свойство используется для активации клавиатуры и автоматического слияния в MDI. - - The merged menu of this form, which is used when displaying a single merged MDI menu. - Объединенное меню этой формы, используемое при отображении одного общего меню MDI. - - Determines whether a form has a minimize box in the upper-right corner of its caption bar. Определяет, содержит ли форма в правом верхнем углу строки заголовка значок свертывания. @@ -7172,26 +6677,6 @@ Stack trace where the illegal operation occurred was: Форма, указанная как MdiParent для данной формы, не является MdiContainer. - - Occurs when the main menu collapses. - Происходит при сворачивании главного меню. - - - - Gets or sets the ImageList associated with this main menu. - Получает или задает ImageList, соответствующий данному главному меню. - - - - Gets or sets a value indicating whether the menu has an image margin. - Получает или задает значение, определяющее наличие в меню полей изображения. - - - - <No Form> - <No Form> - - Indicates whether the prompt character is valid as input. Указывает, является ли символ, введенный в окне приглашения, допустимым. @@ -7327,139 +6812,14 @@ Stack trace where the illegal operation occurred was: Указывает Type для объекта, который будет использоваться для разбора вводимого текста при потере фокуса элементом управления. - - Parameter must be of type MenuItem. - Параметр должен иметь тип MenuItem. - - - - Gets or sets the background color of this menu's image margin. - Считывает или задает цвет фона для поля рисунка этого меню. - - - - Indicates if this menu contains any child items. - Указывает, содержит ли это меню дочерние элементы. - - - - Cannot add MenuItem '{0}'. It already exists as a parent of the current menu item. - Невозможно добавить MenuItem '{0}'. Он уже существует как родитель для данного пункта меню. - - - - Indicates whether the item is checked. - Указывает, установлен ли этот элемент. - - - - Indicates whether the item is the default item. - Указывает, является ли этот пункт элементом по умолчанию. - - - - Indicates whether the item is enabled. - Указывает, включен ли данный элемент. - - - - Gets or sets the image to be displayed on this menu item. - Считывает или задает рисунок, отображаемый в данном пункте меню. - - - - Gets or sets the ImageList associated with this menu item. - Считывает или задает ImageList, связанный с данным пунктом меню. - - - - Gets or sets the background color of this menu item's image margin. - Считывает или задает цвет фона для поля рисунка этого пункта меню. - - - - True is not a valid value for the Checked property. This is only valid for MenuItems that have no children and are not top-level. - True (истина) не является допустимым значением для Checked Property. Это значение допустимо только для MenuItems, не имеющего дочерних элементов и не принадлежащего к верхнему уровню. - - - - Determines whether the MDI child window list is appended to this item. - Определяет, присоединен ли список дочерних окон MDI к этому пункту. - - - - Determines the merge order of the item. - Определяет порядок слияния для этого элемента. - - - - Determines how the item is handled when menus are merged. - Определяет, как будет обрабатываться данный пункт при слиянии меню. - - - - Occurs when the menu item is selected. - Происходит, когда выбирается элемент меню. - - - - Occurs before the containing menu is displayed. - Происходит перед отображением охватывающего меню. - - - - Occurs when the menu item is selected. - Происходит, когда выбирается элемент меню. - - - - Indicates if Windows will draw the menu item or if the user will handle the painting. - Указывает, прорисовывает ли Windows данный элемент меню или прорисовку реализует пользователь. - - - - If the item is checked, this value will determine whether the check style is a radio button. - Если этот пункт выбран, данное значение будет определять, является ли данный элемент переключателем. - - The shortcut key associated with the menu item. - Указывает клавиши быстрого доступа к данному меню. + The shortcut key associated with the menu item. Indicates whether the shorcut key for the menu item is displayed on the item. - Определяет, будут ли отображаться клавиши быстрого доступа для данного элемента меню. - - - - The caption displayed by the item. - Заголовок, отображаемый данным элементом. - - - - Indicates whether the item is visible. - Указывает, является ли этот элемент видимым. - - - - Retrieves the menu item that contains a list of MDI child windows. - Извлекает элемент меню, который содержит список дочерних MDI-окон. - - - - The menu items for the menu. - Элементы данного меню. - - - - Cannot merge a menu with itself. - Невозможно объединить меню с самим собой. - - - - Indicates if this menu should display right to left - Показывает, должно ли данное меню отображаться справа налево. + Indicates whether the shorcut key for the menu item is displayed on the item. @@ -9977,136 +9337,6 @@ Stack trace where the illegal operation occurred was: Недопустимо большое число вызовов ResumeUpdateMenuHandles. - - Controls the appearance of the ToolBar control, using values from the ToolBarAppearance enumeration. - Задает внешний вид элемента управления ToolBar с помощью значений из перечисления ToolBarAppearance. - - - - Controls whether the ToolBar will automatically size itself based on Button size. - Указывает, будет ли ToolBar автоматически изменять размер в соответствии с размером кнопок. - - - - Parameter must be of type ToolBarButton. - Параметр должен быть типа ToolBarButton. - - - - Controls what type of border the ToolBar control will have. - Определяет тип границы для элемента управления ToolBar. - - - - Occurs whenever a button in the ToolBar is clicked by the user. - Происходит при каждом нажатии кнопки на ToolBar с помощью мыши. - - - - Occurs whenever a button with the DropDownButton style is pressed. - Происходит при каждом нажатии кнопки, имеющей стиль DropDownButton. - - - - Controls whether this button responds to user input. - Указывает, воспринимает ли эта кнопка действия пользователя. - - - - Identifies the image displayed on the button. - Указывает индекс изображения в ImageList для родительского ToolBar, который используется при получении изображения для этой кнопки. - - - - The drop-down menu for a ToolBarButton must be of type ContextMenu. - Раскрывающееся меню для ToolBarButton должно иметь тип ContextMenu. - - - - The shortcut menu that will appear if this button's style is set to DropDownButton. - Контекстное меню, отображаемое в том случае, если кнопке назначен стиль DropDownButton. - - - - References that a non-existent ToolBarButton has been received. - Сообщает о том, что получен несуществующий ToolBarButton. - - - - Controls whether the button should be displayed as partially pushed or not, but only if the style of the button is ToggleButton. - Задает, должна ли кнопка отображаться нажатой (только для кнопок, имеющих стиль ToggleButton). - - - - Indicates whether the button is pushed or not. This is most commonly seen for buttons with the TOGGLEBUTTON style. - Указывает, находится ли кнопка в нажатом положении. Обычно этот признак используется для кнопок, имеющих стиль TOGGLEBUTTON. - - - - The size of the buttons on the control if the button contents do not require a larger size. - Предлагает размер кнопок на ToolBar. Размеры отдельных кнопок могут отличаться от данного размера в зависимости от длины текста, наличия стрелок раскрывающегося списка и др. - - - - Indicates what style of ToolBarButton this will be. - Указывает, какой стиль ToolBarButton будет использоваться. - - - - The caption to be displayed for this button. - Надпись, отображаемая на этой кнопке. - - - - The ToolTip text to be displayed for this button. - Текст подсказки, отображаемый для этой кнопки. - - - - Indicates whether this button should be visible. - Указывает, должна ли эта кнопка быть видимой. - - - - The collection of ToolBarButtons that make up this ToolBar. - Коллекция ToolBarButton, из которых состоит эта панель ToolBar. - - - - Controls whether the ToolBar will display a 3-D line at the top of its client area. - Задает, должна ли в верхней части клиентской области панели ToolBar отображаться объемная линия. - - - - Controls whether the ToolBar will display an arrow on the side of drop-down buttons. - Задает, отображаются ли на ToolBar стрелки рядом с кнопками, имеющими раскрывающиеся списки. - - - - The ImageList from which this ToolBar will get all of the button images. - ImageList, из которого эта панель ToolBar будет извлекать изображения всех кнопок. - - - - The size of the images within the ToolBar's ImageList. - Размер изображений в списке изображений для ToolBar. - - - - Indicates whether ToolTips will be shown for each of the buttons, if available. - Указывает, должна ли отображаться подсказка (если доступна) для каждой кнопки. - - - - Controls how the text is positioned relative to the Image in each button. - Задает расположение текста относительно изображения на каждой кнопке. - - - - Indicates if more than one row of buttons is allowed. - Указывает, разрешено ли несколько рядов кнопок. - - AllowItemReorder and AllowDrop cannot both be true. AllowItemReorder и AllowDrop не могут одновременно иметь значение true. diff --git a/src/System.Windows.Forms/src/Resources/xlf/SR.tr.xlf b/src/System.Windows.Forms/src/Resources/xlf/SR.tr.xlf index 5cef44e49f3..07f1558bc3a 100644 --- a/src/System.Windows.Forms/src/Resources/xlf/SR.tr.xlf +++ b/src/System.Windows.Forms/src/Resources/xlf/SR.tr.xlf @@ -1217,34 +1217,9 @@ Bu kapsayıcı denetiminin üst formu. - - Raised when the context menu collapses. - İçerik menüsü daraltıldığında harekete geçirilir. - - - - Gets or sets the ImageList associated with this context menu. - Bu içerik menüsüyle ilişkili ImageList'i alır veya ayarlar. - - - - ContextMenu cannot be shown on an invisible control. - ContextMenu, görünmeyen bir denetimde gösterilemiyor. - - - - Gets or sets a value indicating whether the menu has an image margin. - Menüde resim kenar boşluğu olup olmadığını gösteren değeri alır veya ayarlar. - - - - The last control that caused this context menu to be displayed. - Bu bağlam menüsünün görüntülenmesine neden olan en son denetim. - - The last control that caused this context menu strip to be displayed. - Bu içerik menüsü şeridinin görüntülenmesine neden olan en son denetim. + The last control that caused this context menu strip to be displayed. @@ -2107,466 +2082,6 @@ RemoveAt, özellikler arası bağlama için desteklenmiyor. - - Indicates whether the grid can be re-sorted by clicking a column header. - Bir sütun üst bilgisi tıklatılarak kılavuzun yeniden sıralanıp sıralanamayacağını gösterir. - - - - Indicates the background color of alternating rows for a ledger appearance. - Büyük defter görünümü için değişik satırların arka plan rengini gösterir. - - - - Occurs when the user clicks the Back button on a child table to return to the parent table. - Kullanıcı bir üst tabloya dönmek için bir alt tabloda Geri düğmesini tıklattığında gerçekleşir. - - - - Indicates the color of the DataGrid background. - DataGrid arka planının rengini gösterir. - - - - BeginInit() has already been called without an EndInit(). - EndInit() olmadan BeginInit() zaten çağrıldı. - - - - Specifies whether the DataGridBoolColumn allows null values. - DataGridBoolColumn tarafından null değerlere izin verilip verilmediğini belirtir. - - - - Indicates the border style for the DataGrid. - DataGrid için kenarlık stilini gösterir. - - - - Navigates back to the parent rows. - Üst satırlara geri döner. - - - - Indicates the background color of the top caption. - Üst başlığın arka plan rengini gösterir. - - - - Shows/Hides the parent rows for the current set of child rows. - Geçerli alt satırlar kümesi için üst satırları gösterir/gizler. - - - - Indicates the font of the top caption. - Üst başlığın yazı tipini gösterir. - - - - Indicates the color of text that appears in the top caption. - Üst başlıkta görünen metnin rengini gösterir. - - - - Indicates the text displayed in the top caption. - Üst başlıkta görüntülenen metni gösterir. - - - - Indicates whether the top caption is visible. - Üst başlığın görünür olup olmadığını gösterir. - - - - DataGridColumn instance does not exist in the collection. - DataGridColumn örneği koleksiyonda yok. - - - - Indicates whether the column headers are visible. - Sütun üst bilgilerinin görünür olup olmadığını gösterir. - - - - Position of ListManager must be equal to 'rowNum'. - ListManager'ın konumu 'rowNum' ile eşit olmalıdır. - - - - PropertyDescriptor has not been set on this DataGridColumn. - Bu DataGridColumn'da PropertyDescriptor ayarlanmamış. - - - - Data grid column styles collection already contains a column style with the same mapping name. - Veri kılavuzu sütun stilleri koleksiyonunda aynı eşleştirme adına sahip bir sütun stili zaten var. - - - - DataGridColumnStyle of '{0}' cannot be used because it is not associated with a Property or Column in the DataSource. - DataSource'da bir Özellik veya Sütun ile ilişkili olmadığından '{0}' türündeki DataGridColumnStyle kullanılamaz. - - - - ColumnWidth must be greater than or equal to 0. - ColumnWidth özelliği sıfıra eşit veya büyük olmalıdır. - - - - The currently selected cell in the DataGrid. - DataGrid içinde şu anda seçili olan hücre. - - - - Indicates a sub-list of the DataSource to show in the DataGrid. - DataSource'un DataGrid içinde gösterilecek alt listesini gösterir. - - - - Indicates the source of data for the DataGrid. - DataGrid için veri kaynağını gösterir. - - - - User cannot change the contents of the default GridColumnStylesCollection. - Varsayılan GridColumnStylesCollection'ın içeriğini kullanıcı değiştiremez. - - - - Value of this property cannot be changed on the default DataGridTableStyle. - Bu özelliğin değeri varsayılan DataGridTableStyle'da değiştirilemez. - - - - Occurs when the user clicks the "show/hide parent rows" icon. - Kullanıcı "üst satırları göster/gizle" simgesini tıklattığında gerçekleşir. - - - - Value '{0}' cannot be set to an empty value. - '{0}' değeri boş değere ayarlanamaz. - - - - Committing the row to the original data store has caused an error. - Satırı özgün veri deposuna kaydetme bir hataya neden oldu. - - - - DataGrid received an exception at design time. Reset the DataSource and DataMember property on the grid. - DataGrid tasarım zamanında bir özel durum aldı. Kılavuzun DataSource ve DataMember özelliğini sıfırlayın. - - - - Program cannot get information about the painting and scrolling region. - Program boyama ve kaydırma bölgesi hakkında bilgi alamıyor. - - - - Indicates the index of the column that is first shown. - İlk olarak gösterilen sütunun dizinini gösterir. - - - - Indicates whether the grid has a flat appearance. - Kılavuzun düz bir görünümü olup olmadığını gösterir. - - - - Indicates the color of the grid lines. - Kılavuz çizgilerinin rengini gösterir. - - - - Indicates the style of the grid lines. - Kılavuz çizgilerinin stilini gösterir. - - - - The collection of DataGridTableStyle objects that the DataGrid can render its data with. - DataGrid'in verilerini birlikte işleyebileceği DataGridTableStyle nesneleri koleksiyonu. - - - - Indicates the background color of the column and row headers. - Sütun ve satır üst bilgilerinin arka plan rengini gösterir. - - - - Indicates the font of the text in the column and row headers. - Sütun ve satır üst bilgilerindeki metnin yazı tipini gösterir. - - - - Indicates the color of the text in the column and row headers. - Sütun ve satır üst bilgilerindeki metnin rengini gösterir. - - - - Returns the horizontal scroll bar used by the grid. - Kılavuz tarafından kullanılan yatay kaydırma çubuğunu döndürür. - - - - Indicates the color of the text that appears inside the child links. - Alt bağlantılarda görünen metnin rengini gösterir. - - - - Indicates the color of the text that appears inside a child link when the mouse pointer moves over it. - Fare işaretçisi üzerinde geldiğinde alt bağlantıda görünen metnin rengini gösterir. - - - - The CurrencyManager that the DataGrid uses to get data from the data source. - DataGrid'in veri kaynağından veri almak için kullandığı CurrencyManager. - - - - Occurs when the user navigates to the child rows or when the user navigates back to the parent rows. - Kullanıcı alt satırlara gittiğinde veya üst satırlara geri gittiğinde gerçekleşir. - - - - Indicates whether links to child tables are shown. - Alt tablo bağlantılarının gösterilip gösterilmediğini gösterir. - - - - Occurs when the user clicks on the expansion glyph on the row header. - Kullanıcı satır üst bilgisindeki genişletme kabartmasını tıklattığında gerçekleşir. - - - - (null) - (null) - - - - Event raised when the value of the BackgroundColor property is changed on DataGrid. - DataGrid üzerinde BackgroundColor özelliğinin değeri değiştiğinde harekete geçirilen olay. - - - - Event raised when the value of the BorderStyle property is changed on DataGrid. - DataGrid üzerinde BorderStyle özelliğinin değeri değiştiğinde harekete geçirilen olay. - - - - Event raised when the value of the CaptionVisible property is changed on DataGrid. - DataGrid üzerinde CaptionVisible özelliğinin değeri değiştiğinde harekete geçirilen olay. - - - - Event raised when the value of the CurrentCell property is changed on DataGrid. - DataGrid üzerinde CurrentCell özelliğinin değeri değiştiğinde harekete geçirilen olay. - - - - Event raised when the value of the DataSource property is changed on DataGrid. - DataGrid üzerinde DataSource özelliğinin değeri değiştiğinde harekete geçirilen olay. - - - - Event raised when the value of the FlatMode property is changed on DataGrid. - DataGrid üzerinde FlatMode özelliğinin değeri değiştiğinde harekete geçirilen olay. - - - - Event raised when the value of the NavigationMode property is changed on DataGrid. - DataGrid üzerinde NavigationMode özelliğinin değeri değiştiğinde harekete geçirilen olay. - - - - Event raised when the value of the ParentRowsLabelStyle property is changed on DataGrid. - DataGrid üzerinde ParentRowsLabelStyle özelliğinin değeri değiştiğinde harekete geçirilen olay. - - - - Event raised when the value of the ParentRowsVisible property is changed on DataGrid. - DataGrid üzerinde ParentRowsVisible özelliğinin değeri değiştiğinde harekete geçirilen olay. - - - - Event raised when the value of the ReadOnly property is changed on DataGrid. - DataGrid üzerinde ReadOnly özelliğinin değeri değiştiğinde harekete geçirilen olay. - - - - Indicates the background color of the parent rows. - Üst satırların arka plan rengini gösterir. - - - - Indicates the color of the text in the parent rows. - Üst satırlardaki metnin rengini gösterir. - - - - Indicates whether the parent rows show labels for the table and for the columns. - Üst satırların tablo ve sütun etiketlerini gösterip göstermediği belirtir. - - - - Indicates whether the parent rows area is visible. - Üst satır alanının görünür olup olmadığını gösterir. - - - - Specifies what the default pixel widths of the grid columns are. The default value for PreferredColumnWidth is 75. - Kılavuz sütunlarının varsayılan piksel genişliğini belirtir. PreferredColumnWidth için varsayılan değer 75'tir. - - - - Indicates the preferred height of the rows. - Satırların tercih edilen yüksekliği gösterir. - - - - Value {0} Do you want to correct this value? - Değer {0} Bu değeri düzeltmek istiyor musunuz? - - - - Indicates whether rows in the grid can be edited, added, or deleted. - Kılavuzdaki satırların düzenlenebilir, eklenebilir veya silinebilir olup olmadıklarını gösterir. - - - - Indicates the width of the row headers. - Satır üst bilgilerinin genişliğini gösterir. - - - - Indicates whether the row headers are visible. - Satır üst bilgilerinin görünür olup olmadıklarını gösterir. - - - - DataGridRow.Height cannot be negative. - DataGridRow.Height değeri eksi olamaz. - - - - DataGridRow cannot have a negative row number. - DataGridRow eksi bir satır numarası alamaz. - - - - Occurs when the user scrolls either the horizontal or vertical scroll bar. - Kullanıcı yatay veya dikey kaydırma çubuğunu kaydırdığında gerçekleşir. - - - - Indicates the index of the current row. - Geçerli satırın dizinini gösterir. - - - - Indicates the background color of any selected cells or rows. - Seçili herhangi bir hücre veya satırın arka plan rengini gösterir. - - - - Indicates the color of the text in any selected cells or rows. - Seçili herhangi bir hücre veya satırdaki metnin rengini gösterir. - - - - ListManager can be set using the DataSource and DataMember properties. - DataSource ve DataMember özellikleri kullanılarak ListManager ayarlanabilir. - - - - Position on a null ListManager cannot be set. - Null olan ListManager'da konum ayarlanamaz. - - - - CurrentCell cannot be set at this time. Moving your code to the Form.Load event should solve this problem. - CurrentCell şu anda ayarlanamıyor. Kodunuzu Form.Load olayına taşıdığınızda bu sorun çözülmeli. - - - - DataGridTable instance does not exist in the collection. - DataGridTable örneği koleksiyonda yok. - - - - DataGridTableStyle that is already parented to another DataGrid cannot be added. - Başka bir DataGrid için zaten üst öğe yapılan DataGridTableStyle eklenemez. - - - - Data grid table styles collection already contains a table style with the same mapping name. - Veri kılavuzu tablo stilleri koleksiyonunda aynı eşleştirme adına sahip bir tablo stili zaten var. - - - - DataGridTableStyle does not support transparent AlternatingBackColor. - DataGridTableStyle saydam AlternatingBackColor'ı desteklemiyor. - - - - DataGridTableStyle does not support transparent BackColor. - DataGridTableStyle saydam BackColor'ı desteklemiyor. - - - - DataGridTableStyle does not support transparent HeaderBackColor. - DataGridTableStyle saydam HeaderBackColor'ı desteklemiyor. - - - - DataGridTableStyle does not support transparent SelectionBackColor. - DataGridTableStyle saydam SelectionBackColor'ı desteklemiyor. - - - - null rectangle for icon bounds when adding tool tip. - araç ipucu eklerken simge sınırlarını belirten dikdörtgen null. - - - - DataGrid control does not support transparent AlternatingBackColor. - DataGrid denetimi saydam AlternatingBackColor'ı desteklemiyor. - - - - DataGrid control does not support transparent BackColor. - DataGrid denetimi saydam BackColor'ı desteklemiyor. - - - - DataGrid control does not support transparent CaptionBackColor. - DataGrid denetimi saydam CaptionBackColor'ı desteklemiyor. - - - - DataGrid control does not support transparent HeaderBackColor. - DataGrid denetimi saydam HeaderBackColor'ı desteklemiyor. - - - - DataGrid control does not support transparent ParentRowsBackColor. - DataGrid denetimi saydam ParentRowsBackColor'ı desteklemiyor. - - - - DataGrid control does not support transparent SelectionBackColor. - DataGrid denetimi saydam SelectionBackColor'ı desteklemiyor. - - - - Data cannot be read from a DataGrid which is not bound to a DataTable. - Bir DataTable'a bağlı olmayan DataGrid'den veri okunamaz. - - - - Returns the vertical scroll bar used by the grid. - Kılavuz tarafından kullanılan dikey kaydırma çubuğunu döndürür. - - Occurs when the value of the AlternatingRowsDefaultCellStyle property changes. AlternatingRowsDefaultCellStyle özelliğinin değeri değiştiğinde gerçekleşir. @@ -5657,21 +5172,11 @@ Bunu değiştirmek istiyor musunuz? Formun yeniden boyutlandırılabileceği en büyük boyut. - - The main menu of the form. This must be set to a component of type MainMenu. - Formun ana menüsü. MainMenu türünde bir bileşene ayarlanması gerekir. - - Specifies the primary MenuStrip for the Form. This property is used for keyboard activation and automatic merging in MDI. Form için birincil MenuStrip'i belirtir. Bu özellik MDI'da klavye etkinleştirme ve otomatik birleştirme için kullanılır. - - The merged menu of this form, which is used when displaying a single merged MDI menu. - Bu formun, tek bir birleşik MDI menüsü görüntülenirken kullanılan birleşik menüsü. - - Determines whether a form has a minimize box in the upper-right corner of its caption bar. Formda başlık çubuğunun sağ üst köşesinde simge durumuna küçültme kutusunun bulunup bulunmadığını belirler. @@ -7171,26 +6676,6 @@ Geçersiz işlemin gerçekleştiği yığın izi: Bu form için MdiParent olarak belirtilen form, bir MdiContainer değil. - - Occurs when the main menu collapses. - Ana menü daraltıldığında gerçekleşir. - - - - Gets or sets the ImageList associated with this main menu. - Bu ana menüyle ilişkili ImageList'i alır veya ayarlar. - - - - Gets or sets a value indicating whether the menu has an image margin. - Menüde resim kenar boşluğu olup olmadığını gösteren değeri alır veya ayarlar. - - - - <No Form> - <No Form> - - Indicates whether the prompt character is valid as input. İstem karakterinin giriş olarak geçerli olup olmadığını gösterir. @@ -7326,139 +6811,14 @@ Geçersiz işlemin gerçekleştiği yığın izi: Denetim odağı kaybettiğinde giriş metnini ayrıştırmak için kullanılacak nesnenin türünü belirtir. - - Parameter must be of type MenuItem. - Parametrenin MenuItem türünde olması gerekir. - - - - Gets or sets the background color of this menu's image margin. - Bu menünün resim kenar boşluğunun arka plan rengini alır veya ayarlar. - - - - Indicates if this menu contains any child items. - Bu menünün alt öğe içerip içermediğini gösterir. - - - - Cannot add MenuItem '{0}'. It already exists as a parent of the current menu item. - MenuItem '{0}' eklenemiyor. Geçerli menü öğesinin üstü olarak zaten var. - - - - Indicates whether the item is checked. - Öğenin işaretli olup olmadığını gösterir. - - - - Indicates whether the item is the default item. - Öğenin varsayılan öğe olup olmadığını gösterir. - - - - Indicates whether the item is enabled. - Öğenin etkin olup olmadığını gösterir. - - - - Gets or sets the image to be displayed on this menu item. - Bu menü öğesinde görüntülenecek resmi alır veya ayarlar. - - - - Gets or sets the ImageList associated with this menu item. - Bu menü öğesiyle ilişkili ImageList'i alır veya ayarlar. - - - - Gets or sets the background color of this menu item's image margin. - Bu menü öğesinin resim kenar boşluğunun arka plan rengini alır veya ayarlar. - - - - True is not a valid value for the Checked property. This is only valid for MenuItems that have no children and are not top-level. - True, Checked özelliği için geçerli bir değer değil. Bu, yalnızca hiç alt öğesi bulunmayan ve en üst düzeyde olmayan MenuItem'lar için geçerlidir. - - - - Determines whether the MDI child window list is appended to this item. - MDI alt pencere listesinin bu öğenin sonuna eklenip eklenmediğini belirler. - - - - Determines the merge order of the item. - Öğenin birleştirme sırasını belirler. - - - - Determines how the item is handled when menus are merged. - Menüler birleştirildiğinde öğenin nasıl işlendiğini belirler. - - - - Occurs when the menu item is selected. - Menü öğesi seçildiğinde gerçekleşir. - - - - Occurs before the containing menu is displayed. - İçeren menü görüntülenmeden önce gerçekleşir. - - - - Occurs when the menu item is selected. - Menü öğesi seçildiğinde gerçekleşir. - - - - Indicates if Windows will draw the menu item or if the user will handle the painting. - Menü öğesinin Windows tarafından mı çizileceğini yoksa boyama işini kullanıcının mı yapacağını gösterir. - - - - If the item is checked, this value will determine whether the check style is a radio button. - Öğe işaretliyse, bu değer işaret stilinin radyo düğmesi olup olmadığını belirler. - - The shortcut key associated with the menu item. - Menü öğesiyle ilişkili kısayol tuşu. + The shortcut key associated with the menu item. Indicates whether the shorcut key for the menu item is displayed on the item. - Menü öğesinin kısayolunun öğede görüntülenip görüntülenmeyeceğini gösterir. - - - - The caption displayed by the item. - Öğe tarafından görüntülenen başlık. - - - - Indicates whether the item is visible. - Öğenin görünür olup olmadığını gösterir. - - - - Retrieves the menu item that contains a list of MDI child windows. - MDI alt pencereleri listesi içeren menü öğesini alır. - - - - The menu items for the menu. - Menüdeki menü öğeleri. - - - - Cannot merge a menu with itself. - Menü kendisiyle birleştirilemez. - - - - Indicates if this menu should display right to left - Bu menünün sağdan sola görüntülenip görüntülenmeyeceğini gösterir + Indicates whether the shorcut key for the menu item is displayed on the item. @@ -9976,136 +9336,6 @@ Geçersiz işlemin gerçekleştiği yığın izi: Çok fazla sayıda ResumeUpdateMenuHandles çağrısı. - - Controls the appearance of the ToolBar control, using values from the ToolBarAppearance enumeration. - ToolBarAppearance numaralandırmasındaki değerleri kullanarak ToolBar denetiminin görünümünü denetler. - - - - Controls whether the ToolBar will automatically size itself based on Button size. - Araç Çubuğu'nun Düğme boyutuna bağlı olarak kendi kendini otomatik olarak boyutlandırıp boyutlandıramayacağını denetler. - - - - Parameter must be of type ToolBarButton. - Parametrenin ToolBarButton türünde olması gerekir. - - - - Controls what type of border the ToolBar control will have. - ToolBar denetiminin ne tür kenarlığı olacağını denetler. - - - - Occurs whenever a button in the ToolBar is clicked by the user. - Araç Çubuğu'ndaki bir düğme kullanıcı tarafından her tıklatıldığında gerçekleşir. - - - - Occurs whenever a button with the DropDownButton style is pressed. - DropDownButton stilindeki bir düğmeye her basıldığında gerçekleşir. - - - - Controls whether this button responds to user input. - Bu düğmenin kullanıcı girişini yanıtlayıp yanıtlayamayacağını denetler. - - - - Identifies the image displayed on the button. - Düğmede görüntülenen resmi tanımlar. - - - - The drop-down menu for a ToolBarButton must be of type ContextMenu. - ToolBarButton'ın açılan menüsü ContextMenu türünde olmalı. - - - - The shortcut menu that will appear if this button's style is set to DropDownButton. - Bu düğmenin stili DropDownButton olarak ayarlandığında görünecek olan kısayol menüsü. - - - - References that a non-existent ToolBarButton has been received. - Varolmayan bir ToolBarButton alındığını gösterir. - - - - Controls whether the button should be displayed as partially pushed or not, but only if the style of the button is ToggleButton. - Düğmenin kısmen basılı olarak görüntülenip görüntülenmeyeceğini denetler, ancak yalnızca düğme stili ToggleButton ise uygulanabilir. - - - - Indicates whether the button is pushed or not. This is most commonly seen for buttons with the TOGGLEBUTTON style. - Düğmenin basılı olup olmadığını gösterir. Bu, genellikle stili TOGGLEBUTTON olan düğmelerde görülür. - - - - The size of the buttons on the control if the button contents do not require a larger size. - Düğme içerikleri daha büyük bir boyut gerektirmezse düğmelerin boyutu. - - - - Indicates what style of ToolBarButton this will be. - Bu ToolBarButton'ın hangi stilde olacağını gösterir. - - - - The caption to be displayed for this button. - Bu düğme için görüntülenecek başlık. - - - - The ToolTip text to be displayed for this button. - Bu düğme için görüntülenecek ToolTip metni. - - - - Indicates whether this button should be visible. - Bu düğmenin görünür olup olmayacağını gösterir. - - - - The collection of ToolBarButtons that make up this ToolBar. - Bu ToolBar'ı oluşturan ToolBarButton koleksiyonu. - - - - Controls whether the ToolBar will display a 3-D line at the top of its client area. - ToolBar'ın istemci alanının üstünde 3 boyutlu çizgi görüntülenip görüntülenmeyeceğini denetler. - - - - Controls whether the ToolBar will display an arrow on the side of drop-down buttons. - ToolBar'ın açılır düğmelerinin yanında ok görüntülenip görüntülenmeyeceğini denetler. - - - - The ImageList from which this ToolBar will get all of the button images. - Bu ToolBar'ın tüm düğme resimlerini alacağı ImageList. - - - - The size of the images within the ToolBar's ImageList. - ToolBar'ın ImageList'indeki resimlerin boyutu. - - - - Indicates whether ToolTips will be shown for each of the buttons, if available. - Her bir düğme için ToolTip'lerin (varsa) gösterilip gösterilmeyeceğini belirler. - - - - Controls how the text is positioned relative to the Image in each button. - Metnin her düğmedeki Resme göre nasıl yerleştirileceğini denetler. - - - - Indicates if more than one row of buttons is allowed. - Birden fazla düğme satırına izin verilip verilmeyeceğini gösterir. - - AllowItemReorder and AllowDrop cannot both be true. Hem AllowItemReorder hem de AllowDrop True olamaz. diff --git a/src/System.Windows.Forms/src/Resources/xlf/SR.zh-Hans.xlf b/src/System.Windows.Forms/src/Resources/xlf/SR.zh-Hans.xlf index 063940c042d..43b38b324ab 100644 --- a/src/System.Windows.Forms/src/Resources/xlf/SR.zh-Hans.xlf +++ b/src/System.Windows.Forms/src/Resources/xlf/SR.zh-Hans.xlf @@ -1217,34 +1217,9 @@ 此容器控件的父窗体。 - - Raised when the context menu collapses. - 在上下文菜单折叠时引发。 - - - - Gets or sets the ImageList associated with this context menu. - 获取或设置与此上下文菜单关联的 ImageList。 - - - - ContextMenu cannot be shown on an invisible control. - ContextMenu 无法在不可见的控件上显示。 - - - - Gets or sets a value indicating whether the menu has an image margin. - 获取或设置指示菜单是否有图像边距的值。 - - - - The last control that caused this context menu to be displayed. - 使此上下文菜单显示的最后一个控件。 - - The last control that caused this context menu strip to be displayed. - 使该上下文菜单条显示的最后一个控件。 + The last control that caused this context menu strip to be displayed. @@ -2107,466 +2082,6 @@ 属性到属性的绑定不支持 RemoveAt。 - - Indicates whether the grid can be re-sorted by clicking a column header. - 指示是否可以通过单击列标头对网格进行重新排序。 - - - - Indicates the background color of alternating rows for a ledger appearance. - 指示帐目型外观交替行的背景色。 - - - - Occurs when the user clicks the Back button on a child table to return to the parent table. - 在用户单击子表上的“后退”按钮以返回到父表时发生。 - - - - Indicates the color of the DataGrid background. - 指示 DataGrid 的背景色。 - - - - BeginInit() has already been called without an EndInit(). - 已调用 BeginInit(),但没有 EndInit()。 - - - - Specifies whether the DataGridBoolColumn allows null values. - 指定 DataGridBoolColumn 是否允许 null。 - - - - Indicates the border style for the DataGrid. - 指示 DataGrid 的边框样式。 - - - - Navigates back to the parent rows. - 向后定位到父行。 - - - - Indicates the background color of the top caption. - 指示顶部标题的背景色。 - - - - Shows/Hides the parent rows for the current set of child rows. - 显示/隐藏当前子行集的父行。 - - - - Indicates the font of the top caption. - 指示顶部标题的字体。 - - - - Indicates the color of text that appears in the top caption. - 指示顶部标题中所显示文本的颜色。 - - - - Indicates the text displayed in the top caption. - 指示顶部标题中所显示的文本。 - - - - Indicates whether the top caption is visible. - 指示顶部标题是否可见。 - - - - DataGridColumn instance does not exist in the collection. - 集合中不存在 DataGridColumn 实例。 - - - - Indicates whether the column headers are visible. - 指示列标头是否可见。 - - - - Position of ListManager must be equal to 'rowNum'. - ListManager 的位置必须等于“rowNum”。 - - - - PropertyDescriptor has not been set on this DataGridColumn. - 尚未在此 DataGridColumn 上设置 PropertyDescriptor。 - - - - Data grid column styles collection already contains a column style with the same mapping name. - 数据网格列样式集合已包含具有同一映射名称的列样式。 - - - - DataGridColumnStyle of '{0}' cannot be used because it is not associated with a Property or Column in the DataSource. - “{0}”的 DataGridColumnStyle 不与 DataSource 中的属性或列关联,因此无法使用。 - - - - ColumnWidth must be greater than or equal to 0. - ColumnWidth 必须大于或等于 0。 - - - - The currently selected cell in the DataGrid. - DataGrid 中当前选定的单元格。 - - - - Indicates a sub-list of the DataSource to show in the DataGrid. - 指示要在 DataGrid 中显示的 DataSource 子列表。 - - - - Indicates the source of data for the DataGrid. - 指示 DataGrid 的数据源。 - - - - User cannot change the contents of the default GridColumnStylesCollection. - 用户不能更改默认 GridColumnStylesCollection 的内容。 - - - - Value of this property cannot be changed on the default DataGridTableStyle. - 不能更改默认 DataGridTableStyle 的此属性的值。 - - - - Occurs when the user clicks the "show/hide parent rows" icon. - 在用户单击“显示/隐藏父行”图标时发生。 - - - - Value '{0}' cannot be set to an empty value. - 不能将值“{0}”设置为空值。 - - - - Committing the row to the original data store has caused an error. - 向原始数据存储区提交行导致错误发生。 - - - - DataGrid received an exception at design time. Reset the DataSource and DataMember property on the grid. - DataGrid 在设计时收到异常。请重置网格的 DataSource 和 DataMember 属性。 - - - - Program cannot get information about the painting and scrolling region. - 程序无法获取有关绘图和滚动区域的信息。 - - - - Indicates the index of the column that is first shown. - 指示首先显示的列的索引。 - - - - Indicates whether the grid has a flat appearance. - 指示网格的外观是否为平面。 - - - - Indicates the color of the grid lines. - 指示网格线的颜色。 - - - - Indicates the style of the grid lines. - 指示网格线的样式。 - - - - The collection of DataGridTableStyle objects that the DataGrid can render its data with. - DataGrid 呈现自己的数据时使用的 DataGridTableStyle 对象的集合。 - - - - Indicates the background color of the column and row headers. - 指示列和行标头的背景色。 - - - - Indicates the font of the text in the column and row headers. - 指示列和行标头中文本的字体。 - - - - Indicates the color of the text in the column and row headers. - 指示列和行标头中文本的颜色。 - - - - Returns the horizontal scroll bar used by the grid. - 返回网格所使用的水平滚动条。 - - - - Indicates the color of the text that appears inside the child links. - 指示出现在子链接内的文本的颜色。 - - - - Indicates the color of the text that appears inside a child link when the mouse pointer moves over it. - 指示在鼠标指针移过子链接时子链接内显示的文本的颜色。 - - - - The CurrencyManager that the DataGrid uses to get data from the data source. - DataGrid 用于从数据源中获取数据的 CurrencyManager。 - - - - Occurs when the user navigates to the child rows or when the user navigates back to the parent rows. - 在用户定位到子行时或者在用户向后定位到父行时发生。 - - - - Indicates whether links to child tables are shown. - 指示是否显示到子表的链接。 - - - - Occurs when the user clicks on the expansion glyph on the row header. - 在用户单击行标头上的扩展标志符号时发生。 - - - - (null) - (null) - - - - Event raised when the value of the BackgroundColor property is changed on DataGrid. - 在 DataGrid 的 BackgroundColor 属性值更改时引发的事件。 - - - - Event raised when the value of the BorderStyle property is changed on DataGrid. - 在 DataGrid 的 BorderStyle 属性值更改时引发的事件。 - - - - Event raised when the value of the CaptionVisible property is changed on DataGrid. - 在 DataGrid 的 CaptionVisible 属性值更改时引发的事件。 - - - - Event raised when the value of the CurrentCell property is changed on DataGrid. - 在更改 DataGrid 上 CurrentCell 属性的值时激发的事件。 - - - - Event raised when the value of the DataSource property is changed on DataGrid. - 在 DataGrid 的 DataSource 属性值更改时引发的事件。 - - - - Event raised when the value of the FlatMode property is changed on DataGrid. - 在更改 DataGrid 上 FlatMode 属性值时引发的事件。 - - - - Event raised when the value of the NavigationMode property is changed on DataGrid. - 在 DataGrid 的 NavigationMode 属性值更改时引发的事件。 - - - - Event raised when the value of the ParentRowsLabelStyle property is changed on DataGrid. - 在 DataGrid 的 ParentRowsLabelStyle 属性值更改时引发的事件。 - - - - Event raised when the value of the ParentRowsVisible property is changed on DataGrid. - 在 DataGrid 的 ParentRowsVisible 属性值更改时引发的事件。 - - - - Event raised when the value of the ReadOnly property is changed on DataGrid. - 在 DataGrid 的 ReadOnly 属性值更改时引发的事件。 - - - - Indicates the background color of the parent rows. - 指示父行的背景色。 - - - - Indicates the color of the text in the parent rows. - 指示父行中文本的颜色。 - - - - Indicates whether the parent rows show labels for the table and for the columns. - 指示父行是否显示表和列的标签。 - - - - Indicates whether the parent rows area is visible. - 指示父行区域是否可见。 - - - - Specifies what the default pixel widths of the grid columns are. The default value for PreferredColumnWidth is 75. - 指定网格列的默认像素宽度。PreferredColumnWidth 的默认值为 75。 - - - - Indicates the preferred height of the rows. - 指示行的首选高度。 - - - - Value {0} Do you want to correct this value? - 值 {0}。是否更正此值? - - - - Indicates whether rows in the grid can be edited, added, or deleted. - 指示是否可以编辑、添加或删除网格中的行。 - - - - Indicates the width of the row headers. - 指示行标头的宽度。 - - - - Indicates whether the row headers are visible. - 指示行标头是否可见。 - - - - DataGridRow.Height cannot be negative. - DataGridRow.Height 不能为负。 - - - - DataGridRow cannot have a negative row number. - DataGridRow 的行号不能为负。 - - - - Occurs when the user scrolls either the horizontal or vertical scroll bar. - 在用户滚动水平滚动条或垂直滚动条时发生。 - - - - Indicates the index of the current row. - 指示当前行的索引。 - - - - Indicates the background color of any selected cells or rows. - 指示任意选定单元格或行的背景色。 - - - - Indicates the color of the text in any selected cells or rows. - 指示任意选定单元格或行中文本的颜色。 - - - - ListManager can be set using the DataSource and DataMember properties. - 可以用 DataSource 和 DataMember 属性来设置 ListManager。 - - - - Position on a null ListManager cannot be set. - 不能在空 ListManager 上设置位置。 - - - - CurrentCell cannot be set at this time. Moving your code to the Form.Load event should solve this problem. - 此时无法设置 CurrentCell。将代码移到 Form.Load 事件应该可以解决此问题。 - - - - DataGridTable instance does not exist in the collection. - 集合中不存在 DataGridTable 实例。 - - - - DataGridTableStyle that is already parented to another DataGrid cannot be added. - 无法添加已经成为另一个 DataGrid 的父级的 DataGridTableStyle。 - - - - Data grid table styles collection already contains a table style with the same mapping name. - 数据网格表样式集合已包含具有同一映射名称的表样式。 - - - - DataGridTableStyle does not support transparent AlternatingBackColor. - DataGridTableStyle 不支持透明的 AlternatingBackColor。 - - - - DataGridTableStyle does not support transparent BackColor. - DataGridTableStyle 不支持透明的 BackColor。 - - - - DataGridTableStyle does not support transparent HeaderBackColor. - DataGridTableStyle 不支持透明的 HeaderBackColor。 - - - - DataGridTableStyle does not support transparent SelectionBackColor. - DataGridTableStyle 不支持透明的 SelectionBackColor。 - - - - null rectangle for icon bounds when adding tool tip. - 当添加工具提示时,图标边界矩形为空。 - - - - DataGrid control does not support transparent AlternatingBackColor. - DataGrid 控件不支持透明的 AlternatingBackColor。 - - - - DataGrid control does not support transparent BackColor. - DataGrid 控件不支持透明的 BackColor。 - - - - DataGrid control does not support transparent CaptionBackColor. - DataGrid 控件不支持透明的 CaptionBackColor。 - - - - DataGrid control does not support transparent HeaderBackColor. - DataGrid 控件不支持透明的 HeaderBackColor。 - - - - DataGrid control does not support transparent ParentRowsBackColor. - DataGrid 控件不支持透明的 ParentRowsBackColor。 - - - - DataGrid control does not support transparent SelectionBackColor. - DataGrid 控件不支持透明的 SelectionBackColor。 - - - - Data cannot be read from a DataGrid which is not bound to a DataTable. - 无法从未绑定到 DataTable 的 DataGrid 中读取数据。 - - - - Returns the vertical scroll bar used by the grid. - 返回网格所使用的垂直滚动条。 - - Occurs when the value of the AlternatingRowsDefaultCellStyle property changes. AlternatingRowsDefaultCellStyle 属性值更改时发生。 @@ -5657,21 +5172,11 @@ Do you want to replace it? 窗体可以调整到的最大大小。 - - The main menu of the form. This must be set to a component of type MainMenu. - 窗体的主菜单。必须设置为 MainMenu 类型的组件。 - - Specifies the primary MenuStrip for the Form. This property is used for keyboard activation and automatic merging in MDI. 为窗体指定主 MenuStrip。此属性用于键盘激活和 MDI 中的自动合并。 - - The merged menu of this form, which is used when displaying a single merged MDI menu. - 此窗体的合并菜单,它在显示单个合并的 MDI 菜单时使用。 - - Determines whether a form has a minimize box in the upper-right corner of its caption bar. 确定窗体标题栏的右上角是否有最小化框。 @@ -7171,26 +6676,6 @@ Stack trace where the illegal operation occurred was: 被指定为此窗体的 MdiParent 的窗体不是 MdiContainer。 - - Occurs when the main menu collapses. - 当主菜单折叠时发生。 - - - - Gets or sets the ImageList associated with this main menu. - 获取或设置与此主菜单关联的 ImageList。 - - - - Gets or sets a value indicating whether the menu has an image margin. - 获取或设置指示菜单是否有图像边距的值。 - - - - <No Form> - <No Form> - - Indicates whether the prompt character is valid as input. 指示提示字符是否为有效输入。 @@ -7326,139 +6811,14 @@ Stack trace where the illegal operation occurred was: 指定当控件失去焦点时用于分析输入文本的对象的类型。 - - Parameter must be of type MenuItem. - 参数必须是 MenuItem 类型。 - - - - Gets or sets the background color of this menu's image margin. - 获取或设置此菜单的图像边距的背景颜色。 - - - - Indicates if this menu contains any child items. - 指示此菜单是否包含任何子项。 - - - - Cannot add MenuItem '{0}'. It already exists as a parent of the current menu item. - 无法添加 MenuItem“{0}”。它已经作为当前菜单项的父级存在。 - - - - Indicates whether the item is checked. - 指示该项是否已选中。 - - - - Indicates whether the item is the default item. - 指示该项是否是默认项。 - - - - Indicates whether the item is enabled. - 指示该项是否已启用。 - - - - Gets or sets the image to be displayed on this menu item. - 获取或设置要在此菜单项上显示的图像。 - - - - Gets or sets the ImageList associated with this menu item. - 获取或设置与此菜单项关联的 ImageList。 - - - - Gets or sets the background color of this menu item's image margin. - 获取或设置此菜单项的图像边距的背景颜色。 - - - - True is not a valid value for the Checked property. This is only valid for MenuItems that have no children and are not top-level. - True 不是 Checked 属性的有效值。 它仅对于无子级且不是顶级的 MenuItem 有效。 - - - - Determines whether the MDI child window list is appended to this item. - 确定是否将 MDI 子窗口列表追加到此项。 - - - - Determines the merge order of the item. - 确定该项的合并顺序。 - - - - Determines how the item is handled when menus are merged. - 确定在合并菜单时如何处理该项。 - - - - Occurs when the menu item is selected. - 在选中菜单项时发生。 - - - - Occurs before the containing menu is displayed. - 在显示包含菜单前发生。 - - - - Occurs when the menu item is selected. - 在选中菜单项时发生。 - - - - Indicates if Windows will draw the menu item or if the user will handle the painting. - 指示是由 Windows 来绘制该菜单项,还是由用户来完成这一绘制任务。 - - - - If the item is checked, this value will determine whether the check style is a radio button. - 如果选中该项,则此值确定选择样式是否是单选按钮。 - - The shortcut key associated with the menu item. - 与菜单项关联的快捷键。 + The shortcut key associated with the menu item. Indicates whether the shorcut key for the menu item is displayed on the item. - 指示是否在该项上显示菜单项的快捷键。 - - - - The caption displayed by the item. - 由该项显示的标题。 - - - - Indicates whether the item is visible. - 指示该项是否可见。 - - - - Retrieves the menu item that contains a list of MDI child windows. - 检索包含 MDI 子窗口列表的菜单项。 - - - - The menu items for the menu. - 菜单的菜单项。 - - - - Cannot merge a menu with itself. - 无法将菜单与其自身合并。 - - - - Indicates if this menu should display right to left - 指示此菜单是否应按从右到左的顺序显示 + Indicates whether the shorcut key for the menu item is displayed on the item. @@ -9976,136 +9336,6 @@ Stack trace where the illegal operation occurred was: 对 ResumeUpdateMenuHandles 的调用过多。 - - Controls the appearance of the ToolBar control, using values from the ToolBarAppearance enumeration. - 使用 ToolBarAppearance 枚举中的值来控制 ToolBar 控件的外观。 - - - - Controls whether the ToolBar will automatically size itself based on Button size. - 控制工具栏是否根据按钮大小自动调整自身的大小。 - - - - Parameter must be of type ToolBarButton. - 参数必须是 ToolBarButton 类型。 - - - - Controls what type of border the ToolBar control will have. - 控制工具栏控件将具有的边框类型。 - - - - Occurs whenever a button in the ToolBar is clicked by the user. - 每当用户单击 ToolBar 中的按钮时发生。 - - - - Occurs whenever a button with the DropDownButton style is pressed. - 每当按下具有 DropDownButton 样式的按钮时发生。 - - - - Controls whether this button responds to user input. - 控制此按钮是否响应用户输入。 - - - - Identifies the image displayed on the button. - 标识按钮上显示的图像。 - - - - The drop-down menu for a ToolBarButton must be of type ContextMenu. - ToolBarButton 的下拉菜单的类型必须为 ContextMenu。 - - - - The shortcut menu that will appear if this button's style is set to DropDownButton. - 当此按钮的样式设置为 DropDownButton 时将显示的快捷菜单。 - - - - References that a non-existent ToolBarButton has been received. - 接收到对不存在的 ToolBarButton 的引用。 - - - - Controls whether the button should be displayed as partially pushed or not, but only if the style of the button is ToggleButton. - 控制该按钮是否应显示为部分下压,但这仅适用于样式为 ToggleButton 的按钮。 - - - - Indicates whether the button is pushed or not. This is most commonly seen for buttons with the TOGGLEBUTTON style. - 指示按钮是否是下压的。这常见于样式为 TOGGLEBUTTON 的按钮。 - - - - The size of the buttons on the control if the button contents do not require a larger size. - 按钮内容不需要更大大小时控件上的按钮的大小。 - - - - Indicates what style of ToolBarButton this will be. - 指示它将成为何种样式的 ToolBarButton。 - - - - The caption to be displayed for this button. - 此按钮将要显示的标题。 - - - - The ToolTip text to be displayed for this button. - 要为此按钮显示的 ToolTip 文本。 - - - - Indicates whether this button should be visible. - 指示此按钮是否应为可见。 - - - - The collection of ToolBarButtons that make up this ToolBar. - 组成此 ToolBar 的 ToolBarButtons 集合。 - - - - Controls whether the ToolBar will display a 3-D line at the top of its client area. - 控制工具栏是否在其工作区的顶部显示三维线。 - - - - Controls whether the ToolBar will display an arrow on the side of drop-down buttons. - 控制工具栏是否在下拉按钮旁边显示一个箭头。 - - - - The ImageList from which this ToolBar will get all of the button images. - 此 ToolBar 将从中获取所有按钮图像的 ImageList。 - - - - The size of the images within the ToolBar's ImageList. - 工具栏的 ImageList 内的图像的大小。 - - - - Indicates whether ToolTips will be shown for each of the buttons, if available. - 指示是否为每个按钮显示工具提示(如果有的话)。 - - - - Controls how the text is positioned relative to the Image in each button. - 控制如何相对于每一按钮中的图像来定位文本。 - - - - Indicates if more than one row of buttons is allowed. - 指示是否允许多行按钮。 - - AllowItemReorder and AllowDrop cannot both be true. AllowItemReorder 和 AllowDrop 不能同时为 True。 diff --git a/src/System.Windows.Forms/src/Resources/xlf/SR.zh-Hant.xlf b/src/System.Windows.Forms/src/Resources/xlf/SR.zh-Hant.xlf index 49c1c6f74c1..40516134516 100644 --- a/src/System.Windows.Forms/src/Resources/xlf/SR.zh-Hant.xlf +++ b/src/System.Windows.Forms/src/Resources/xlf/SR.zh-Hant.xlf @@ -1217,34 +1217,9 @@ 此容器控制項的父表單。 - - Raised when the context menu collapses. - 在內容功能表摺疊時引發。 - - - - Gets or sets the ImageList associated with this context menu. - 取得或設定與此內容功能表相關的 ImageList。 - - - - ContextMenu cannot be shown on an invisible control. - 無法在不可見的控制項上顯示 ContextMenu。 - - - - Gets or sets a value indicating whether the menu has an image margin. - 取得或設定用來指示功能表是否有影像邊界的值。 - - - - The last control that caused this context menu to be displayed. - 造成顯示此內容功能表的最後控制項。 - - The last control that caused this context menu strip to be displayed. - 造成顯示此內容功能表區域的最後控制項。 + The last control that caused this context menu strip to be displayed. @@ -2107,466 +2082,6 @@ 屬性間的繫結不支援 RemoveAt。 - - Indicates whether the grid can be re-sorted by clicking a column header. - 表示是否按一下資料行行首就可以重新排序方格。 - - - - Indicates the background color of alternating rows for a ledger appearance. - 表示總帳外觀交替資料列的背景色彩。 - - - - Occurs when the user clicks the Back button on a child table to return to the parent table. - 使用者按一下子資料表的 [上一頁] 按鈕返回父資料表時發生。 - - - - Indicates the color of the DataGrid background. - 表示 DataGrid 背景的色彩。 - - - - BeginInit() has already been called without an EndInit(). - 在沒有 EndInit() 的情況下呼叫 BeginInit()。 - - - - Specifies whether the DataGridBoolColumn allows null values. - 指定 DataGridBoolColumn 是否允許 null 值。 - - - - Indicates the border style for the DataGrid. - 表示 DataGrid 的框線樣式。 - - - - Navigates back to the parent rows. - 向後巡覽至父資料列。 - - - - Indicates the background color of the top caption. - 表示上方標題的背景色彩。 - - - - Shows/Hides the parent rows for the current set of child rows. - 顯示/隱藏目前子資料列集的父資料列。 - - - - Indicates the font of the top caption. - 表示上方標題的字型。 - - - - Indicates the color of text that appears in the top caption. - 表示出現在上方標題的文字色彩。 - - - - Indicates the text displayed in the top caption. - 表示出現在上方標題的文字。 - - - - Indicates whether the top caption is visible. - 表示上方標題是否可見。 - - - - DataGridColumn instance does not exist in the collection. - DataGridColumn 執行個體不存在於此集合。 - - - - Indicates whether the column headers are visible. - 表示資料行行首是否為可見。 - - - - Position of ListManager must be equal to 'rowNum'. - ListManager 的位置必須等於 'rowNum'。 - - - - PropertyDescriptor has not been set on this DataGridColumn. - 尚未在此 DataGridColumn 上設定 PropertyDescriptor。 - - - - Data grid column styles collection already contains a column style with the same mapping name. - 資料格資料行樣式集合已經包含擁有相同對應名稱的資料行樣式。 - - - - DataGridColumnStyle of '{0}' cannot be used because it is not associated with a Property or Column in the DataSource. - 因為其與 DataSource 中的屬性或資料行沒有關聯,所以 '{0}' 的 DataGridColumnStyle 無法使用。 - - - - ColumnWidth must be greater than or equal to 0. - ColumnWidth 必須大於或等於 0。 - - - - The currently selected cell in the DataGrid. - 目前 DataGrid 中所選取的儲存格。 - - - - Indicates a sub-list of the DataSource to show in the DataGrid. - 表示要在 DataGrid 中顯示的 DataSource 子清單。 - - - - Indicates the source of data for the DataGrid. - 表示 DataGrid 的資料來源。 - - - - User cannot change the contents of the default GridColumnStylesCollection. - 使用者無法變更預設 GridColumnStylesCollection 的內容。 - - - - Value of this property cannot be changed on the default DataGridTableStyle. - 此屬性的值無法在預設 DataGridTableStyle 上變更。 - - - - Occurs when the user clicks the "show/hide parent rows" icon. - 使用者按一下 [顯示/隱藏父資料列] 圖示時發生。 - - - - Value '{0}' cannot be set to an empty value. - 無法將值 '{0}' 設為空值。 - - - - Committing the row to the original data store has caused an error. - 認可原始資料存放區的資料列造成錯誤。 - - - - DataGrid received an exception at design time. Reset the DataSource and DataMember property on the grid. - DataGrid 在設計階段收到例外狀況。請重設方格上的 DataSource 和 DataMember 屬性。 - - - - Program cannot get information about the painting and scrolling region. - 程式無法取得繪製和捲動區域的相關資訊。 - - - - Indicates the index of the column that is first shown. - 表示第一個出現的資料行索引。 - - - - Indicates whether the grid has a flat appearance. - 表示方格是否有平面外觀。 - - - - Indicates the color of the grid lines. - 表示格線的色彩。 - - - - Indicates the style of the grid lines. - 表示格線的樣式。 - - - - The collection of DataGridTableStyle objects that the DataGrid can render its data with. - DataGrid 可用來呈現其資料的 DataGridTableStyle 物件集合。 - - - - Indicates the background color of the column and row headers. - 表示資料行和資料列行首的背景色彩。 - - - - Indicates the font of the text in the column and row headers. - 表示資料行和資料列行首文字的字型。 - - - - Indicates the color of the text in the column and row headers. - 表示資料行和資料列行首文字的色彩。 - - - - Returns the horizontal scroll bar used by the grid. - 傳回方格所使用的水平捲軸。 - - - - Indicates the color of the text that appears inside the child links. - 表示顯示於子連結內部文字的色彩。 - - - - Indicates the color of the text that appears inside a child link when the mouse pointer moves over it. - 表示滑鼠指標移到子連結時,其內部顯示的文字色彩。 - - - - The CurrencyManager that the DataGrid uses to get data from the data source. - DataGrid 從資料來源取得資料所使用的 CurrencyManager。 - - - - Occurs when the user navigates to the child rows or when the user navigates back to the parent rows. - 當使用者巡覽至子資料列或巡覽回父資料列時發生。 - - - - Indicates whether links to child tables are shown. - 表示是否顯示子資料表的連結。 - - - - Occurs when the user clicks on the expansion glyph on the row header. - 當使用者按下資料列行首的展開圖像時發生。 - - - - (null) - (null) - - - - Event raised when the value of the BackgroundColor property is changed on DataGrid. - BackgroundColor 屬性值在 DataGrid 上變更時引發的事件。 - - - - Event raised when the value of the BorderStyle property is changed on DataGrid. - BorderStyle 屬性值在 DataGrid 上變更時引發的事件。 - - - - Event raised when the value of the CaptionVisible property is changed on DataGrid. - CaptionVisible 屬性值在 DataGrid 上變更時引發的事件。 - - - - Event raised when the value of the CurrentCell property is changed on DataGrid. - CurrentCell 屬性值在 DataGrid 上變更時引發的事件。 - - - - Event raised when the value of the DataSource property is changed on DataGrid. - DataSource 屬性值在 DataGrid 上變更時引發的事件。 - - - - Event raised when the value of the FlatMode property is changed on DataGrid. - FlatMode 屬性值在 DataGrid 上變更時引發的事件。 - - - - Event raised when the value of the NavigationMode property is changed on DataGrid. - NavigationMode 屬性值在 DataGrid 上變更時引發的事件。 - - - - Event raised when the value of the ParentRowsLabelStyle property is changed on DataGrid. - ParentRowsLabelStyle 屬性值在 DataGrid 上變更時引發的事件。 - - - - Event raised when the value of the ParentRowsVisible property is changed on DataGrid. - ParentRowsVisible 屬性值在 DataGrid 上變更時引發的事件。 - - - - Event raised when the value of the ReadOnly property is changed on DataGrid. - ReadOnly 屬性值在 DataGrid 上變更時引發的事件。 - - - - Indicates the background color of the parent rows. - 表示父資料列的背景色彩。 - - - - Indicates the color of the text in the parent rows. - 表示父資料列中文字的色彩。 - - - - Indicates whether the parent rows show labels for the table and for the columns. - 表示父資料列是否顯示資料表與資料行的標籤。 - - - - Indicates whether the parent rows area is visible. - 表示父資料列區域是否為可見的。 - - - - Specifies what the default pixel widths of the grid columns are. The default value for PreferredColumnWidth is 75. - 指定方格資料行預設的像素寬度。PreferredColumnWidth 的預設值為 75。 - - - - Indicates the preferred height of the rows. - 表示資料列的慣用高度。 - - - - Value {0} Do you want to correct this value? - 值 {0} 您要更正這個值嗎? - - - - Indicates whether rows in the grid can be edited, added, or deleted. - 表示是否可以編輯、加入或刪除方格中的資料列。 - - - - Indicates the width of the row headers. - 表示資料列行首的寬度。 - - - - Indicates whether the row headers are visible. - 表示資料列行首是否可見。 - - - - DataGridRow.Height cannot be negative. - DataGridRow.Height 不能為負數。 - - - - DataGridRow cannot have a negative row number. - DataGridRow 不能有負的資料列編號。 - - - - Occurs when the user scrolls either the horizontal or vertical scroll bar. - 當使用者捲動水平或垂直捲軸時發生。 - - - - Indicates the index of the current row. - 表示目前資料列的索引。 - - - - Indicates the background color of any selected cells or rows. - 表示任何所選取儲存格或資料列的背景色彩。 - - - - Indicates the color of the text in any selected cells or rows. - 表示任何所選取儲存格或資料列中文字的色彩。 - - - - ListManager can be set using the DataSource and DataMember properties. - 可以使用 DataSource 與 DataMember 屬性來設定 ListManager。 - - - - Position on a null ListManager cannot be set. - 無法於 null 的 ListManager 上設定位置。 - - - - CurrentCell cannot be set at this time. Moving your code to the Form.Load event should solve this problem. - 此時無法設定 CurrentCell。將您的程式碼移至 Form.Load 事件中即可解決此問題。 - - - - DataGridTable instance does not exist in the collection. - DataGridTable 執行個體不存在於集合中。 - - - - DataGridTableStyle that is already parented to another DataGrid cannot be added. - 無法加入已經是其他 DataGrid 父項的 DataGridTableStyle。 - - - - Data grid table styles collection already contains a table style with the same mapping name. - 資料格資料表樣式集合已經包含擁有相同對應名稱的資料表樣式。 - - - - DataGridTableStyle does not support transparent AlternatingBackColor. - DataGridTableStyle 不支援透明 AlternatingBackColor。 - - - - DataGridTableStyle does not support transparent BackColor. - DataGridTableStyle 不支援透明 BackColor。 - - - - DataGridTableStyle does not support transparent HeaderBackColor. - DataGridTableStyle 不支援透明 HeaderBackColor。 - - - - DataGridTableStyle does not support transparent SelectionBackColor. - DataGridTableStyle 不支援透明 SelectionBackColor。 - - - - null rectangle for icon bounds when adding tool tip. - 加入工具提示時,圖示框線為 null 方框。 - - - - DataGrid control does not support transparent AlternatingBackColor. - DataGrid 控制項不支援透明 AlternatingBackColor。 - - - - DataGrid control does not support transparent BackColor. - DataGrid 控制項不支援透明 BackColor。 - - - - DataGrid control does not support transparent CaptionBackColor. - DataGrid 控制項不支援透明 CaptionBackColor。 - - - - DataGrid control does not support transparent HeaderBackColor. - DataGrid 控制項不支援透明 HeaderBackColor。 - - - - DataGrid control does not support transparent ParentRowsBackColor. - DataGrid 控制項不支援透明 ParentRowsBackColor。 - - - - DataGrid control does not support transparent SelectionBackColor. - DataGrid 控制項不支援透明 SelectionBackColor。 - - - - Data cannot be read from a DataGrid which is not bound to a DataTable. - 無法讀取未繫結至 DataTable 的 DataGrid 的資料。 - - - - Returns the vertical scroll bar used by the grid. - 傳回方格所使用的垂直捲軸。 - - Occurs when the value of the AlternatingRowsDefaultCellStyle property changes. AlternatingRowsDefaultCellStyle 屬性的值變更時發生。 @@ -5657,21 +5172,11 @@ Do you want to replace it? 可以重新調整表單的最大值。 - - The main menu of the form. This must be set to a component of type MainMenu. - 表單的主功能表。這必須設為類型 MainMenu 的元件。 - - Specifies the primary MenuStrip for the Form. This property is used for keyboard activation and automatic merging in MDI. 指定表單的主要 MenuStrip。此屬性可用於鍵盤啟用,以及 MDI 中的自動合併。 - - The merged menu of this form, which is used when displaying a single merged MDI menu. - 此表單的合併功能表,用於顯示單一合併的 MDI 功能表。 - - Determines whether a form has a minimize box in the upper-right corner of its caption bar. 決定表單在其標題列的右上角是否有最小化的方塊。 @@ -7171,26 +6676,6 @@ Stack trace where the illegal operation occurred was: 指定了不是 MdiContainer 的表單當做是該表單的 MdiParent 的表單。 - - Occurs when the main menu collapses. - 當主功能表摺疊時發生。 - - - - Gets or sets the ImageList associated with this main menu. - 取得或設定與此主功能表相關的 ImageList。 - - - - Gets or sets a value indicating whether the menu has an image margin. - 取得或設定用來指示功能表是否有影像邊界的值。 - - - - <No Form> - <No Form> - - Indicates whether the prompt character is valid as input. 表示提示字元是否可以當做有效輸入。 @@ -7326,139 +6811,14 @@ Stack trace where the illegal operation occurred was: 指定當控制項遺失焦點時,用來剖析輸入文字的物件類型。 - - Parameter must be of type MenuItem. - 參數必須屬於 MenuItem 類型。 - - - - Gets or sets the background color of this menu's image margin. - 取得或設定此功能表之影像邊界的背景色彩。 - - - - Indicates if this menu contains any child items. - 表示功能表是否包含任何子項目。 - - - - Cannot add MenuItem '{0}'. It already exists as a parent of the current menu item. - 無法加入 MenuItem '{0}'。它已經是目前功能表項目的父項。 - - - - Indicates whether the item is checked. - 表示是否已經選取項目。 - - - - Indicates whether the item is the default item. - 表示項目是否為預設項目。 - - - - Indicates whether the item is enabled. - 表示項目是否已啟用。 - - - - Gets or sets the image to be displayed on this menu item. - 取得或設定要顯示在此功能表項目上的影像。 - - - - Gets or sets the ImageList associated with this menu item. - 取得或設定與此功能表項目相關的 ImageList。 - - - - Gets or sets the background color of this menu item's image margin. - 取得或設定此功能表項目之影像邊界的背景色彩。 - - - - True is not a valid value for the Checked property. This is only valid for MenuItems that have no children and are not top-level. - True 不是 Checked 屬性的有效值。這只對沒有子系且非最上層的 MenuItems 有效。 - - - - Determines whether the MDI child window list is appended to this item. - 決定 MDI 子視窗清單是否附加至此項目。 - - - - Determines the merge order of the item. - 決定合併項目的順序。 - - - - Determines how the item is handled when menus are merged. - 決定合併功能表時如何處理項目。 - - - - Occurs when the menu item is selected. - 當選取功能表項目時發生。 - - - - Occurs before the containing menu is displayed. - 顯示包含功能表前發生。 - - - - Occurs when the menu item is selected. - 當選取功能表項目時發生。 - - - - Indicates if Windows will draw the menu item or if the user will handle the painting. - 表示 Windows 是否將繪製功能表項目或使用者是否將處理繪製。 - - - - If the item is checked, this value will determine whether the check style is a radio button. - 如果已核取項目,此值將決定核取樣式是否為選項按鈕。 - - The shortcut key associated with the menu item. - 與功能表項目相關的快速鍵。 + The shortcut key associated with the menu item. Indicates whether the shorcut key for the menu item is displayed on the item. - 表示是否將功能表項目的快速鍵顯示在該項目上。 - - - - The caption displayed by the item. - 項目顯示的標題。 - - - - Indicates whether the item is visible. - 表示項目是否為可見的。 - - - - Retrieves the menu item that contains a list of MDI child windows. - 擷取包含 MDI 子視窗清單的功能表項目。 - - - - The menu items for the menu. - 功能表的功能表項目。 - - - - Cannot merge a menu with itself. - 無法將功能表與其本身合併。 - - - - Indicates if this menu should display right to left - 表示此功能表是否應該由右至左顯示 + Indicates whether the shorcut key for the menu item is displayed on the item. @@ -9976,136 +9336,6 @@ Stack trace where the illegal operation occurred was: 太多的 ResumeUpdateMenuHandles 呼叫。 - - Controls the appearance of the ToolBar control, using values from the ToolBarAppearance enumeration. - 控制 ToolBar 控制項的外觀,使用來自 ToolBarAppearance 列舉型別的值。 - - - - Controls whether the ToolBar will automatically size itself based on Button size. - 控制工具列 (ToolBar) 是否會依照按鈕大小自動調整其大小。 - - - - Parameter must be of type ToolBarButton. - 參數必須屬於 ToolBarButton 類型。 - - - - Controls what type of border the ToolBar control will have. - 控制 ToolBar 控制項擁有的框線類型。 - - - - Occurs whenever a button in the ToolBar is clicked by the user. - 當使用者按下 ToolBar 中的按鈕時發生。 - - - - Occurs whenever a button with the DropDownButton style is pressed. - 當按住有 DropDownButton 樣式的按鈕時發生。 - - - - Controls whether this button responds to user input. - 控制此按鈕是否回應使用者的輸入。 - - - - Identifies the image displayed on the button. - 識別按鈕上顯示的影像。 - - - - The drop-down menu for a ToolBarButton must be of type ContextMenu. - ToolBarButton 的下拉式功能表必須屬於 ContextMenu 類型。 - - - - The shortcut menu that will appear if this button's style is set to DropDownButton. - 將此按鈕的樣式設為 DropDownButton 時會顯示的捷徑功能表。 - - - - References that a non-existent ToolBarButton has been received. - 參考已收到的非現存 ToolBarButton。 - - - - Controls whether the button should be displayed as partially pushed or not, but only if the style of the button is ToggleButton. - 控制按鈕是否應顯示為部分壓下,但僅適用於按鈕的樣式為 ToggleButton。 - - - - Indicates whether the button is pushed or not. This is most commonly seen for buttons with the TOGGLEBUTTON style. - 表示是否按下按鈕。這些按鈕最常見的樣式為 TOGGLEBUTTON。 - - - - The size of the buttons on the control if the button contents do not require a larger size. - 按鈕內容不需要更大的大小時,控制項上按鈕的大小。 - - - - Indicates what style of ToolBarButton this will be. - 表示將會是何種 ToolBarButton 樣式。 - - - - The caption to be displayed for this button. - 此按鈕所顯示的標題。 - - - - The ToolTip text to be displayed for this button. - 此按鈕所顯示的 ToolTip 文字。 - - - - Indicates whether this button should be visible. - 表示此按鈕是否可見。 - - - - The collection of ToolBarButtons that make up this ToolBar. - 組成這個 ToolBar 的 ToolBarButtons 集合物件。 - - - - Controls whether the ToolBar will display a 3-D line at the top of its client area. - 控制工具列是否要在其工作區的頂端顯示立體線段。 - - - - Controls whether the ToolBar will display an arrow on the side of drop-down buttons. - 控制工具列是否要在下拉按鈕旁顯示箭頭。 - - - - The ImageList from which this ToolBar will get all of the button images. - 這個 ToolBar 用來取得所有按鈕影像的 ImageList。 - - - - The size of the images within the ToolBar's ImageList. - 工具列的 ImageList 中的影像大小。 - - - - Indicates whether ToolTips will be shown for each of the buttons, if available. - 表示是否顯示每個按鈕的工具提示 (如果有)。 - - - - Controls how the text is positioned relative to the Image in each button. - 控制每個按鈕中與影像相關的文字位置。 - - - - Indicates if more than one row of buttons is allowed. - 表示是否允許一列以上的按鈕。 - - AllowItemReorder and AllowDrop cannot both be true. AllowItemReorder 和 AllowDrop 不能同時為 true。 diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs b/src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs index 2e93bc35da5..8733a7734d7 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs @@ -426,20 +426,6 @@ public override Cursor Cursor } } - [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override ContextMenu ContextMenu - { - get - { - return base.ContextMenu; - } - - set - { - base.ContextMenu = value; - } - } - /// /// Deriving classes can override this to configure a default size for their control. /// This is more efficient than setting the size in the control's constructor. @@ -670,13 +656,6 @@ public void ShowAboutBox() remove { } } - [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler ContextMenuChanged - { - add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "ContextMenuChanged")); - remove { } - } - [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public event EventHandler CursorChanged { @@ -3090,7 +3069,7 @@ private void DepersistFromIStorage(Ole32.IStorage storage) // if (storage != null) { - HRESULT hr = iPersistStorage.Load(storage); + HRESULT hr = iPersistStorage.Load(storage); if (hr != HRESULT.S_OK) { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "Error trying load depersist from IStorage: " + hr); @@ -4232,7 +4211,7 @@ int UnsafeNativeMethods.IOleControlSite.GetExtendedControl(out object ppDisp) return NativeMethods.S_OK; } - unsafe HRESULT UnsafeNativeMethods.IOleControlSite.TransformCoords(Point *pPtlHimetric, PointF *pPtfContainer, uint dwFlags) + unsafe HRESULT UnsafeNativeMethods.IOleControlSite.TransformCoords(Point* pPtlHimetric, PointF* pPtfContainer, uint dwFlags) { if (pPtlHimetric == null || pPtfContainer == null) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComboBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComboBox.cs index d39bdd80706..1a22de92b2e 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComboBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComboBox.cs @@ -1973,7 +1973,7 @@ private void ChildWndProc(ref Message m) //set the mouse capture .. this is the Child Wndproc.. // - if (ContextMenu != null || ContextMenuStrip != null) + if (ContextMenuStrip != null) { CaptureInternal = true; } @@ -1997,12 +1997,6 @@ private void ChildWndProc(ref Message m) case WindowMessages.WM_RBUTTONUP: mousePressed = false; mouseEvents = false; - //set the mouse capture .. this is the Child Wndproc.. - // - if (ContextMenu != null) - { - CaptureInternal = false; - } DefChildWndProc(ref m); //the up gets fired from "Combo-box's WndPrc --- So Convert these Coordinates to Combobox coordianate... @@ -2014,7 +2008,7 @@ private void ChildWndProc(ref Message m) case WindowMessages.WM_CONTEXTMENU: // Forward context menu messages to the parent control - if (ContextMenu != null || ContextMenuStrip != null) + if (ContextMenuStrip != null) { UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), WindowMessages.WM_CONTEXTMENU, m.WParam, m.LParam); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ContextMenu.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ContextMenu.cs deleted file mode 100644 index 160d830e68b..00000000000 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ContextMenu.cs +++ /dev/null @@ -1,224 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.ComponentModel; -using System.Drawing; -using System.Runtime.InteropServices; - -namespace System.Windows.Forms -{ - /// - /// This class is used to put context menus on your form and show them for - /// controls at runtime. It basically acts like a regular Menu control, - /// but can be set for the ContextMenu property that most controls have. - /// - [DefaultEvent(nameof(Popup))] - public class ContextMenu : Menu - { - private EventHandler onPopup; - private EventHandler onCollapse; - internal Control sourceControl; - - private RightToLeft rightToLeft = System.Windows.Forms.RightToLeft.Inherit; - - /// - /// Creates a new ContextMenu object with no items in it by default. - /// - public ContextMenu() - : base(null) - { - } - - /// - /// Creates a ContextMenu object with the given MenuItems. - /// - public ContextMenu(MenuItem[] menuItems) - : base(menuItems) - { - } - - /// - /// The last control that was acted upon that resulted in this context - /// menu being displayed. - /// - [ - Browsable(false), - DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), - SRDescription(nameof(SR.ContextMenuSourceControlDescr)) - ] - public Control SourceControl - { - get - { - return sourceControl; - } - } - - [SRDescription(nameof(SR.MenuItemOnInitDescr))] - public event EventHandler Popup - { - add => onPopup += value; - remove => onPopup -= value; - } - - /// - /// Fires when the context menu collapses. - /// - [SRDescription(nameof(SR.ContextMenuCollapseDescr))] - public event EventHandler Collapse - { - add => onCollapse += value; - remove => onCollapse -= value; - } - - /// - /// This is used for international applications where the language - /// is written from RightToLeft. When this property is true, - /// text alignment and reading order will be from right to left. - /// - // Add a DefaultValue attribute so that the Reset context menu becomes - // available in the Property Grid but the default value remains No. - [ - Localizable(true), - DefaultValue(RightToLeft.No), - SRDescription(nameof(SR.MenuRightToLeftDescr)) - ] - public virtual RightToLeft RightToLeft - { - get - { - if (System.Windows.Forms.RightToLeft.Inherit == rightToLeft) - { - if (sourceControl != null) - { - return ((Control)sourceControl).RightToLeft; - } - else - { - return RightToLeft.No; - } - } - else - { - return rightToLeft; - } - } - set - { - - //valid values are 0x0 to 0x2. - if (!ClientUtils.IsEnumValid(value, (int)value, (int)RightToLeft.No, (int)RightToLeft.Inherit)) - { - throw new InvalidEnumArgumentException(nameof(RightToLeft), (int)value, typeof(RightToLeft)); - } - if (RightToLeft != value) - { - rightToLeft = value; - UpdateRtl((value == System.Windows.Forms.RightToLeft.Yes)); - } - - } - } - - internal override bool RenderIsRightToLeft - { - get - { - return (rightToLeft == System.Windows.Forms.RightToLeft.Yes); - } - } - /// - /// Fires the popup event - /// - protected internal virtual void OnPopup(EventArgs e) - { - onPopup?.Invoke(this, e); - } - - /// - /// Fires the collapse event - /// - protected internal virtual void OnCollapse(EventArgs e) - { - onCollapse?.Invoke(this, e); - } - - protected internal virtual bool ProcessCmdKey(ref Message msg, Keys keyData, Control control) - { - sourceControl = control; - return ProcessCmdKey(ref msg, keyData); - } - - private void ResetRightToLeft() - { - RightToLeft = RightToLeft.No; - } - - /// - /// Returns true if the RightToLeft should be persisted in code gen. - /// - internal virtual bool ShouldSerializeRightToLeft() - { - if (System.Windows.Forms.RightToLeft.Inherit == rightToLeft) - { - return false; - } - return true; - } - - /// - /// Displays the context menu at the specified position. This method - /// doesn't return until the menu is dismissed. - /// - public void Show(Control control, Point pos) - { - Show(control, pos, NativeMethods.TPM_VERTICAL | NativeMethods.TPM_RIGHTBUTTON); - } - - /// - /// Displays the context menu at the specified position. This method - /// doesn't return until the menu is dismissed. - /// - public void Show(Control control, Point pos, LeftRightAlignment alignment) - { - // This code below looks wrong but it's correct. - // WinForms Left alignment means we want the menu to show up left of the point it is invoked from. - // We specify TPM_RIGHTALIGN which tells win32 to align the right side of this - // menu with the point (which aligns it Left visually) - if (alignment == LeftRightAlignment.Left) - { - Show(control, pos, NativeMethods.TPM_VERTICAL | NativeMethods.TPM_RIGHTBUTTON | NativeMethods.TPM_RIGHTALIGN); - } - else - { - Show(control, pos, NativeMethods.TPM_VERTICAL | NativeMethods.TPM_RIGHTBUTTON | NativeMethods.TPM_LEFTALIGN); - } - } - - private void Show(Control control, Point pos, int flags) - { - if (control == null) - { - throw new ArgumentNullException(nameof(control)); - } - - if (!control.IsHandleCreated || !control.Visible) - { - throw new ArgumentException(SR.ContextMenuInvalidParent, "control"); - } - - sourceControl = control; - - OnPopup(EventArgs.Empty); - pos = control.PointToScreen(pos); - SafeNativeMethods.TrackPopupMenuEx(new HandleRef(this, Handle), - flags, - pos.X, - pos.Y, - new HandleRef(control, control.Handle), - null); - } - - } -} diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Control.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Control.cs index 336efab217e..645037f1372 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Control.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Control.cs @@ -22,9 +22,9 @@ using System.Windows.Forms.Layout; using Accessibility; using Microsoft.Win32; +using static Interop; using Encoding = System.Text.Encoding; using IComDataObject = System.Runtime.InteropServices.ComTypes.IDataObject; -using static Interop; namespace System.Windows.Forms { @@ -258,7 +258,6 @@ private protected void TraceCanProcessMnemonic() private static readonly object s_enabledEvent = new object(); private static readonly object s_dockEvent = new object(); private static readonly object s_cursorEvent = new object(); - private static readonly object s_contextMenuEvent = new object(); private static readonly object s_contextMenuStripEvent = new object(); private static readonly object s_causesValidationEvent = new object(); private static readonly object s_regionChangedEvent = new object(); @@ -308,7 +307,6 @@ private protected void TraceCanProcessMnemonic() private static readonly int s_backgroundImageProperty = PropertyStore.CreateKey(); private static readonly int s_fontHandleWrapperProperty = PropertyStore.CreateKey(); private static readonly int s_userDataProperty = PropertyStore.CreateKey(); - private static readonly int s_contextMenuProperty = PropertyStore.CreateKey(); private static readonly int s_cursorProperty = PropertyStore.CreateKey(); private static readonly int s_regionProperty = PropertyStore.CreateKey(); @@ -1502,58 +1500,6 @@ public bool ContainsFocus } } - /// - /// The contextMenu associated with this control. The contextMenu - /// will be shown when the user right clicks the mouse on the control. - /// - /// Whidbey: ContextMenu is browsable false. In all cases where both a context menu - /// and a context menu strip are assigned, context menu will be shown instead of context menu strip. - /// - [ - SRCategory(nameof(SR.CatBehavior)), - DefaultValue(null), - SRDescription(nameof(SR.ControlContextMenuDescr)), - Browsable(false) - ] - public virtual ContextMenu ContextMenu - { - get => (ContextMenu)Properties.GetObject(s_contextMenuProperty); - set - { - ContextMenu oldValue = (ContextMenu)Properties.GetObject(s_contextMenuProperty); - - if (oldValue != value) - { - EventHandler disposedHandler = new EventHandler(DetachContextMenu); - - if (oldValue != null) - { - oldValue.Disposed -= disposedHandler; - } - - Properties.SetObject(s_contextMenuProperty, value); - - if (value != null) - { - value.Disposed += disposedHandler; - } - - OnContextMenuChanged(EventArgs.Empty); - } - } - } - - [ - SRCategory(nameof(SR.CatPropertyChanged)), - SRDescription(nameof(SR.ControlOnContextMenuChangedDescr)), - Browsable(false) - ] - public event EventHandler ContextMenuChanged - { - add => Events.AddHandler(s_contextMenuEvent, value); - remove => Events.RemoveHandler(s_contextMenuEvent, value); - } - /// /// The contextMenuStrip associated with this control. The contextMenuStrip /// will be shown when the user right clicks the mouse on the control. @@ -1833,7 +1779,7 @@ internal bool IsCurrentlyBeingScaled /// handle for this control. If the control's handle hasn't been /// created yet, this method will return the current thread's ID. /// - internal int CreateThreadId => IsHandleCreated + internal int CreateThreadId => IsHandleCreated ? SafeNativeMethods.GetWindowThreadProcessId(new HandleRef(this, Handle), out int _) : SafeNativeMethods.GetCurrentThreadId(); @@ -1999,8 +1945,6 @@ public static Font DefaultFont /// protected virtual Size DefaultSize => Size.Empty; - private void DetachContextMenu(object sender, EventArgs e) => ContextMenu = null; - private void DetachContextMenuStrip(object sender, EventArgs e) => ContextMenuStrip = null; /// @@ -3710,7 +3654,7 @@ public object Tag ] public virtual string Text { - get => CacheTextInternal ? _text ?? "" : WindowText; + get => CacheTextInternal ? _text ?? "" : WindowText; set { if (value == null) @@ -5332,12 +5276,6 @@ protected override void Dispose(bool disposing) { DisposeAxControls(); - ContextMenu contextMenu = (ContextMenu)Properties.GetObject(s_contextMenuProperty); - if (contextMenu != null) - { - contextMenu.Disposed -= new EventHandler(DetachContextMenu); - } - ResetBindings(); if (IsHandleCreated) @@ -5991,48 +5929,6 @@ internal bool GetAnyDisposingInHierarchy() return isDisposing; } - private MenuItem GetMenuItemFromHandleId(IntPtr hmenu, int item) - { - MenuItem mi = null; - int id = UnsafeNativeMethods.GetMenuItemID(new HandleRef(null, hmenu), item); - if (id == unchecked((int)0xFFFFFFFF)) - { - IntPtr childMenu = IntPtr.Zero; - childMenu = UnsafeNativeMethods.GetSubMenu(new HandleRef(null, hmenu), item); - int count = UnsafeNativeMethods.GetMenuItemCount(new HandleRef(null, childMenu)); - MenuItem found = null; - for (int i = 0; i < count; i++) - { - found = GetMenuItemFromHandleId(childMenu, i); - if (found != null) - { - Menu parent = found.Parent; - if (parent != null && parent is MenuItem) - { - found = (MenuItem)parent; - break; - } - found = null; - } - } - - mi = found; - } - else - { - Command cmd = Command.GetCommandFromID(id); - if (cmd != null) - { - object reference = cmd.Target; - if (reference != null && reference is MenuItem.MenuItemData) - { - mi = ((MenuItem.MenuItemData)reference).baseItem; - } - } - } - return mi; - } - /// /// - Returns child controls sorted according to their TabIndex property order. /// - Controls with the same TabIndex remain in original relative child index order (= z-order). @@ -6463,7 +6359,7 @@ internal virtual IntPtr InitializeDCForWmCtlColor(IntPtr dc, int msg) SafeNativeMethods.SetBkColor(new HandleRef(null, dc), ColorTranslator.ToWin32(BackColor)); return BackColorBrush; } - + return Gdi32.GetStockObject(Gdi32.StockObject.HOLLOW_BRUSH); } @@ -7420,15 +7316,6 @@ internal virtual void OnChildLayoutResuming(Control child, bool performLayout) } } - [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnContextMenuChanged(EventArgs e) - { - if (Events[s_contextMenuEvent] is EventHandler eh) - { - eh(this, e); - } - } - [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void OnContextMenuStripChanged(EventArgs e) { @@ -8385,7 +8272,7 @@ protected virtual void OnLayout(LayoutEventArgs levent) { ActiveXViewChanged(); } - + ((LayoutEventHandler)Events[s_layoutEvent])?.Invoke(this, levent); bool parentRequiresLayout = LayoutEngine.Layout(this, levent); @@ -9440,16 +9327,12 @@ internal static PreProcessControlState PreProcessControlMessageInternal(Control protected virtual bool ProcessCmdKey(ref Message msg, Keys keyData) { Debug.WriteLineIf(s_controlKeyboardRouting.TraceVerbose, "Control.ProcessCmdKey " + msg.ToString()); - ContextMenu contextMenu = (ContextMenu)Properties.GetObject(s_contextMenuProperty); - if (contextMenu != null && contextMenu.ProcessCmdKey(ref msg, keyData, this)) - { - return true; - } if (_parent != null) { return _parent.ProcessCmdKey(ref msg, keyData); } + return false; } @@ -12009,11 +11892,8 @@ internal virtual void WmContextMenu(ref Message m) /// internal void WmContextMenu(ref Message m, Control sourceControl) { - ContextMenu contextMenu = Properties.GetObject(s_contextMenuProperty) as ContextMenu; - ContextMenuStrip contextMenuStrip = (contextMenu != null) ? null /*save ourselves a property fetch*/ - : Properties.GetObject(s_contextMenuStripProperty) as ContextMenuStrip; - - if (contextMenu != null || contextMenuStrip != null) + var contextMenuStrip = (ContextMenuStrip)Properties.GetObject(s_contextMenuStripProperty); + if (contextMenuStrip != null) { int x = NativeMethods.Util.SignedLOWORD(m.LParam); int y = NativeMethods.Util.SignedHIWORD(m.LParam); @@ -12032,22 +11912,9 @@ internal void WmContextMenu(ref Message m, Control sourceControl) client = PointToClient(new Point(x, y)); } - // VisualStudio7 # 156, only show the context menu when clicked in the client area if (ClientRectangle.Contains(client)) { - if (contextMenu != null) - { - contextMenu.Show(sourceControl, client); - } - else if (contextMenuStrip != null) - { - contextMenuStrip.ShowInternal(sourceControl, client, keyboardActivated); - } - else - { - Debug.Fail("contextmenu and contextmenustrip are both null... hmm how did we get here?"); - DefWndProc(ref m); - } + contextMenuStrip.ShowInternal(sourceControl, client, keyboardActivated); } else { @@ -12085,40 +11952,6 @@ private void WmDisplayChange(ref Message m) DefWndProc(ref m); } - /// - /// WM_DRAWITEM handler - /// - private void WmDrawItem(ref Message m) - { - // If the wparam is zero, then the message was sent by a menu. - // See WM_DRAWITEM in MSDN. - if (m.WParam == IntPtr.Zero) - { - WmDrawItemMenuItem(ref m); - } - else - { - WmOwnerDraw(ref m); - } - } - - private void WmDrawItemMenuItem(ref Message m) - { - // Obtain the menu item object - NativeMethods.DRAWITEMSTRUCT dis = (NativeMethods.DRAWITEMSTRUCT)m.GetLParam(typeof(NativeMethods.DRAWITEMSTRUCT)); - - // A pointer to the correct MenuItem is stored in the draw item - // information sent with the message. - // (See MenuItem.CreateMenuItemInfo) - MenuItem menuItem = MenuItem.GetMenuItemFromItemData(dis.itemData); - - // Delegate this message to the menu item - if (menuItem != null) - { - menuItem.WmDrawItem(ref m); - } - } - /// /// Handles the WM_ERASEBKGND message /// @@ -12151,26 +11984,6 @@ private void WmEraseBkgnd(ref Message m) } } - /// - /// Handles the WM_EXITMENULOOP message. If this control has a context menu, its - /// Collapse event is raised. - /// - private void WmExitMenuLoop(ref Message m) - { - bool isContextMenu = (unchecked((int)(long)m.WParam) == 0) ? false : true; - - if (isContextMenu) - { - ContextMenu contextMenu = (ContextMenu)Properties.GetObject(s_contextMenuProperty); - if (contextMenu != null) - { - contextMenu.OnCollapse(EventArgs.Empty); - } - } - - DefWndProc(ref m); - } - /// /// Handles the WM_GETCONTROLNAME message. Returns the name of the control. /// @@ -12329,112 +12142,6 @@ private void WmHelp(ref Message m) } - /// - /// Handles the WM_INITMENUPOPUP message - /// - private void WmInitMenuPopup(ref Message m) - { - ContextMenu contextMenu = (ContextMenu)Properties.GetObject(s_contextMenuProperty); - if (contextMenu != null) - { - - if (contextMenu.ProcessInitMenuPopup(m.WParam)) - { - return; - } - } - DefWndProc(ref m); - } - - /// - /// WM_MEASUREITEM handler - /// - private void WmMeasureItem(ref Message m) - { - // If the wparam is zero, then the message was sent by a menu. - // See WM_MEASUREITEM in MSDN. - if (m.WParam == IntPtr.Zero) - { - - // Obtain the menu item object - NativeMethods.MEASUREITEMSTRUCT mis = (NativeMethods.MEASUREITEMSTRUCT)m.GetLParam(typeof(NativeMethods.MEASUREITEMSTRUCT)); - - Debug.Assert(m.LParam != IntPtr.Zero, "m.lparam is null"); - - // A pointer to the correct MenuItem is stored in the measure item - // information sent with the message. - // (See MenuItem.CreateMenuItemInfo) - MenuItem menuItem = MenuItem.GetMenuItemFromItemData(mis.itemData); - Debug.Assert(menuItem != null, "UniqueID is not associated with a menu item"); - - // Delegate this message to the menu item - if (menuItem != null) - { - menuItem.WmMeasureItem(ref m); - } - } - else - { - WmOwnerDraw(ref m); - } - } - - /// - /// Handles the WM_MENUCHAR message - /// - private void WmMenuChar(ref Message m) - { - Menu menu = ContextMenu; - if (menu != null) - { - menu.WmMenuChar(ref m); - if (m.Result != IntPtr.Zero) - { - // This char is a mnemonic on our menu. - return; - } - } - } - - /// - /// Handles the WM_MENUSELECT message - /// - private void WmMenuSelect(ref Message m) - { - int item = NativeMethods.Util.LOWORD(m.WParam); - int flags = NativeMethods.Util.HIWORD(m.WParam); - IntPtr hmenu = m.LParam; - MenuItem mi = null; - - if ((flags & NativeMethods.MF_SYSMENU) != 0) - { - // nothing - } - else if ((flags & NativeMethods.MF_POPUP) == 0) - { - Command cmd = Command.GetCommandFromID(item); - if (cmd != null) - { - object reference = cmd.Target; - if (reference != null && reference is MenuItem.MenuItemData) - { - mi = ((MenuItem.MenuItemData)reference).baseItem; - } - } - } - else - { - mi = GetMenuItemFromHandleId(hmenu, item); - } - - if (mi != null) - { - mi.PerformSelect(); - } - - DefWndProc(ref m); - } - /// /// Handles the WM_CREATE message /// @@ -13390,17 +13097,16 @@ protected virtual void WndProc(ref Message m) break; case WindowMessages.WM_DRAWITEM: - WmDrawItem(ref m); + if (m.WParam != IntPtr.Zero) + { + WmOwnerDraw(ref m); + } break; case WindowMessages.WM_ERASEBKGND: WmEraseBkgnd(ref m); break; - case WindowMessages.WM_EXITMENULOOP: - WmExitMenuLoop(ref m); - break; - case WindowMessages.WM_HELP: WmHelp(ref m); break; @@ -13427,10 +13133,6 @@ protected virtual void WndProc(ref Message m) } break; - case WindowMessages.WM_INITMENUPOPUP: - WmInitMenuPopup(ref m); - break; - case WindowMessages.WM_SYSCOMMAND: if ((unchecked((int)(long)m.WParam) & 0xFFF0) == NativeMethods.SC_KEYMENU) { @@ -13455,15 +13157,10 @@ protected virtual void WndProc(ref Message m) break; case WindowMessages.WM_MEASUREITEM: - WmMeasureItem(ref m); - break; - - case WindowMessages.WM_MENUCHAR: - WmMenuChar(ref m); - break; - - case WindowMessages.WM_MENUSELECT: - WmMenuSelect(ref m); + if (m.WParam != IntPtr.Zero) + { + WmOwnerDraw(ref m); + } break; case WindowMessages.WM_SETCURSOR: @@ -13677,6 +13374,9 @@ protected virtual void WndProc(ref Message m) WmParentNotify(ref m); break; + case WindowMessages.WM_EXITMENULOOP: + case WindowMessages.WM_INITMENUPOPUP: + case WindowMessages.WM_MENUSELECT: default: // If we received a thread execute message, then execute it. @@ -14488,7 +14188,7 @@ void UnsafeNativeMethods.IViewObject2.GetAdvise(int[] paspects, int[] padvf, IAd ActiveXInstance.GetAdvise(paspects, padvf, pAdvSink); } - unsafe Interop.HRESULT UnsafeNativeMethods.IViewObject2.GetExtent(uint dwDrawAspect, int lindex, NativeMethods.tagDVTARGETDEVICE ptd, Size *lpsizel) + unsafe Interop.HRESULT UnsafeNativeMethods.IViewObject2.GetExtent(uint dwDrawAspect, int lindex, NativeMethods.tagDVTARGETDEVICE ptd, Size* lpsizel) { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:GetExtent (IViewObject2)"); // we already have an implementation of this [from IOleObject] diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGrid.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGrid.cs deleted file mode 100644 index e692ead8fea..00000000000 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGrid.cs +++ /dev/null @@ -1,10628 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Collections; -using System.ComponentModel; -using System.ComponentModel.Design; -using System.Diagnostics; -using System.Drawing; -using System.Globalization; -using System.Runtime.InteropServices; -using System.Text; -using static Interop; - -namespace System.Windows.Forms -{ - /// - /// Displays ADO.NET data in a scrollable grid. - /// - [ - ComVisible(true), - ClassInterface(ClassInterfaceType.AutoDispatch), - Designer("System.Windows.Forms.Design.DataGridDesigner, " + AssemblyRef.SystemDesign), - DefaultProperty(nameof(DataSource)), - DefaultEvent(nameof(Navigate)), - ComplexBindingProperties(nameof(DataSource), nameof(DataMember)), - ] - public class DataGrid : Control, ISupportInitialize, IDataGridEditingService - { -#if DEBUG - internal TraceSwitch DataGridAcc = new TraceSwitch("DataGridAcc", "Trace Windows Forms DataGrid Accessibility"); -#else - internal TraceSwitch DataGridAcc = null; -#endif - - private const int GRIDSTATE_allowSorting = 0x00000001; - private const int GRIDSTATE_columnHeadersVisible = 0x00000002; - private const int GRIDSTATE_rowHeadersVisible = 0x00000004; - private const int GRIDSTATE_trackColResize = 0x00000008; - private const int GRIDSTATE_trackRowResize = 0x00000010; - private const int GRIDSTATE_isLedgerStyle = 0x00000020; - private const int GRIDSTATE_isFlatMode = 0x00000040; - private const int GRIDSTATE_listHasErrors = 0x00000080; - private const int GRIDSTATE_dragging = 0x00000100; - private const int GRIDSTATE_inListAddNew = 0x00000200; - private const int GRIDSTATE_inDeleteRow = 0x00000400; - private const int GRIDSTATE_canFocus = 0x00000800; - private const int GRIDSTATE_readOnlyMode = 0x00001000; - private const int GRIDSTATE_allowNavigation = 0x00002000; - private const int GRIDSTATE_isNavigating = 0x00004000; - private const int GRIDSTATE_isEditing = 0x00008000; - private const int GRIDSTATE_editControlChanging = 0x00010000; - private const int GRIDSTATE_isScrolling = 0x00020000; - private const int GRIDSTATE_overCaption = 0x00040000; - private const int GRIDSTATE_childLinkFocused = 0x00080000; - private const int GRIDSTATE_inAddNewRow = 0x00100000; - private const int GRIDSTATE_inSetListManager = 0x00200000; - private const int GRIDSTATE_metaDataChanged = 0x00400000; - private const int GRIDSTATE_exceptionInPaint = 0x00800000; - private const int GRIDSTATE_layoutSuspended = 0x01000000; - - // PERF: take all the bools and put them into a state variable - private Collections.Specialized.BitVector32 gridState; // see GRIDSTATE_ consts above - - // for column widths - private const int NumRowsForAutoResize = 10; - - private const int errorRowBitmapWidth = 15; - - private const DataGridParentRowsLabelStyle defaultParentRowsLabelStyle = DataGridParentRowsLabelStyle.Both; - - private const BorderStyle defaultBorderStyle = BorderStyle.Fixed3D; - - private const bool defaultCaptionVisible = true; - - private const bool defaultParentRowsVisible = true; - - private readonly DataGridTableStyle defaultTableStyle = new DataGridTableStyle(true); - - // private bool allowSorting = true; - - private SolidBrush alternatingBackBrush = DefaultAlternatingBackBrush; - - // private bool columnHeadersVisible = true; - - private SolidBrush gridLineBrush = DefaultGridLineBrush; - - private const DataGridLineStyle defaultGridLineStyle = DataGridLineStyle.Solid; - private DataGridLineStyle gridLineStyle = defaultGridLineStyle; - - private SolidBrush headerBackBrush = DefaultHeaderBackBrush; - - private Font headerFont = null; // this is ambient property to Font value - - private SolidBrush headerForeBrush = DefaultHeaderForeBrush; - private Pen headerForePen = DefaultHeaderForePen; - - private SolidBrush linkBrush = DefaultLinkBrush; - - private const int defaultPreferredColumnWidth = 75; - private int preferredColumnWidth = defaultPreferredColumnWidth; - - private static readonly int defaultFontHeight = Control.DefaultFont.Height; - private int preferredRowHeight = defaultFontHeight + 3; - - // private bool rowHeadersVisible = true; - private const int defaultRowHeaderWidth = 35; - private int rowHeaderWidth = defaultRowHeaderWidth; - private int minRowHeaderWidth; - - private SolidBrush selectionBackBrush = DefaultSelectionBackBrush; - private SolidBrush selectionForeBrush = DefaultSelectionForeBrush; - - // parent rows - // - private readonly DataGridParentRows parentRows = null; - // Set_ListManager uses the originalState to determine - // if the grid should disconnect from all the MetaDataChangedEvents - // keep "originalState != null" when navigating back and forth in the grid - // and use Add/RemoveMetaDataChanged methods. - private DataGridState originalState = null; - - // ui state - // - // Don't use dataGridRows, use the accessor!!! - private DataGridRow[] dataGridRows = Array.Empty(); - private int dataGridRowsLength = 0; - - // for toolTip - private int toolTipId = 0; - private DataGridToolTip toolTipProvider = null; - - private DataGridAddNewRow addNewRow = null; - private LayoutData layout = new LayoutData(); - private RECT[] cachedScrollableRegion = null; - - // header namespace goo - // - - // these are actually get/set by ColumnBehavior - internal bool allowColumnResize = true; - - internal bool allowRowResize = true; - - internal DataGridParentRowsLabelStyle parentRowsLabels = defaultParentRowsLabelStyle; - - // information for col/row resizing - // private bool trackColResize = false; - private int trackColAnchor = 0; - private int trackColumn = 0; - // private bool trackRowResize = false; - private int trackRowAnchor = 0; - private int trackRow = 0; - private PropertyDescriptor trackColumnHeader = null; - private MouseEventArgs lastSplitBar = null; - - // private bool isLedgerStyle = true; - // private bool isFlatMode = false; - private Font linkFont = null; - - private SolidBrush backBrush = DefaultBackBrush; - private SolidBrush foreBrush = DefaultForeBrush; - private SolidBrush backgroundBrush = DefaultBackgroundBrush; - - // font cacheing info - private int fontHeight = -1; - private int linkFontHeight = -1; - private int captionFontHeight = -1; - private int headerFontHeight = -1; - - // the preffered height of the row. - - // if the list has items with errors - - // private bool listHasErrors = false; - - // caption - private readonly DataGridCaption caption; - - // Border - // - private BorderStyle borderStyle; - - // data binding - // - private object dataSource = null; - private string dataMember = string.Empty; - private CurrencyManager listManager = null; - - // currently focused control - // we want to unparent it either when rebinding the grid or when the grid is disposed - Control toBeDisposedEditingControl = null; - - // persistent data state - // - internal GridTableStylesCollection dataGridTables = null; - // SET myGridTable in SetDataGridTable ONLY - internal DataGridTableStyle myGridTable = null; - internal bool checkHierarchy = true; - internal bool inInit = false; - - // Selection - internal int currentRow = 0; - internal int currentCol = 0; - private int numSelectedRows = 0; - private int lastRowSelected = -1; - - // dragging: - // private bool dragging = false; - - // addNewRow - // private bool inAddNewRow = false; - // delete Row - // private bool inDeleteRow = false; - - // when we leave, we call CommitEdit - // if we leave, then do not focus the dataGrid. - // so we can't focus the grid at the following moments: - // 1. while processing the OnLayout event - // 2. while processing the OnLeave event - // private bool canFocus = true; - - // for CurrentCell -#if DEBUG - private bool inDataSource_PositionChanged = false; -#endif // DEBUG - - // Policy - // private bool readOnlyMode = false; - private readonly Policy policy = new Policy(); - // private bool allowNavigation = true; - - // editing - // private bool isNavigating = false; - // private bool isEditing = false; - // private bool editControlChanging = false; - private DataGridColumnStyle editColumn = null; - private DataGridRow editRow = null; - - // scrolling - // - private readonly ScrollBar horizScrollBar = new HScrollBar(); - private readonly ScrollBar vertScrollBar = new VScrollBar(); - - // the sum of the widths of the columns preceding the firstVisibleColumn - // - private int horizontalOffset = 0; - - // the number of pixels of the firstVisibleColumn which are not visible - // - private int negOffset = 0; - - private int wheelDelta = 0; - // private bool isScrolling = false; - - // Visibility - // - internal int firstVisibleRow = 0; - internal int firstVisibleCol = 0; - private int numVisibleRows = 0; - // the number of columns which are visible - private int numVisibleCols = 0; - private int numTotallyVisibleRows = 0; - // lastTotallyVisibleCol == -1 means that the data grid does not show any column in its entirety - private int lastTotallyVisibleCol = 0; - - // mouse move hot-tracking - // - private int oldRow = -1; - // private bool overCaption = true; - - // child relationships focused - // - // private bool childLinkFocused = false; - - // private static readonly object EVENT_COLUMNHEADERCLICK = new object(); - private static readonly object EVENT_CURRENTCELLCHANGED = new object(); - // private static readonly object EVENT_COLUMNRESIZE = new object(); - // private static readonly object EVENT_LINKCLICKED = new object(); - private static readonly object EVENT_NODECLICKED = new object(); - // private static readonly object EVENT_ROWRESIZE = new object(); - private static readonly object EVENT_SCROLL = new object(); - private static readonly object EVENT_BACKBUTTONCLICK = new object(); - private static readonly object EVENT_DOWNBUTTONCLICK = new object(); - - // event handlers - // - private readonly ItemChangedEventHandler itemChangedHandler; - private readonly EventHandler positionChangedHandler; - private readonly EventHandler currentChangedHandler; - private readonly EventHandler metaDataChangedHandler; - - // we have to know when the collection of dataGridTableStyles changes - private readonly CollectionChangeEventHandler dataGridTableStylesCollectionChanged; - - private readonly EventHandler backButtonHandler; - private readonly EventHandler downButtonHandler; - - private NavigateEventHandler onNavigate; - - private EventHandler onRowHeaderClick; - - // forDebug - // - // private int forDebug = 0; - - // =----------------------------------------------------------------- - - /// - /// Initializes a new instance of the - /// class. - /// - public DataGrid() : base() - { - SetStyle(ControlStyles.UserPaint, true); - SetStyle(ControlStyles.Opaque, false); - SetStyle(ControlStyles.SupportsTransparentBackColor, false); - SetStyle(ControlStyles.UserMouse, true); - gridState = new Collections.Specialized.BitVector32(0x00042827); - - dataGridTables = new GridTableStylesCollection(this); - layout = CreateInitialLayoutState(); - parentRows = new DataGridParentRows(this); - - horizScrollBar.Top = ClientRectangle.Height - horizScrollBar.Height; - horizScrollBar.Left = 0; - horizScrollBar.Visible = false; - horizScrollBar.Scroll += new ScrollEventHandler(GridHScrolled); - Controls.Add(horizScrollBar); - - vertScrollBar.Top = 0; - vertScrollBar.Left = ClientRectangle.Width - vertScrollBar.Width; - vertScrollBar.Visible = false; - vertScrollBar.Scroll += new ScrollEventHandler(GridVScrolled); - Controls.Add(vertScrollBar); - - BackColor = DefaultBackBrush.Color; - ForeColor = DefaultForeBrush.Color; - borderStyle = defaultBorderStyle; - - // create the event handlers - // - currentChangedHandler = new EventHandler(DataSource_RowChanged); - positionChangedHandler = new EventHandler(DataSource_PositionChanged); - itemChangedHandler = new ItemChangedEventHandler(DataSource_ItemChanged); - metaDataChangedHandler = new EventHandler(DataSource_MetaDataChanged); - dataGridTableStylesCollectionChanged = new CollectionChangeEventHandler(TableStylesCollectionChanged); - dataGridTables.CollectionChanged += dataGridTableStylesCollectionChanged; - - SetDataGridTable(defaultTableStyle, true); - - backButtonHandler = new EventHandler(OnBackButtonClicked); - downButtonHandler = new EventHandler(OnShowParentDetailsButtonClicked); - - caption = new DataGridCaption(this); - caption.BackwardClicked += backButtonHandler; - caption.DownClicked += downButtonHandler; - - RecalculateFonts(); - Size = new Size(130, 80); - Invalidate(); - PerformLayout(); - } - - // =------------------------------------------------------------------ - // = Properties - // =------------------------------------------------------------------ - - /// - /// Gets or sets a value indicating whether the grid can be resorted by clicking on - /// a column header. - /// - [ - SRCategory(nameof(SR.CatBehavior)), - DefaultValue(true), - SRDescription(nameof(SR.DataGridAllowSortingDescr)) - ] - public bool AllowSorting - { - get - { - return gridState[GRIDSTATE_allowSorting]; - } - set - { - if (AllowSorting != value) - { - gridState[GRIDSTATE_allowSorting] = value; - if (!value && listManager != null) - { - IList list = listManager.List; - if (list is IBindingList) - { - ((IBindingList)list).RemoveSort(); - } - } - } - } - } - - [ - SRCategory(nameof(SR.CatColors)), - SRDescription(nameof(SR.DataGridAlternatingBackColorDescr)) - ] - public Color AlternatingBackColor - { - get - { - return alternatingBackBrush.Color; - } - set - { - if (value.IsEmpty) - { - throw new ArgumentException(string.Format(SR.DataGridEmptyColor, - "AlternatingBackColor")); - } - if (IsTransparentColor(value)) - { - throw new ArgumentException(SR.DataGridTransparentAlternatingBackColorNotAllowed); - } - - if (!alternatingBackBrush.Color.Equals(value)) - { - alternatingBackBrush = new SolidBrush(value); - InvalidateInside(); - } - } - } - - public void ResetAlternatingBackColor() - { - if (ShouldSerializeAlternatingBackColor()) - { - AlternatingBackColor = DefaultAlternatingBackBrush.Color; - InvalidateInside(); - } - } - - protected virtual bool ShouldSerializeAlternatingBackColor() - { - return !AlternatingBackBrush.Equals(DefaultAlternatingBackBrush); - } - - internal Brush AlternatingBackBrush - { - get - { - return alternatingBackBrush; - } - } - - // overrode those properties just to move the BackColor and the ForeColor - // from the Appearance group onto the Color Group - /// - /// Gets or sets the background color of the grid. - /// - [ - SRCategory(nameof(SR.CatColors)), - SRDescription(nameof(SR.ControlBackColorDescr)) - ] - public override Color BackColor - { - // overrode those properties just to move the BackColor and the ForeColor - // from the Appearance group onto the Color Group - get - { - return base.BackColor; - } - set - { - if (IsTransparentColor(value)) - { - throw new ArgumentException(SR.DataGridTransparentBackColorNotAllowed); - } - - base.BackColor = value; - } - } - - public override void ResetBackColor() - { - if (!BackColor.Equals(DefaultBackBrush.Color)) - { - BackColor = DefaultBackBrush.Color; - } - } - - [ - SRCategory(nameof(SR.CatColors)), - SRDescription(nameof(SR.ControlForeColorDescr)) - ] - public override Color ForeColor - { - get - { - return base.ForeColor; - } - set - { - base.ForeColor = value; - } - } - public override void ResetForeColor() - { - if (!ForeColor.Equals(DefaultForeBrush.Color)) - { - ForeColor = DefaultForeBrush.Color; - } - } - - /// - /// Gets a value - /// indicating whether the property should be - /// persisted. - /// - internal SolidBrush BackBrush - { - get - { - return backBrush; - } - } - - internal SolidBrush ForeBrush - { - get - { - return foreBrush; - } - } - - /// - /// Gets or - /// sets the border style. - /// - [ - SRCategory(nameof(SR.CatAppearance)), - DefaultValue(defaultBorderStyle), - DispId(NativeMethods.ActiveX.DISPID_BORDERSTYLE), - SRDescription(nameof(SR.DataGridBorderStyleDescr)) - ] - public BorderStyle BorderStyle - { - get - { - return borderStyle; - } - set - { - //valid values are 0x0 to 0x2. - if (!ClientUtils.IsEnumValid(value, (int)value, (int)BorderStyle.None, (int)BorderStyle.Fixed3D)) - { - throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(BorderStyle)); - } - if (borderStyle != value) - { - borderStyle = value; - PerformLayout(); - Invalidate(); - OnBorderStyleChanged(EventArgs.Empty); - } - } - } - - private static readonly object EVENT_BORDERSTYLECHANGED = new object(); - - [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridOnBorderStyleChangedDescr))] - public event EventHandler BorderStyleChanged - { - add => Events.AddHandler(EVENT_BORDERSTYLECHANGED, value); - remove => Events.RemoveHandler(EVENT_BORDERSTYLECHANGED, value); - } - - private int BorderWidth - { - get - { - if (BorderStyle == BorderStyle.Fixed3D) - { - return SystemInformation.Border3DSize.Width; - } - else if (BorderStyle == BorderStyle.FixedSingle) - { - return 2; - } - else - { - return 0; - } - } - } - - protected override Size DefaultSize - { - get - { - return new Size(130, 80); - } - } - - private static SolidBrush DefaultSelectionBackBrush - { - get - { - return (SolidBrush)SystemBrushes.ActiveCaption; - } - } - private static SolidBrush DefaultSelectionForeBrush - { - get - { - return (SolidBrush)SystemBrushes.ActiveCaptionText; - } - } - internal static SolidBrush DefaultBackBrush - { - get - { - return (SolidBrush)SystemBrushes.Window; - } - } - internal static SolidBrush DefaultForeBrush - { - get - { - return (SolidBrush)SystemBrushes.WindowText; - } - } - private static SolidBrush DefaultBackgroundBrush - { - get - { - return (SolidBrush)SystemBrushes.AppWorkspace; - } - } - internal static SolidBrush DefaultParentRowsForeBrush - { - get - { - return (SolidBrush)SystemBrushes.WindowText; - } - } - internal static SolidBrush DefaultParentRowsBackBrush - { - get - { - return (SolidBrush)SystemBrushes.Control; - } - } - internal static SolidBrush DefaultAlternatingBackBrush - { - get - { - return (SolidBrush)SystemBrushes.Window; - } - } - private static SolidBrush DefaultGridLineBrush - { - get - { - return (SolidBrush)SystemBrushes.Control; - } - } - private static SolidBrush DefaultHeaderBackBrush - { - get - { - return (SolidBrush)SystemBrushes.Control; - } - } - private static SolidBrush DefaultHeaderForeBrush - { - get - { - return (SolidBrush)SystemBrushes.ControlText; - } - } - private static Pen DefaultHeaderForePen - { - get - { - return new Pen(SystemColors.ControlText); - } - } - private static SolidBrush DefaultLinkBrush - { - get - { - return (SolidBrush)SystemBrushes.HotTrack; - } - } - - private bool ListHasErrors - { - get - { - return gridState[GRIDSTATE_listHasErrors]; - } - set - { - if (ListHasErrors != value) - { - gridState[GRIDSTATE_listHasErrors] = value; - ComputeMinimumRowHeaderWidth(); - if (!layout.RowHeadersVisible) - { - return; - } - - if (value) - { - if (myGridTable.IsDefault) - { - RowHeaderWidth += errorRowBitmapWidth; - } - else - { - myGridTable.RowHeaderWidth += errorRowBitmapWidth; - } - } - else - { - if (myGridTable.IsDefault) - { - RowHeaderWidth -= errorRowBitmapWidth; - } - else - { - myGridTable.RowHeaderWidth -= errorRowBitmapWidth; - } - } - } - } - } - - private bool Bound - { - get - { - return !(listManager == null || myGridTable == null); - } - } - - internal DataGridCaption Caption - { - get - { - return caption; - } - } - - /// - /// Gets or sets the background color of the caption area. - /// - [ - SRCategory(nameof(SR.CatColors)), - SRDescription(nameof(SR.DataGridCaptionBackColorDescr)) - ] - public Color CaptionBackColor - { - get - { - return Caption.BackColor; - } - set - { - if (IsTransparentColor(value)) - { - throw new ArgumentException(SR.DataGridTransparentCaptionBackColorNotAllowed); - } - - Caption.BackColor = value; - } - } - - private void ResetCaptionBackColor() - { - Caption.ResetBackColor(); - } - - /// - /// Gets a value - /// indicating whether the property should be - /// persisted. - /// - protected virtual bool ShouldSerializeCaptionBackColor() - { - return Caption.ShouldSerializeBackColor(); - } - - /// - /// Gets - /// or sets the foreground color - /// of the caption area. - /// - [ - SRCategory(nameof(SR.CatColors)), - SRDescription(nameof(SR.DataGridCaptionForeColorDescr)) - ] - public Color CaptionForeColor - { - get - { - return Caption.ForeColor; - } - set - { - Caption.ForeColor = value; - } - } - - private void ResetCaptionForeColor() - { - Caption.ResetForeColor(); - } - - /// - /// Gets a value - /// indicating whether the property should be - /// persisted. - /// - protected virtual bool ShouldSerializeCaptionForeColor() - { - return Caption.ShouldSerializeForeColor(); - } - - /// - /// Gets or sets the font of the grid's caption. - /// - [ - SRCategory(nameof(SR.CatAppearance)), - Localizable(true), - AmbientValue(null), - SRDescription(nameof(SR.DataGridCaptionFontDescr)) - ] - public Font CaptionFont - { - get - { - return Caption.Font; - } - set - { - Caption.Font = value; - } - } - - /// - /// Gets a value indicating whether the - /// caption's font is persisted. - /// - private bool ShouldSerializeCaptionFont() - { - return Caption.ShouldSerializeFont(); - } - - private void ResetCaptionFont() - { - Caption.ResetFont(); - } - - /// - /// Gets or sets the text of the grid's caption. - /// - [ - SRCategory(nameof(SR.CatAppearance)), - DefaultValue(""), - Localizable(true), - SRDescription(nameof(SR.DataGridCaptionTextDescr)) - ] - public string CaptionText - { - get - { - return Caption.Text; - } - set - { - Caption.Text = value; - } - } - - /// - /// Gets or sets a value that indicates - /// whether the grid's caption is visible. - /// - [ - DefaultValue(true), - SRCategory(nameof(SR.CatDisplay)), - SRDescription(nameof(SR.DataGridCaptionVisibleDescr)) - ] - public bool CaptionVisible - { - get - { - return layout.CaptionVisible; - } - set - { - if (layout.CaptionVisible != value) - { - layout.CaptionVisible = value; - PerformLayout(); - Invalidate(); - OnCaptionVisibleChanged(EventArgs.Empty); - } - } - } - - private static readonly object EVENT_CAPTIONVISIBLECHANGED = new object(); - - [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridOnCaptionVisibleChangedDescr))] - public event EventHandler CaptionVisibleChanged - { - add => Events.AddHandler(EVENT_CAPTIONVISIBLECHANGED, value); - remove => Events.RemoveHandler(EVENT_CAPTIONVISIBLECHANGED, value); - } - - /// - /// Gets or sets which cell has the focus. Not available at design time. - /// - [ - Browsable(false), - DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), - SRDescription(nameof(SR.DataGridCurrentCellDescr)) - ] - public DataGridCell CurrentCell - { - get - { - return new DataGridCell(currentRow, currentCol); - } - set - { - // if the OnLayout event was not set in the grid, then we can't - // reliably set the currentCell on the grid. - if (layout.dirty) - { - throw new ArgumentException(SR.DataGridSettingCurrentCellNotGood); - } - - if (value.RowNumber == currentRow && value.ColumnNumber == currentCol) - { - return; - } - - // should we throw an exception, maybe? - if (DataGridRowsLength == 0 || myGridTable.GridColumnStyles == null || myGridTable.GridColumnStyles.Count == 0) - { - return; - } - - EnsureBound(); - - int currentRowSaved = currentRow; - int currentColSaved = currentCol; - bool wasEditing = gridState[GRIDSTATE_isEditing]; - bool cellChanged = false; - - // if the position in the listManager changed under the DataGrid, - // then do not edit after setting the current cell - bool doNotEdit = false; - - int newCol = value.ColumnNumber; - int newRow = value.RowNumber; - - string errorMessage = null; - - try - { - int columnCount = myGridTable.GridColumnStyles.Count; - if (newCol < 0) - { - newCol = 0; - } - - if (newCol >= columnCount) - { - newCol = columnCount - 1; - } - - int localGridRowsLength = DataGridRowsLength; - DataGridRow[] localGridRows = DataGridRows; - - if (newRow < 0) - { - newRow = 0; - } - if (newRow >= localGridRowsLength) - { - newRow = localGridRowsLength - 1; - } - - // Current Column changing - // - if (currentCol != newCol) - { - cellChanged = true; - int currentListManagerPosition = ListManager.Position; - int currentListManagerCount = ListManager.List.Count; - - EndEdit(); - - if (ListManager.Position != currentListManagerPosition || - currentListManagerCount != ListManager.List.Count) - { - // EndEdit changed the list. - // Reset the data grid rows and the current row inside the datagrid. - // And then exit the method. - RecreateDataGridRows(); - if (ListManager.List.Count > 0) - { - currentRow = ListManager.Position; - Edit(); - } - else - { - currentRow = -1; - } - - return; - } - - currentCol = newCol; - InvalidateRow(currentRow); - } - - // Current Row changing - // - if (currentRow != newRow) - { - cellChanged = true; - int currentListManagerPosition = ListManager.Position; - int currentListManagerCount = ListManager.List.Count; - - EndEdit(); - - if (ListManager.Position != currentListManagerPosition || - currentListManagerCount != ListManager.List.Count) - { - // EndEdit changed the list. - // Reset the data grid rows and the current row inside the datagrid. - // And then exit the method. - RecreateDataGridRows(); - if (ListManager.List.Count > 0) - { - currentRow = ListManager.Position; - Edit(); - } - else - { - currentRow = -1; - } - - return; - } - - if (currentRow < localGridRowsLength) - { - localGridRows[currentRow].OnRowLeave(); - } - - localGridRows[newRow].OnRowEnter(); - currentRow = newRow; - if (currentRowSaved < localGridRowsLength) - { - InvalidateRow(currentRowSaved); - } - - InvalidateRow(currentRow); - - if (currentRowSaved != listManager.Position) - { - // not in sync -#if DEBUG - Debug.Assert(inDataSource_PositionChanged, "currentRow and listManager.Position can be out of sync only when the listManager changes its position under the DataGrid or when navigating back"); - Debug.Assert(ListManager.Position == currentRow || listManager.Position == -1, "DataSource_PositionChanged changes the position in the grid to the position in the listManager"); -#endif //DEBUG - doNotEdit = true; - if (gridState[GRIDSTATE_isEditing]) - { - AbortEdit(); - } - } - else if (gridState[GRIDSTATE_inAddNewRow]) - { -#if DEBUG - int currentRowCount = DataGridRowsLength; -#endif // debug - // cancelCurrentEdit will change the position in the list - // to the last element in the list. and the grid will get an on position changed - // event, and will set the current cell to the last element in the dataSource. - // so unhook the PositionChanged event from the listManager; - ListManager.PositionChanged -= positionChangedHandler; - ListManager.CancelCurrentEdit(); - ListManager.Position = currentRow; - ListManager.PositionChanged += positionChangedHandler; -#if DEBUG - - Debug.Assert(currentRowSaved > currentRow, "we can only go up when we are inAddNewRow"); - Debug.Assert(currentRowCount == DataGridRowsLength, "the number of rows in the dataGrid should not change"); - Debug.Assert(currentRowCount == ListManager.Count + 1, "the listManager should have one less record"); -#endif // debug - localGridRows[DataGridRowsLength - 1] = new DataGridAddNewRow(this, myGridTable, DataGridRowsLength - 1); - SetDataGridRows(localGridRows, DataGridRowsLength); - gridState[GRIDSTATE_inAddNewRow] = false; - } - else - { - ListManager.EndCurrentEdit(); - // some special care must be given when setting the - // position in the listManager. - // if EndCurrentEdit() deleted the current row - // ( because of some filtering problem, say ) - // then we cannot go over the last row - // - if (localGridRowsLength != DataGridRowsLength) - { - Debug.Assert(localGridRowsLength == DataGridRowsLength + 1, "this is the only change that could have happened"); - currentRow = (currentRow == localGridRowsLength - 1) ? DataGridRowsLength - 1 : currentRow; - } - - if (currentRow == dataGridRowsLength - 1 && policy.AllowAdd) - { - // it may be case ( see previous comment ) - // that listManager.EndCurrentEdit changed the number of rows - // in the grid. in this case, we should not be using the old - // localGridRows in our assertion, cause they are outdated now - // - Debug.Assert(DataGridRows[currentRow] is DataGridAddNewRow, "the last row is the DataGridAddNewRow"); - AddNewRow(); - Debug.Assert(ListManager.Position == currentRow || listManager.Position == -1, "the listManager should be positioned at the last row"); - } - else - { - - ListManager.Position = currentRow; - } - } - - } - - } - catch (Exception e) - { - errorMessage = e.Message; - } - - if (errorMessage != null) - { - DialogResult result = RTLAwareMessageBox.Show(null, - string.Format(SR.DataGridPushedIncorrectValueIntoColumn, errorMessage), - SR.DataGridErrorMessageBoxCaption, MessageBoxButtons.YesNo, - MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, 0); - - if (result == DialogResult.Yes) - { - currentRow = currentRowSaved; - currentCol = currentColSaved; - Debug.Assert(currentRow == ListManager.Position || listManager.Position == -1, "the position in the list manager (" + ListManager.Position + ") is out of sync with the currentRow (" + currentRow + ")" + " and the exception is '" + errorMessage + "'"); - // this will make sure the newRow will not paint the - // row selector. - InvalidateRowHeader(newRow); - // also, make sure that we get the row selector on the currentrow, too - InvalidateRowHeader(currentRow); - if (wasEditing) - { - Edit(); - } - } - else - { - // if the user committed a row that used to be addNewRow and the backEnd rejects it, - // and then it tries to navigate down then we should stay in the addNewRow - // in this particular scenario, CancelCurrentEdit will cause the last row to be deleted, - // and this will ultimately call InvalidateRow w/ a row number larger than the number of rows - // so set the currentRow here: - if (currentRow == DataGridRowsLength - 1 && currentRowSaved == DataGridRowsLength - 2 && DataGridRows[currentRow] is DataGridAddNewRow) - { - newRow = currentRowSaved; - } - - currentRow = newRow; - Debug.Assert(result == DialogResult.No, "we only put cancel and ok on the error message box"); - listManager.PositionChanged -= positionChangedHandler; - listManager.CancelCurrentEdit(); - listManager.Position = newRow; - listManager.PositionChanged += positionChangedHandler; - currentRow = newRow; - currentCol = newCol; - if (wasEditing) - { - Edit(); - } - } - } - - if (cellChanged) - { - EnsureVisible(currentRow, currentCol); - OnCurrentCellChanged(EventArgs.Empty); - - // if the user changed the current cell using the UI, edit the new cell - // but if the user changed the current cell by changing the position in the - // listManager, then do not continue the edit - // - if (!doNotEdit) - { -#if DEBUG - Debug.Assert(!inDataSource_PositionChanged, "if the user changed the current cell using the UI, then do not edit"); -#endif // debug - Edit(); - } - - AccessibilityNotifyClients(AccessibleEvents.Focus, CurrentCellAccIndex); - AccessibilityNotifyClients(AccessibleEvents.Selection, CurrentCellAccIndex); - } - - Debug.Assert(currentRow == ListManager.Position || listManager.Position == -1, "the position in the list manager is out of sync with the currentRow"); - } - } - - internal int CurrentCellAccIndex - { - get - { - int currentCellAccIndex = 0; - currentCellAccIndex++; // ParentRowsAccessibleObject - currentCellAccIndex += myGridTable.GridColumnStyles.Count; // ColumnHeaderAccessibleObject - currentCellAccIndex += DataGridRows.Length; // DataGridRowAccessibleObject - if (horizScrollBar.Visible) // Horizontal Scroll Bar Accessible Object - { - currentCellAccIndex++; - } - - if (vertScrollBar.Visible) // Vertical Scroll Bar Accessible Object - { - currentCellAccIndex++; - } - - currentCellAccIndex += (currentRow * myGridTable.GridColumnStyles.Count) + currentCol; - return currentCellAccIndex; - } - } - - [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridOnCurrentCellChangedDescr))] - public event EventHandler CurrentCellChanged - { - add => Events.AddHandler(EVENT_CURRENTCELLCHANGED, value); - remove => Events.RemoveHandler(EVENT_CURRENTCELLCHANGED, value); - } - - private int CurrentColumn - { - get - { - return CurrentCell.ColumnNumber; - } - set - { - CurrentCell = new DataGridCell(currentRow, value); - } - } - - private int CurrentRow - { - get - { - return CurrentCell.RowNumber; - } - set - { - CurrentCell = new DataGridCell(value, currentCol); - } - } - - [ - SRCategory(nameof(SR.CatColors)), - SRDescription(nameof(SR.DataGridSelectionBackColorDescr)) - ] - public Color SelectionBackColor - { - get - { - return selectionBackBrush.Color; - } - set - { - if (value.IsEmpty) - { - throw new ArgumentException(string.Format(SR.DataGridEmptyColor, "SelectionBackColor")); - } - - if (IsTransparentColor(value)) - { - throw new ArgumentException(SR.DataGridTransparentSelectionBackColorNotAllowed); - } - - if (!value.Equals(selectionBackBrush.Color)) - { - selectionBackBrush = new SolidBrush(value); - - InvalidateInside(); - } - } - } - - internal SolidBrush SelectionBackBrush - { - get - { - return selectionBackBrush; - } - } - - internal SolidBrush SelectionForeBrush - { - get - { - return selectionForeBrush; - } - } - - protected bool ShouldSerializeSelectionBackColor() - { - return !DefaultSelectionBackBrush.Equals(selectionBackBrush); - } - - public void ResetSelectionBackColor() - { - if (ShouldSerializeSelectionBackColor()) - { - SelectionBackColor = DefaultSelectionBackBrush.Color; - } - } - - [ - SRCategory(nameof(SR.CatColors)), - SRDescription(nameof(SR.DataGridSelectionForeColorDescr)) - ] - public Color SelectionForeColor - { - get - { - return selectionForeBrush.Color; - } - set - { - if (value.IsEmpty) - { - throw new ArgumentException(string.Format(SR.DataGridEmptyColor, "SelectionForeColor")); - } - - if (!value.Equals(selectionForeBrush.Color)) - { - selectionForeBrush = new SolidBrush(value); - - InvalidateInside(); - } - } - } - - protected virtual bool ShouldSerializeSelectionForeColor() - { - return !SelectionForeBrush.Equals(DefaultSelectionForeBrush); - } - - public void ResetSelectionForeColor() - { - if (ShouldSerializeSelectionForeColor()) - { - SelectionForeColor = DefaultSelectionForeBrush.Color; - } - } - - internal override bool ShouldSerializeForeColor() - { - return !DefaultForeBrush.Color.Equals(ForeColor); - } - - /// - /// Indicates whether the property should be - /// persisted. - /// - internal override bool ShouldSerializeBackColor() - { - return !DefaultBackBrush.Color.Equals(BackColor); - } - - // Don't use dataGridRows, use the accessor!!! - internal DataGridRow[] DataGridRows - { - get - { - if (dataGridRows == null) - { - CreateDataGridRows(); - } - - return dataGridRows; - } - } - - // ToolTipping - internal DataGridToolTip ToolTipProvider - { - get - { - return toolTipProvider; - } - } - - internal int ToolTipId - { - get - { - return toolTipId; - } - set - { - toolTipId = value; - } - } - - private void ResetToolTip() - { - // remove all the tool tips which are stored - for (int i = 0; i < ToolTipId; i++) - { - ToolTipProvider.RemoveToolTip(new IntPtr(i)); - } - - // add toolTips for the backButton and - // details button on the caption. - if (!parentRows.IsEmpty()) - { - bool alignRight = isRightToLeft(); - int detailsButtonWidth = Caption.GetDetailsButtonWidth(); - Rectangle backButton = Caption.GetBackButtonRect(layout.Caption, alignRight, detailsButtonWidth); - Rectangle detailsButton = Caption.GetDetailsButtonRect(layout.Caption, alignRight); - - // mirror the buttons wrt RTL property - backButton.X = MirrorRectangle(backButton, layout.Inside, isRightToLeft()); - detailsButton.X = MirrorRectangle(detailsButton, layout.Inside, isRightToLeft()); - - ToolTipProvider.AddToolTip(SR.DataGridCaptionBackButtonToolTip, new IntPtr(0), backButton); - ToolTipProvider.AddToolTip(SR.DataGridCaptionDetailsButtonToolTip, new IntPtr(1), detailsButton); - ToolTipId = 2; - } - else - { - ToolTipId = 0; - } - } - - /// - /// Given a cursor, this will Create the right DataGridRows - /// - private void CreateDataGridRows() - { - CurrencyManager listManager = ListManager; - DataGridTableStyle dgt = myGridTable; - InitializeColumnWidths(); - - if (listManager == null) - { - SetDataGridRows(Array.Empty(), 0); - return; - } - - int nDataGridRows = listManager.Count; - if (policy.AllowAdd) - { - nDataGridRows++; - } - - DataGridRow[] rows = new DataGridRow[nDataGridRows]; - for (int r = 0; r < listManager.Count; r++) - { - rows[r] = new DataGridRelationshipRow(this, dgt, r); - } - - if (policy.AllowAdd) - { - addNewRow = new DataGridAddNewRow(this, dgt, nDataGridRows - 1); - rows[nDataGridRows - 1] = addNewRow; - } - else - { - addNewRow = null; - } - // SetDataGridRows(rows, rows.Length); - SetDataGridRows(rows, nDataGridRows); - } - - private void RecreateDataGridRows() - { - int nDataGridRows = 0; - CurrencyManager listManager = ListManager; - - if (listManager != null) - { - nDataGridRows = listManager.Count; - if (policy.AllowAdd) - { - nDataGridRows++; - } - } - SetDataGridRows(null, nDataGridRows); - } - - /// - /// Sets the array of DataGridRow objects used for - /// all row-related logic in the DataGrid. - /// - internal void SetDataGridRows(DataGridRow[] newRows, int newRowsLength) - { - dataGridRows = newRows; - dataGridRowsLength = newRowsLength; - - // update the vertical scroll bar - vertScrollBar.Maximum = Math.Max(0, DataGridRowsLength - 1); - if (firstVisibleRow > newRowsLength) - { - vertScrollBar.Value = 0; - firstVisibleRow = 0; - } - - ResetUIState(); -#if DEBUG - // sanity check: all the rows should have the same - // dataGridTable - if (newRows != null && newRowsLength > 0) - { - DataGridTableStyle dgTable = newRows[0].DataGridTableStyle; - for (int i = 0; i < newRowsLength; i++) - { - Debug.Assert(dgTable == newRows[i].DataGridTableStyle, "how can two rows have different tableStyles?"); - - } - } -#endif // DEBUG - Debug.WriteLineIf(CompModSwitches.DataGridCursor.TraceVerbose, "DataGridCursor: There are now " + DataGridRowsLength.ToString(CultureInfo.InvariantCulture) + " rows."); - } - - internal int DataGridRowsLength - { - get - { - return dataGridRowsLength; - } - } - - /// - /// Gets or sets the data source that the grid is displaying data for. - /// - [ - DefaultValue(null), - SRCategory(nameof(SR.CatData)), - RefreshProperties(RefreshProperties.Repaint), - AttributeProvider(typeof(IListSource)), - SRDescription(nameof(SR.DataGridDataSourceDescr)) - ] - public object DataSource - { - get - { - return dataSource; - } - - set - { - if (value != null && !(value is IList || value is IListSource)) - { - throw new ArgumentException(SR.BadDataSourceForComplexBinding); - } - - if (dataSource != null && dataSource.Equals(value)) - { - return; - } - - // when the designer resets the dataSource to null, set the dataMember to null, too - if ((value == null || value == Convert.DBNull) && DataMember != null && DataMember.Length != 0) - { - dataSource = null; - DataMember = string.Empty; - return; - } - - // if we are setting the dataSource and the dataMember is not a part - // of the properties in the dataSource, then set the dataMember to "" - // - if (value != null) - { - EnforceValidDataMember(value); - } - - Debug.WriteLineIf(CompModSwitches.DataGridCursor.TraceVerbose, "DataGridCursor: DataSource being set to " + ((value == null) ? "null" : value.ToString())); - - // when we change the dataSource, we need to clear the parent rows. - // the same goes for all the caption UI: reset it when the datasource changes. - // - ResetParentRows(); - Set_ListManager(value, DataMember, false); - } - } - - private static readonly object EVENT_DATASOURCECHANGED = new object(); - - [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridOnDataSourceChangedDescr))] - public event EventHandler DataSourceChanged - { - add => Events.AddHandler(EVENT_DATASOURCECHANGED, value); - remove => Events.RemoveHandler(EVENT_DATASOURCECHANGED, value); - } - - /// - /// Gets or sets the specific table in a DataSource for the control. - /// - [ - DefaultValue(null), - SRCategory(nameof(SR.CatData)), - Editor("System.Windows.Forms.Design.DataMemberListEditor, " + AssemblyRef.SystemDesign, typeof(Drawing.Design.UITypeEditor)), - SRDescription(nameof(SR.DataGridDataMemberDescr)) - ] - public string DataMember - { - get - { - return dataMember; - } - set - { - if (dataMember != null && dataMember.Equals(value)) - { - return; - } - - Debug.WriteLineIf(CompModSwitches.DataGridCursor.TraceVerbose, "DataGridCursor: DataSource being set to " + ((value == null) ? "null" : value.ToString())); - // when we change the dataMember, we need to clear the parent rows. - // the same goes for all the caption UI: reset it when the datamember changes. - // - ResetParentRows(); - Set_ListManager(DataSource, value, false); - } - } - - public void SetDataBinding(object dataSource, string dataMember) - { - parentRows.Clear(); - originalState = null; - caption.BackButtonActive = caption.DownButtonActive = caption.BackButtonVisible = false; - caption.SetDownButtonDirection(!layout.ParentRowsVisible); - - Set_ListManager(dataSource, dataMember, false); - } - - [ - Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced), - SRDescription(nameof(SR.DataGridListManagerDescr)) - ] - internal protected CurrencyManager ListManager - { - get - { - //try to return something useful: - if (listManager == null && BindingContext != null && DataSource != null) - { - return (CurrencyManager)BindingContext[DataSource, DataMember]; - } - else - { - return listManager; - } - } - set - { - throw new NotSupportedException(SR.DataGridSetListManager); - } - } - - internal void Set_ListManager(object newDataSource, string newDataMember, bool force) - { - Set_ListManager(newDataSource, newDataMember, force, true); // true for forcing column creation - } - - // - // prerequisite: the dataMember and the dataSource should be set to the new values - // - // will do the following: - // call EndEdit on the current listManager, will unWire the listManager events, will set the listManager to the new - // reality, will wire the new listManager, will update the policy, will set the dataGridTable, will reset the ui state. - // - internal void Set_ListManager(object newDataSource, string newDataMember, bool force, bool forceColumnCreation) - { - bool dataSourceChanged = DataSource != newDataSource; - bool dataMemberChanged = DataMember != newDataMember; - - // if nothing happened, then why do any work? - if (!force && !dataSourceChanged && !dataMemberChanged && gridState[GRIDSTATE_inSetListManager]) - { - return; - } - - gridState[GRIDSTATE_inSetListManager] = true; - if (toBeDisposedEditingControl != null) - { - Debug.Assert(Controls.Contains(toBeDisposedEditingControl)); - Controls.Remove(toBeDisposedEditingControl); - toBeDisposedEditingControl = null; - } - bool beginUpdateInternal = true; - try - { - // will endEdit on the current listManager - UpdateListManager(); - - // unwire the events: - if (listManager != null) - { - UnWireDataSource(); - } - - CurrencyManager oldListManager = listManager; - bool listManagerChanged = false; - // set up the new listManager - // CAUTION: we need to set up the listManager in the grid before setting the dataSource/dataMember props - // in the grid. the reason is that if the BindingContext was not yet requested, and it is created in the BindingContext prop - // then the grid will call Set_ListManager again, and eventually that means that the dataGrid::listManager will - // be hooked up twice to all the events (PositionChanged, ItemChanged, CurrentChanged) - if (newDataSource != null && BindingContext != null && !(newDataSource == Convert.DBNull)) - { - listManager = (CurrencyManager)BindingContext[newDataSource, newDataMember]; - } - else - { - listManager = null; - } - - // update the dataSource and the dateMember - dataSource = newDataSource; - dataMember = newDataMember ?? ""; - - listManagerChanged = (listManager != oldListManager); - - // wire the events - if (listManager != null) - { - WireDataSource(); - // update the policy - policy.UpdatePolicy(listManager, ReadOnly); - } - - if (!Initializing) - { - if (listManager == null) - { - if (ContainsFocus && ParentInternal == null) - { - Debug.Assert(toBeDisposedEditingControl == null, "we should have removed the toBeDisposedEditingControl already"); - // if we unparent the active control then the form won't close - for (int i = 0; i < Controls.Count; i++) - { - if (Controls[i].Focused) - { - toBeDisposedEditingControl = Controls[i]; - break; - } - } - - if (toBeDisposedEditingControl == horizScrollBar || toBeDisposedEditingControl == vertScrollBar) - { - toBeDisposedEditingControl = null; - } - -#if DEBUG - else - { - Debug.Assert(toBeDisposedEditingControl != null, "if the grid contains the focus, then the active control should be in the children of data grid control"); - Debug.Assert(editColumn != null, "if we have an editing control should be a control in the data grid column"); - if (editColumn is DataGridTextBoxColumn) - { - Debug.Assert(((DataGridTextBoxColumn)editColumn).TextBox == toBeDisposedEditingControl, "if we have an editing control should be a control in the data grid column"); - } - } -#endif // debug; - - } - - SetDataGridRows(null, 0); - defaultTableStyle.GridColumnStyles.Clear(); - SetDataGridTable(defaultTableStyle, forceColumnCreation); - - if (toBeDisposedEditingControl != null) - { - Controls.Add(toBeDisposedEditingControl); - } - } - } - - // PERF: if the listManager did not change, then do not: - // 1. create new rows - // 2. create new columns - // 3. compute the errors in the list - // - // when the metaDataChanges, we need to recreate - // the rows and the columns - // - if (listManagerChanged || gridState[GRIDSTATE_metaDataChanged]) - { - if (Visible) - { - BeginUpdateInternal(); - } - - if (listManager != null) - { - // get rid of the old gridColumns - // we need to clear the old column collection even when navigating to - // a list that has a table style associated w/ it. Why? because the - // old column collection will be used by the parent rows to paint - defaultTableStyle.GridColumnStyles.ResetDefaultColumnCollection(); - - DataGridTableStyle newGridTable = dataGridTables[listManager.GetListName()]; - if (newGridTable == null) - { - SetDataGridTable(defaultTableStyle, forceColumnCreation); - } - else - { - SetDataGridTable(newGridTable, forceColumnCreation); - } - - // set the currentRow in ssync w/ the position in the listManager - currentRow = listManager.Position == -1 ? 0 : listManager.Position; - } - - // when we create the rows we need to use the current dataGridTable - // - RecreateDataGridRows(); - if (Visible) - { - EndUpdateInternal(); - } - - beginUpdateInternal = false; - - ComputeMinimumRowHeaderWidth(); - if (myGridTable.IsDefault) - { - RowHeaderWidth = Math.Max(minRowHeaderWidth, RowHeaderWidth); - } - else - { - myGridTable.RowHeaderWidth = Math.Max(minRowHeaderWidth, RowHeaderWidth); - } - - ListHasErrors = DataGridSourceHasErrors(); - - // build the list of columns and relationships - // wipe out the now invalid states - //ResetMouseState(); - - ResetUIState(); - - //layout.CaptionVisible = dataCursor == null ? false : true; - - OnDataSourceChanged(EventArgs.Empty); - } - - } - finally - { - gridState[GRIDSTATE_inSetListManager] = false; - // start painting again - if (beginUpdateInternal && Visible) - { - EndUpdateInternal(); - } - } - } - - /// - /// Gets or sets index of the selected row. - /// - // will set the position in the ListManager - // - [ - DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), - Browsable(false), - SRDescription(nameof(SR.DataGridSelectedIndexDescr)) - ] - public int CurrentRowIndex - { - get - { - if (originalState == null) - { - return listManager == null ? -1 : listManager.Position; - } - else - { - if (BindingContext == null) - { - return -1; - } - - CurrencyManager originalListManager = (CurrencyManager)BindingContext[originalState.DataSource, originalState.DataMember]; - return originalListManager.Position; - } - } - set - { - if (listManager == null) - { - throw new InvalidOperationException(SR.DataGridSetSelectIndex); - } - - if (originalState == null) - { - listManager.Position = value; - currentRow = value; - return; - } - - // if we have a this.ListManager, then this.BindingManager cannot be null - // - CurrencyManager originalListManager = (CurrencyManager)BindingContext[originalState.DataSource, originalState.DataMember]; - originalListManager.Position = value; - - // this is for parent rows - originalState.LinkingRow = originalState.DataGridRows[value]; - - // Invalidate everything - Invalidate(); - } - } - - /// - /// Gets the collection of tables for the grid. - /// - [ - SRCategory(nameof(SR.CatData)), - DesignerSerializationVisibility(DesignerSerializationVisibility.Content), - Localizable(true), - SRDescription(nameof(SR.DataGridGridTablesDescr)) - ] - public GridTableStylesCollection TableStyles - { - get - { - return dataGridTables; - } - } - - internal new int FontHeight - { - get - { - return fontHeight; - } - } - - internal AccessibleObject ParentRowsAccessibleObject - { - get - { - return parentRows.AccessibleObject; - } - } - - internal Rectangle ParentRowsBounds - { - get - { - return layout.ParentRows; - } - } - - /// - /// Gets or sets the color of the grid lines. - /// - [ - SRCategory(nameof(SR.CatColors)), - SRDescription(nameof(SR.DataGridGridLineColorDescr)) - ] - public Color GridLineColor - { - get - { - return gridLineBrush.Color; - } - set - { - if (gridLineBrush.Color != value) - { - if (value.IsEmpty) - { - throw new ArgumentException(string.Format(SR.DataGridEmptyColor, "GridLineColor")); - } - - gridLineBrush = new SolidBrush(value); - - Invalidate(layout.Data); - } - } - } - - protected virtual bool ShouldSerializeGridLineColor() - { - return !GridLineBrush.Equals(DefaultGridLineBrush); - } - - public void ResetGridLineColor() - { - if (ShouldSerializeGridLineColor()) - { - GridLineColor = DefaultGridLineBrush.Color; - } - } - - internal SolidBrush GridLineBrush - { - get - { - return gridLineBrush; - } - } - - /// - /// Gets or sets the line style of the grid. - /// - [ - SRCategory(nameof(SR.CatAppearance)), - DefaultValue(defaultGridLineStyle), - SRDescription(nameof(SR.DataGridGridLineStyleDescr)) - ] - public DataGridLineStyle GridLineStyle - { - get - { - return gridLineStyle; - } - set - { - //valid values are 0x0 to 0x1. - if (!ClientUtils.IsEnumValid(value, (int)value, (int)DataGridLineStyle.None, (int)DataGridLineStyle.Solid)) - { - throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridLineStyle)); - } - if (gridLineStyle != value) - { - gridLineStyle = value; - myGridTable.ResetRelationsUI(); - Invalidate(layout.Data); - } - } - } - - internal int GridLineWidth - { - get - { - Debug.Assert(GridLineStyle == DataGridLineStyle.Solid || GridLineStyle == DataGridLineStyle.None, "are there any other styles?"); - return GridLineStyle == DataGridLineStyle.Solid ? 1 : 0; - } - } - - /// - /// Gets or - /// sets the - /// way parent row labels are displayed. - /// - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), - DefaultValue(defaultParentRowsLabelStyle), - SRCategory(nameof(SR.CatDisplay)), - SRDescription(nameof(SR.DataGridParentRowsLabelStyleDescr)) - ] - public DataGridParentRowsLabelStyle ParentRowsLabelStyle - { - get - { - return parentRowsLabels; - } - - set - { - //valid values are 0x0 to 0x3 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)DataGridParentRowsLabelStyle.None, (int)DataGridParentRowsLabelStyle.Both)) - { - throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridParentRowsLabelStyle)); - } - - if (parentRowsLabels != value) - { - parentRowsLabels = value; - Invalidate(layout.ParentRows); - OnParentRowsLabelStyleChanged(EventArgs.Empty); - } - } - } - - private static readonly object EVENT_PARENTROWSLABELSTYLECHANGED = new object(); - - [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridOnParentRowsLabelStyleChangedDescr))] - public event EventHandler ParentRowsLabelStyleChanged - { - add => Events.AddHandler(EVENT_PARENTROWSLABELSTYLECHANGED, value); - remove => Events.RemoveHandler(EVENT_PARENTROWSLABELSTYLECHANGED, value); - } - - internal bool Initializing - { - get - { - return inInit; - } - } - - /// - /// Gets the index of the first visible column in a grid. - /// - [ - Browsable(false), - SRDescription(nameof(SR.DataGridFirstVisibleColumnDescr)) - ] - public int FirstVisibleColumn - { - get - { - return firstVisibleCol; - } - } - - /// - /// Gets or sets a value indicating whether the grid displays in flat mode. - /// - [ - DefaultValue(false), - SRCategory(nameof(SR.CatAppearance)), - SRDescription(nameof(SR.DataGridFlatModeDescr)) - ] - public bool FlatMode - { - get - { - return gridState[GRIDSTATE_isFlatMode]; - } - set - { - if (value != FlatMode) - { - gridState[GRIDSTATE_isFlatMode] = value; - Invalidate(layout.Inside); - OnFlatModeChanged(EventArgs.Empty); - } - } - } - - private static readonly object EVENT_FLATMODECHANGED = new object(); - - [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridOnFlatModeChangedDescr))] - public event EventHandler FlatModeChanged - { - add => Events.AddHandler(EVENT_FLATMODECHANGED, value); - remove => Events.RemoveHandler(EVENT_FLATMODECHANGED, value); - } - - /// - /// Gets or - /// sets the background color of all row and column headers. - /// - [ - SRCategory(nameof(SR.CatColors)), - SRDescription(nameof(SR.DataGridHeaderBackColorDescr)) - ] - public Color HeaderBackColor - { - get - { - return headerBackBrush.Color; - } - set - { - if (value.IsEmpty) - { - throw new ArgumentException(string.Format(SR.DataGridEmptyColor, "HeaderBackColor")); - } - - if (IsTransparentColor(value)) - { - throw new ArgumentException(SR.DataGridTransparentHeaderBackColorNotAllowed); - } - - if (!value.Equals(headerBackBrush.Color)) - { - headerBackBrush = new SolidBrush(value); - - if (layout.RowHeadersVisible) - { - Invalidate(layout.RowHeaders); - } - - if (layout.ColumnHeadersVisible) - { - Invalidate(layout.ColumnHeaders); - } - - Invalidate(layout.TopLeftHeader); - } - } - } - - internal SolidBrush HeaderBackBrush - { - get - { - return headerBackBrush; - } - } - - protected virtual bool ShouldSerializeHeaderBackColor() - { - return !HeaderBackBrush.Equals(DefaultHeaderBackBrush); - } - - public void ResetHeaderBackColor() - { - if (ShouldSerializeHeaderBackColor()) - { - HeaderBackColor = DefaultHeaderBackBrush.Color; - } - } - internal SolidBrush BackgroundBrush - { - get - { - return backgroundBrush; - } - } - - private void ResetBackgroundColor() - { - if (backgroundBrush != null && BackgroundBrush != DefaultBackgroundBrush) - { - backgroundBrush.Dispose(); - backgroundBrush = null; - } - backgroundBrush = DefaultBackgroundBrush; - } - - protected virtual bool ShouldSerializeBackgroundColor() - { - return !BackgroundBrush.Equals(DefaultBackgroundBrush); - } - - // using this property, the user can set the backGround color - /// - /// Gets or sets the background color of the grid. - /// - [ - SRCategory(nameof(SR.CatColors)), - SRDescription(nameof(SR.DataGridBackgroundColorDescr)) - ] - public Color BackgroundColor - { - get - { - return backgroundBrush.Color; - } - set - { - if (value.IsEmpty) - { - throw new ArgumentException(string.Format(SR.DataGridEmptyColor, "BackgroundColor")); - } - - if (!value.Equals(backgroundBrush.Color)) - { - - if (backgroundBrush != null && BackgroundBrush != DefaultBackgroundBrush) - { - backgroundBrush.Dispose(); - backgroundBrush = null; - } - backgroundBrush = new SolidBrush(value); - - Invalidate(layout.Inside); - OnBackgroundColorChanged(EventArgs.Empty); - } - } - } - - private static readonly object EVENT_BACKGROUNDCOLORCHANGED = new object(); - - [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridOnBackgroundColorChangedDescr))] - public event EventHandler BackgroundColorChanged - { - add => Events.AddHandler(EVENT_BACKGROUNDCOLORCHANGED, value); - remove => Events.RemoveHandler(EVENT_BACKGROUNDCOLORCHANGED, value); - } - - /// - /// Indicates whether the property should be persisted. - /// - [ - SRCategory(nameof(SR.CatAppearance)), - SRDescription(nameof(SR.DataGridHeaderFontDescr)) - ] - public Font HeaderFont - { - get - { - return (headerFont ?? Font); - } - set - { - if (value == null) - { - throw new ArgumentNullException(nameof(HeaderFont)); - } - - if (!value.Equals(headerFont)) - { - headerFont = value; - RecalculateFonts(); - PerformLayout(); - Invalidate(layout.Inside); - } - } - } - - protected bool ShouldSerializeHeaderFont() - { - return (headerFont != null); - } - - public void ResetHeaderFont() - { - if (headerFont != null) - { - headerFont = null; - RecalculateFonts(); - PerformLayout(); - Invalidate(layout.Inside); - } - } - - /// - /// Resets the property to its default value. - /// - /// - /// Gets or sets the foreground color of the grid's headers. - /// - [ - SRCategory(nameof(SR.CatColors)), - SRDescription(nameof(SR.DataGridHeaderForeColorDescr)) - ] - public Color HeaderForeColor - { - get - { - return headerForePen.Color; - } - set - { - if (value.IsEmpty) - { - throw new ArgumentException(string.Format(SR.DataGridEmptyColor, "HeaderForeColor")); - } - - if (!value.Equals(headerForePen.Color)) - { - headerForePen = new Pen(value); - headerForeBrush = new SolidBrush(value); - - if (layout.RowHeadersVisible) - { - Invalidate(layout.RowHeaders); - } - - if (layout.ColumnHeadersVisible) - { - Invalidate(layout.ColumnHeaders); - } - - Invalidate(layout.TopLeftHeader); - } - } - } - - protected virtual bool ShouldSerializeHeaderForeColor() - { - return !HeaderForePen.Equals(DefaultHeaderForePen); - } - - public void ResetHeaderForeColor() - { - if (ShouldSerializeHeaderForeColor()) - { - HeaderForeColor = DefaultHeaderForeBrush.Color; - } - } - - internal SolidBrush HeaderForeBrush - { - get - { - return headerForeBrush; - } - } - - internal Pen HeaderForePen - { - get - { - return headerForePen; - } - } - private void ResetHorizontalOffset() - { - horizontalOffset = 0; - negOffset = 0; - firstVisibleCol = 0; - numVisibleCols = 0; - lastTotallyVisibleCol = -1; - } - - internal int HorizontalOffset - { - get - { - return horizontalOffset; - } - set - { - //if (CompModSwitches.DataGridScrolling.TraceVerbose) Debug.WriteLine("DataGridScrolling: Set_HorizontalOffset, value = " + value.ToString()); - if (value < 0) - { - value = 0; - } - - // - // if the dataGrid is not bound ( listManager == null || gridTable == null) - // then use ResetHorizontalOffset(); - // - - int totalWidth = GetColumnWidthSum(); - int widthNotVisible = totalWidth - layout.Data.Width; - if (value > widthNotVisible && widthNotVisible > 0) - { - value = widthNotVisible; - } - - if (value == horizontalOffset) - { - return; - } - - int change = horizontalOffset - value; - horizScrollBar.Value = value; - Rectangle scroll = layout.Data; - if (layout.ColumnHeadersVisible) - { - scroll = Rectangle.Union(scroll, layout.ColumnHeaders); - } - - horizontalOffset = value; - - firstVisibleCol = ComputeFirstVisibleColumn(); - // update the lastTotallyVisibleCol - ComputeVisibleColumns(); - - if (gridState[GRIDSTATE_isScrolling]) - { - // if the user did not click on the grid yet, then do not put the edit - // control when scrolling - if (currentCol >= firstVisibleCol && currentCol < firstVisibleCol + numVisibleCols - 1 && (gridState[GRIDSTATE_isEditing] || gridState[GRIDSTATE_isNavigating])) - { - Edit(); - } - else - { - EndEdit(); - } - - // isScrolling is set to TRUE when the user scrolls. - // once we move the edit box, we finished processing the scroll event, so set isScrolling to FALSE - // to set isScrolling to TRUE, we need another scroll event. - gridState[GRIDSTATE_isScrolling] = false; - } - else - { - EndEdit(); - } - - RECT[] rects = CreateScrollableRegion(scroll); - ScrollRectangles(rects, change); - OnScroll(EventArgs.Empty); - } - } - - private void ScrollRectangles(RECT[] rects, int change) - { - if (rects != null) - { - RECT scroll; - if (isRightToLeft()) - { - change = -change; - } - - for (int r = 0; r < rects.Length; r++) - { - scroll = rects[r]; - SafeNativeMethods.ScrollWindow(new HandleRef(this, Handle), - change, - 0, - ref scroll, - ref scroll); - } - } - } - - [ - SRDescription(nameof(SR.DataGridHorizScrollBarDescr)) - ] - protected ScrollBar HorizScrollBar - { - get - { - return horizScrollBar; - } - } - - /// - /// Retrieves a value indicating whether odd and even - /// rows are painted using a different background color. - /// - // Cleanup eventually to be static. - internal bool LedgerStyle - { - get - { - return gridState[GRIDSTATE_isLedgerStyle]; - } - /* - set { - if (isLedgerStyle != value) { - isLedgerStyle = value; - InvalidateInside(); - } - } - */ - } - - /// - /// Indicates whether the property should be persisted. - /// - [ - SRCategory(nameof(SR.CatColors)), - SRDescription(nameof(SR.DataGridLinkColorDescr)) - ] - public Color LinkColor - { - get - { - return linkBrush.Color; - } - set - { - if (value.IsEmpty) - { - throw new ArgumentException(string.Format(SR.DataGridEmptyColor, "LinkColor")); - } - - if (!linkBrush.Color.Equals(value)) - { - linkBrush = new SolidBrush(value); - Invalidate(layout.Data); - } - } - } - - internal virtual bool ShouldSerializeLinkColor() - { - return !LinkBrush.Equals(DefaultLinkBrush); - } - - public void ResetLinkColor() - { - if (ShouldSerializeLinkColor()) - { - LinkColor = DefaultLinkBrush.Color; - } - } - - internal Brush LinkBrush - { - get - { - return linkBrush; - } - } - - /// - /// Gets - /// or sets the color a link changes to when - /// the mouse pointer moves over it. - /// - [ - SRDescription(nameof(SR.DataGridLinkHoverColorDescr)), - SRCategory(nameof(SR.CatColors)), - Browsable(false), - EditorBrowsable(EditorBrowsableState.Never) - - ] - public Color LinkHoverColor - { - get - { - return LinkColor; - } - set - { - } - } - - protected virtual bool ShouldSerializeLinkHoverColor() - { - return false; - // return !LinkHoverBrush.Equals(defaultLinkHoverBrush); - } - - public void ResetLinkHoverColor() - { - /* - if (ShouldSerializeLinkHoverColor()) - LinkHoverColor = defaultLinkHoverBrush.Color;*/ - } - - /// - /// Indicates whether the property should be - /// persisted. - /// - internal Font LinkFont - { - get - { - return linkFont; - } - } - - internal int LinkFontHeight - { - get - { - return linkFontHeight; - } - } - - /// - /// Gets or sets a value - /// that specifies which links are shown and in what context. - /// - [ - DefaultValue(true), - SRDescription(nameof(SR.DataGridNavigationModeDescr)), - SRCategory(nameof(SR.CatBehavior)) - ] - public bool AllowNavigation - { - get - { - return gridState[GRIDSTATE_allowNavigation]; - } - set - { - if (AllowNavigation != value) - { - gridState[GRIDSTATE_allowNavigation] = value; - // let the Caption know about this: - Caption.BackButtonActive = !parentRows.IsEmpty() && (value); - Caption.BackButtonVisible = Caption.BackButtonActive; - RecreateDataGridRows(); - - OnAllowNavigationChanged(EventArgs.Empty); - } - } - } - - private static readonly object EVENT_ALLOWNAVIGATIONCHANGED = new object(); - - [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridOnNavigationModeChangedDescr))] - public event EventHandler AllowNavigationChanged - { - add => Events.AddHandler(EVENT_ALLOWNAVIGATIONCHANGED, value); - remove => Events.RemoveHandler(EVENT_ALLOWNAVIGATIONCHANGED, value); - } - - [ - Browsable(false), EditorBrowsable(EditorBrowsableState.Never) - ] - public override Cursor Cursor - { - // get the cursor out of the propertyGrid. - get - { - return base.Cursor; - } - - set - { - base.Cursor = value; - } - } - - [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler CursorChanged - { - add => base.CursorChanged += value; - remove => base.CursorChanged -= value; - } - - [ - Browsable(false), EditorBrowsable(EditorBrowsableState.Never) - ] - public override Image BackgroundImage - { - // get the BackgroundImage out of the propertyGrid. - get - { - return base.BackgroundImage; - } - - set - { - base.BackgroundImage = value; - } - } - - [ - Browsable(false), EditorBrowsable(EditorBrowsableState.Never) - ] - public override ImageLayout BackgroundImageLayout - { - // get the BackgroundImage out of the propertyGrid. - get - { - return base.BackgroundImageLayout; - } - - set - { - base.BackgroundImageLayout = value; - } - } - - [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler BackgroundImageChanged - { - add => base.BackgroundImageChanged += value; - remove => base.BackgroundImageChanged -= value; - } - - [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler BackgroundImageLayoutChanged - { - add => base.BackgroundImageLayoutChanged += value; - remove => base.BackgroundImageLayoutChanged -= value; - } - - /// - /// Gets or sets the background color of parent rows. - /// - [ - SRCategory(nameof(SR.CatColors)), - SRDescription(nameof(SR.DataGridParentRowsBackColorDescr)) - ] - public Color ParentRowsBackColor - { - get - { - return parentRows.BackColor; - } - set - { - if (IsTransparentColor(value)) - { - throw new ArgumentException(SR.DataGridTransparentParentRowsBackColorNotAllowed); - } - - parentRows.BackColor = value; - } - } - - internal SolidBrush ParentRowsBackBrush - { - get - { - return parentRows.BackBrush; - } - } - - /// - /// Indicates whether the property should be - /// persisted. - /// - protected virtual bool ShouldSerializeParentRowsBackColor() - { - return !ParentRowsBackBrush.Equals(DefaultParentRowsBackBrush); - } - - private void ResetParentRowsBackColor() - { - if (ShouldSerializeParentRowsBackColor()) - { - parentRows.BackBrush = DefaultParentRowsBackBrush; - } - } - - /// - /// Gets or sets the foreground color of parent rows. - /// - [ - SRCategory(nameof(SR.CatColors)), - SRDescription(nameof(SR.DataGridParentRowsForeColorDescr)) - ] - public Color ParentRowsForeColor - { - get - { - return parentRows.ForeColor; - } - set - { - parentRows.ForeColor = value; - } - } - - internal SolidBrush ParentRowsForeBrush - { - get - { - return parentRows.ForeBrush; - } - } - - /// - /// Indicates whether the property should be - /// persisted. - /// - protected virtual bool ShouldSerializeParentRowsForeColor() - { - return !ParentRowsForeBrush.Equals(DefaultParentRowsForeBrush); - } - - private void ResetParentRowsForeColor() - { - if (ShouldSerializeParentRowsForeColor()) - { - parentRows.ForeBrush = DefaultParentRowsForeBrush; - } - } - - /// - /// Gets - /// or sets the default width of the grid columns in - /// pixels. - /// - [ - DefaultValue(defaultPreferredColumnWidth), - SRCategory(nameof(SR.CatLayout)), - SRDescription(nameof(SR.DataGridPreferredColumnWidthDescr)), - TypeConverter(typeof(DataGridPreferredColumnWidthTypeConverter)) - ] - public int PreferredColumnWidth - { - get - { - return preferredColumnWidth; - } - set - { - if (value < 0) - { - throw new ArgumentException(SR.DataGridColumnWidth, "PreferredColumnWidth"); - } - - if (preferredColumnWidth != value) - { - preferredColumnWidth = value; - } - } - } - - /// - /// Gets or sets the preferred row height for the control. - /// - [ - SRCategory(nameof(SR.CatLayout)), - SRDescription(nameof(SR.DataGridPreferredRowHeightDescr)) - ] - public int PreferredRowHeight - { - get - { - return preferredRowHeight; - } - set - { - if (value < 0) - { - throw new ArgumentException(SR.DataGridRowRowHeight); - } - - preferredRowHeight = value; - } - } - - private void ResetPreferredRowHeight() - { - preferredRowHeight = defaultFontHeight + 3; - } - - protected bool ShouldSerializePreferredRowHeight() - { - return preferredRowHeight != defaultFontHeight + 3; - } - - /// - /// Gets or sets a value indicating whether the grid - /// is in read-only mode. - /// - [ - DefaultValue(false), - SRCategory(nameof(SR.CatBehavior)), - SRDescription(nameof(SR.DataGridReadOnlyDescr)) - ] - public bool ReadOnly - { - get - { - return gridState[GRIDSTATE_readOnlyMode]; - } - set - { - if (ReadOnly != value) - { - bool recreateRows = false; - if (value) - { - // AllowAdd happens to have the same boolean value as whether we need to recreate rows. - recreateRows = policy.AllowAdd; - - policy.AllowRemove = false; - policy.AllowEdit = false; - policy.AllowAdd = false; - } - else - { - recreateRows |= policy.UpdatePolicy(listManager, value); - } - gridState[GRIDSTATE_readOnlyMode] = value; - DataGridRow[] dataGridRows = DataGridRows; - if (recreateRows) - { - RecreateDataGridRows(); - - // keep the selected rows - DataGridRow[] currentDataGridRows = DataGridRows; - int rowCount = Math.Min(currentDataGridRows.Length, dataGridRows.Length); - for (int i = 0; i < rowCount; i++) - { - if (dataGridRows[i].Selected) - { - currentDataGridRows[i].Selected = true; - } - } - } - - // the addnew row needs to be updated. - PerformLayout(); - InvalidateInside(); - OnReadOnlyChanged(EventArgs.Empty); - } - } - } - - private static readonly object EVENT_READONLYCHANGED = new object(); - - [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridOnReadOnlyChangedDescr))] - public event EventHandler ReadOnlyChanged - { - add => Events.AddHandler(EVENT_READONLYCHANGED, value); - remove => Events.RemoveHandler(EVENT_READONLYCHANGED, value); - } - - /// - /// Gets - /// or sets a value indicating if the grid's column headers are visible. - /// - [ - SRCategory(nameof(SR.CatDisplay)), - DefaultValue(true), - SRDescription(nameof(SR.DataGridColumnHeadersVisibleDescr)) - ] - public bool ColumnHeadersVisible - { - get - { - return gridState[GRIDSTATE_columnHeadersVisible]; - } - set - { - if (ColumnHeadersVisible != value) - { - gridState[GRIDSTATE_columnHeadersVisible] = value; - layout.ColumnHeadersVisible = value; - PerformLayout(); - InvalidateInside(); - } - } - } - - /// - /// Gets or sets a value indicating whether the parent rows of a table are - /// visible. - /// - [ - SRCategory(nameof(SR.CatDisplay)), - DefaultValue(true), - SRDescription(nameof(SR.DataGridParentRowsVisibleDescr)) - ] - public bool ParentRowsVisible - { - get - { - return layout.ParentRowsVisible; - } - set - { - if (layout.ParentRowsVisible != value) - { - SetParentRowsVisibility(value); - - // update the caption: parentDownVisible == false corresponds to DownButtonDown == true; - // - caption.SetDownButtonDirection(!value); - - OnParentRowsVisibleChanged(EventArgs.Empty); - } - } - } - - private static readonly object EVENT_PARENTROWSVISIBLECHANGED = new object(); - - [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridOnParentRowsVisibleChangedDescr))] - public event EventHandler ParentRowsVisibleChanged - { - add => Events.AddHandler(EVENT_PARENTROWSVISIBLECHANGED, value); - remove => Events.RemoveHandler(EVENT_PARENTROWSVISIBLECHANGED, value); - } - - internal bool ParentRowsIsEmpty() - { - return parentRows.IsEmpty(); - } - - /// - /// Gets or sets a value indicating whether the data grid's row headers are - /// visible. - /// - [ - SRCategory(nameof(SR.CatDisplay)), - DefaultValue(true), - SRDescription(nameof(SR.DataGridRowHeadersVisibleDescr)) - ] - public bool RowHeadersVisible - { - get - { - return gridState[GRIDSTATE_rowHeadersVisible]; - } - set - { - if (RowHeadersVisible != value) - { - gridState[GRIDSTATE_rowHeadersVisible] = value; - PerformLayout(); - InvalidateInside(); - } - } - } - - [ - SRCategory(nameof(SR.CatLayout)), - DefaultValue(defaultRowHeaderWidth), - SRDescription(nameof(SR.DataGridRowHeaderWidthDescr)) - ] - public int RowHeaderWidth - { - get - { - return rowHeaderWidth; - } - set - { - value = Math.Max(minRowHeaderWidth, value); - if (rowHeaderWidth != value) - { - rowHeaderWidth = value; - if (layout.RowHeadersVisible) - { - PerformLayout(); - InvalidateInside(); - } - } - } - } - - /// - /// Gets or sets the width of headers. - /// - [ - Browsable(false), EditorBrowsable(EditorBrowsableState.Never), - DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), - Bindable(false) - ] - public override string Text - { - get - { - return base.Text; - } - set - { - base.Text = value; - } - } - - [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler TextChanged - { - add => base.TextChanged += value; - remove => base.TextChanged -= value; - } - - /// - /// Gets the vertical scroll bar of the control. - /// - [ - Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced), - SRDescription(nameof(SR.DataGridVertScrollBarDescr)) - ] - protected ScrollBar VertScrollBar - { - get - { - return vertScrollBar; - } - } - - /// - /// Gets the number of visible columns. - /// - [ - Browsable(false), - SRDescription(nameof(SR.DataGridVisibleColumnCountDescr)) - ] - public int VisibleColumnCount - { - get - { - return Math.Min(numVisibleCols, myGridTable == null ? 0 : myGridTable.GridColumnStyles.Count); - } - } - - /// - /// Gets the number of rows visible. - /// - [ - Browsable(false), - SRDescription(nameof(SR.DataGridVisibleRowCountDescr)) - ] - public int VisibleRowCount - { - get - { - return numVisibleRows; - } - } - - /// - /// Gets or sets the value of the cell at - /// the specified the row and column. - /// - public object this[int rowIndex, int columnIndex] - { - get - { - EnsureBound(); - if (rowIndex < 0 || rowIndex >= DataGridRowsLength) - { - throw new ArgumentOutOfRangeException(nameof(rowIndex)); - } - - if (columnIndex < 0 || columnIndex >= myGridTable.GridColumnStyles.Count) - { - throw new ArgumentOutOfRangeException(nameof(columnIndex)); - } - - CurrencyManager listManager = this.listManager; - DataGridColumnStyle column = myGridTable.GridColumnStyles[columnIndex]; - return column.GetColumnValueAtRow(listManager, rowIndex); - } - set - { - EnsureBound(); - if (rowIndex < 0 || rowIndex >= DataGridRowsLength) - { - throw new ArgumentOutOfRangeException(nameof(rowIndex)); - } - - if (columnIndex < 0 || columnIndex >= myGridTable.GridColumnStyles.Count) - { - throw new ArgumentOutOfRangeException(nameof(columnIndex)); - } - - CurrencyManager listManager = this.listManager; - if (listManager.Position != rowIndex) - { - listManager.Position = rowIndex; - } - - DataGridColumnStyle column = myGridTable.GridColumnStyles[columnIndex]; - column.SetColumnValueAtRow(listManager, rowIndex, value); - - // invalidate the bounds of the cell only if the cell is visible - if (columnIndex >= firstVisibleCol && columnIndex <= firstVisibleCol + numVisibleCols - 1 && - rowIndex >= firstVisibleRow && rowIndex <= firstVisibleRow + numVisibleRows) - { - Rectangle bounds = GetCellBounds(rowIndex, columnIndex); - Invalidate(bounds); - } - } - } - - /// - /// Gets or sets the value of a specified . - /// - public object this[DataGridCell cell] - { - get - { - return this[cell.RowNumber, cell.ColumnNumber]; - } - set - { - this[cell.RowNumber, cell.ColumnNumber] = value; - } - } - - private void WireTableStylePropChanged(DataGridTableStyle gridTable) - { - gridTable.GridLineColorChanged += new EventHandler(GridLineColorChanged); - gridTable.GridLineStyleChanged += new EventHandler(GridLineStyleChanged); - gridTable.HeaderBackColorChanged += new EventHandler(HeaderBackColorChanged); - gridTable.HeaderFontChanged += new EventHandler(HeaderFontChanged); - gridTable.HeaderForeColorChanged += new EventHandler(HeaderForeColorChanged); - gridTable.LinkColorChanged += new EventHandler(LinkColorChanged); - gridTable.LinkHoverColorChanged += new EventHandler(LinkHoverColorChanged); - gridTable.PreferredColumnWidthChanged += new EventHandler(PreferredColumnWidthChanged); - gridTable.RowHeadersVisibleChanged += new EventHandler(RowHeadersVisibleChanged); - gridTable.ColumnHeadersVisibleChanged += new EventHandler(ColumnHeadersVisibleChanged); - gridTable.RowHeaderWidthChanged += new EventHandler(RowHeaderWidthChanged); - gridTable.AllowSortingChanged += new EventHandler(AllowSortingChanged); - } - - private void UnWireTableStylePropChanged(DataGridTableStyle gridTable) - { - gridTable.GridLineColorChanged -= new EventHandler(GridLineColorChanged); - gridTable.GridLineStyleChanged -= new EventHandler(GridLineStyleChanged); - gridTable.HeaderBackColorChanged -= new EventHandler(HeaderBackColorChanged); - gridTable.HeaderFontChanged -= new EventHandler(HeaderFontChanged); - gridTable.HeaderForeColorChanged -= new EventHandler(HeaderForeColorChanged); - gridTable.LinkColorChanged -= new EventHandler(LinkColorChanged); - gridTable.LinkHoverColorChanged -= new EventHandler(LinkHoverColorChanged); - gridTable.PreferredColumnWidthChanged -= new EventHandler(PreferredColumnWidthChanged); - gridTable.RowHeadersVisibleChanged -= new EventHandler(RowHeadersVisibleChanged); - gridTable.ColumnHeadersVisibleChanged -= new EventHandler(ColumnHeadersVisibleChanged); - gridTable.RowHeaderWidthChanged -= new EventHandler(RowHeaderWidthChanged); - gridTable.AllowSortingChanged -= new EventHandler(AllowSortingChanged); - } - - /// - /// DataSource events are handled - /// - private void WireDataSource() - { - Debug.WriteLineIf(CompModSwitches.DataGridCursor.TraceVerbose, "DataGridCursor: WireDataSource"); - Debug.Assert(listManager != null, "Can't wire up to a null DataSource"); - listManager.CurrentChanged += currentChangedHandler; - listManager.PositionChanged += positionChangedHandler; - listManager.ItemChanged += itemChangedHandler; - listManager.MetaDataChanged += metaDataChangedHandler; - } - - private void UnWireDataSource() - { - Debug.WriteLineIf(CompModSwitches.DataGridCursor.TraceVerbose, "DataGridCursor: UnWireDataSource"); - Debug.Assert(listManager != null, "Can't un wire from a null DataSource"); - listManager.CurrentChanged -= currentChangedHandler; - listManager.PositionChanged -= positionChangedHandler; - listManager.ItemChanged -= itemChangedHandler; - listManager.MetaDataChanged -= metaDataChangedHandler; - } - - // This is called after a row has been added. And I think whenever - // a row gets deleted, etc. - // We recreate our datagrid rows at this point. - private void DataSource_Changed(object sender, EventArgs ea) - { - Debug.WriteLineIf(CompModSwitches.DataGridCursor.TraceVerbose, "DataGridCursor: DataSource_Changed"); - - // the grid will receive the dataSource_Changed event when - // allowAdd changes on the dataView. - policy.UpdatePolicy(ListManager, ReadOnly); - if (gridState[GRIDSTATE_inListAddNew]) - { - // we are adding a new row - // keep the old rows, w/ their height, expanded/collapsed information - // - Debug.Assert(policy.AllowAdd, "how can we add a new row if the policy does not allow this?"); - Debug.Assert(DataGridRowsLength == DataGridRows.Length, "how can this fail?"); - - DataGridRow[] gridRows = DataGridRows; - int currentRowCount = DataGridRowsLength; - // put the added row: - // - gridRows[currentRowCount - 1] = new DataGridRelationshipRow(this, myGridTable, currentRowCount - 1); - SetDataGridRows(gridRows, currentRowCount); - } - else if (gridState[GRIDSTATE_inAddNewRow] && !gridState[GRIDSTATE_inDeleteRow]) - { - // when the backEnd adds a row and we are still inAddNewRow - listManager.CancelCurrentEdit(); - gridState[GRIDSTATE_inAddNewRow] = false; - RecreateDataGridRows(); - } - else if (!gridState[GRIDSTATE_inDeleteRow]) - { - RecreateDataGridRows(); - currentRow = Math.Min(currentRow, listManager.Count); - } - - bool oldListHasErrors = ListHasErrors; - ListHasErrors = DataGridSourceHasErrors(); - // if we changed the ListHasErrors, then the grid is already invalidated - if (oldListHasErrors == ListHasErrors) - { - InvalidateInside(); - } - } - - private void GridLineColorChanged(object sender, EventArgs e) - { - Invalidate(layout.Data); - } - private void GridLineStyleChanged(object sender, EventArgs e) - { - myGridTable.ResetRelationsUI(); - Invalidate(layout.Data); - } - private void HeaderBackColorChanged(object sender, EventArgs e) - { - if (layout.RowHeadersVisible) - { - Invalidate(layout.RowHeaders); - } - - if (layout.ColumnHeadersVisible) - { - Invalidate(layout.ColumnHeaders); - } - - Invalidate(layout.TopLeftHeader); - } - private void HeaderFontChanged(object sender, EventArgs e) - { - RecalculateFonts(); - PerformLayout(); - Invalidate(layout.Inside); - } - private void HeaderForeColorChanged(object sender, EventArgs e) - { - if (layout.RowHeadersVisible) - { - Invalidate(layout.RowHeaders); - } - - if (layout.ColumnHeadersVisible) - { - Invalidate(layout.ColumnHeaders); - } - - Invalidate(layout.TopLeftHeader); - } - private void LinkColorChanged(object sender, EventArgs e) - { - Invalidate(layout.Data); - } - private void LinkHoverColorChanged(object sender, EventArgs e) - { - Invalidate(layout.Data); - } - private void PreferredColumnWidthChanged(object sender, EventArgs e) - { - // reset the dataGridRows - SetDataGridRows(null, DataGridRowsLength); - // layout the horizontal scroll bar - PerformLayout(); - // invalidate everything - Invalidate(); - } - private void RowHeadersVisibleChanged(object sender, EventArgs e) - { - layout.RowHeadersVisible = myGridTable == null ? false : myGridTable.RowHeadersVisible; - PerformLayout(); - InvalidateInside(); - } - private void ColumnHeadersVisibleChanged(object sender, EventArgs e) - { - layout.ColumnHeadersVisible = myGridTable == null ? false : myGridTable.ColumnHeadersVisible; - PerformLayout(); - InvalidateInside(); - } - private void RowHeaderWidthChanged(object sender, EventArgs e) - { - if (layout.RowHeadersVisible) - { - PerformLayout(); - InvalidateInside(); - } - } - private void AllowSortingChanged(object sender, EventArgs e) - { - if (!myGridTable.AllowSorting && listManager != null) - { - IList list = listManager.List; - if (list is IBindingList) - { - ((IBindingList)list).RemoveSort(); - } - } - } - - private void DataSource_RowChanged(object sender, EventArgs ea) - { - Debug.WriteLineIf(CompModSwitches.DataGridCursor.TraceVerbose, "DataGridCursor: DataSource_RowChanged"); - // it may be the case that our cache was not updated - // to the latest changes in the list : CurrentChanged is fired before - // ListChanged. - // So invalidate the row if there is something to invalidate - DataGridRow[] rows = DataGridRows; - if (currentRow < DataGridRowsLength) - { - InvalidateRow(currentRow); - } - } - - /// - /// Fired by the DataSource when row position moves. - /// - private void DataSource_PositionChanged(object sender, EventArgs ea) - { -#if DEBUG - inDataSource_PositionChanged = true; -#endif - Debug.WriteLineIf(CompModSwitches.DataGridCursor.TraceVerbose, "DataGridCursor: DataSource_PositionChanged to " + listManager.Position.ToString(CultureInfo.InvariantCulture)); - // the grid will get the PositionChanged event - // before the OnItemChanged event when a row will be deleted in the backEnd; - // we still want to keep the old rows when the user deletes the rows using the grid - // and we do not want to do the same work twice when the user adds a row via the grid - if (DataGridRowsLength > listManager.Count + (policy.AllowAdd ? 1 : 0) && !gridState[GRIDSTATE_inDeleteRow]) - { - Debug.Assert(!gridState[GRIDSTATE_inAddNewRow] && !gridState[GRIDSTATE_inListAddNew], "how can the list decrease when we are adding a row?"); - RecreateDataGridRows(); - } - if (ListManager.Position != currentRow) - { - CurrentCell = new DataGridCell(listManager.Position, currentCol); - - } -#if DEBUG - inDataSource_PositionChanged = false; -#endif - } - - internal void DataSource_MetaDataChanged(object sender, EventArgs e) - { - MetaDataChanged(); - } - - private bool DataGridSourceHasErrors() - { - if (listManager == null) - { - return false; - } - - for (int i = 0; i < listManager.Count; i++) - { - object errObj = listManager[i]; - if (errObj is IDataErrorInfo) - { - string errString = ((IDataErrorInfo)errObj).Error; - if (errString != null && errString.Length != 0) - { - return true; - } - } - } - return false; - } - - private void TableStylesCollectionChanged(object sender, CollectionChangeEventArgs ccea) - { - // if the users changed the collection of tableStyles - if (sender != dataGridTables) - { - return; - } - - if (listManager == null) - { - return; - } - - if (ccea.Action == CollectionChangeAction.Add) - { - DataGridTableStyle tableStyle = (DataGridTableStyle)ccea.Element; - if (listManager.GetListName().Equals(tableStyle.MappingName)) - { - Debug.Assert(myGridTable.IsDefault, "if the table is not default, then it had a name. how can one add another table to the collection w/ the same name and not throw an exception"); - SetDataGridTable(tableStyle, true); // true for forcing column creation - SetDataGridRows(null, 0); - } - } - else if (ccea.Action == CollectionChangeAction.Remove) - { - DataGridTableStyle tableStyle = (DataGridTableStyle)ccea.Element; - if (myGridTable.MappingName.Equals(tableStyle.MappingName)) - { - Debug.Assert(myGridTable.IsDefault, "if the table is not default, then it had a name. how can one add another table to the collection w/ the same name and not throw an exception"); - defaultTableStyle.GridColumnStyles.ResetDefaultColumnCollection(); - SetDataGridTable(defaultTableStyle, true); // true for forcing column creation - SetDataGridRows(null, 0); - } - } - else - { - Debug.Assert(ccea.Action == CollectionChangeAction.Refresh, "what else is possible?"); - // we have to search to see if the collection of table styles contains one - // w/ the same name as the list in the dataGrid - - DataGridTableStyle newGridTable = dataGridTables[listManager.GetListName()]; - if (newGridTable == null) - { - if (!myGridTable.IsDefault) - { - // get rid of the old gridColumns - defaultTableStyle.GridColumnStyles.ResetDefaultColumnCollection(); - SetDataGridTable(defaultTableStyle, true); // true for forcing column creation - SetDataGridRows(null, 0); - } - } - else - { - SetDataGridTable(newGridTable, true); // true for forcing column creation - SetDataGridRows(null, 0); - } - } - } - - private void DataSource_ItemChanged(object sender, ItemChangedEventArgs ea) - { - Debug.WriteLineIf(CompModSwitches.DataGridCursor.TraceVerbose, "DataGridCursor: DataSource_ItemChanged at index " + ea.Index.ToString(CultureInfo.InvariantCulture)); - - // if ea.Index == -1, then we invalidate all rows. - if (ea.Index == -1) - { - DataSource_Changed(sender, EventArgs.Empty); - /* - // if there are rows which are invisible, it is more efficient to invalidata layout.Data - if (numVisibleRows <= dataGridRowsLength) - Invalidate(layout.Data); - else - { - Debug.Assert(firstVisibleRow == 0, "if all rows are visible, then how come that first row is not visible?"); - for (int i = 0; i < numVisibleRows; i++) - InvalidateRow(firstVisibleRow + numVisibleRows); - } - */ - } - else - { - // let's see how we are doing w/ the errors - object errObj = listManager[ea.Index]; - bool oldListHasErrors = ListHasErrors; - if (errObj is IDataErrorInfo) - { - if (((IDataErrorInfo)errObj).Error.Length != 0) - { - ListHasErrors = true; - } - else if (ListHasErrors) - { - // maybe there was an error that now is fixed - ListHasErrors = DataGridSourceHasErrors(); - } - } - - // Invalidate the row only if we did not change the ListHasErrors - if (oldListHasErrors == ListHasErrors) - { - InvalidateRow(ea.Index); - } - - // we need to update the edit box: - // we update the text in the edit box only when the currentRow - // equals the ea.Index - if (editColumn != null && ea.Index == currentRow) - { - editColumn.UpdateUI(ListManager, ea.Index, null); - } - } - } - - protected virtual void OnBorderStyleChanged(EventArgs e) - { - if (Events[EVENT_BORDERSTYLECHANGED] is EventHandler eh) - { - eh(this, e); - } - } - - protected virtual void OnCaptionVisibleChanged(EventArgs e) - { - if (Events[EVENT_CAPTIONVISIBLECHANGED] is EventHandler eh) - { - eh(this, e); - } - } - - protected virtual void OnCurrentCellChanged(EventArgs e) - { - if (Events[EVENT_CURRENTCELLCHANGED] is EventHandler eh) - { - eh(this, e); - } - } - - protected virtual void OnFlatModeChanged(EventArgs e) - { - if (Events[EVENT_FLATMODECHANGED] is EventHandler eh) - { - eh(this, e); - } - } - - protected virtual void OnBackgroundColorChanged(EventArgs e) - { - if (Events[EVENT_BACKGROUNDCOLORCHANGED] is EventHandler eh) - { - eh(this, e); - } - } - - protected virtual void OnAllowNavigationChanged(EventArgs e) - { - if (Events[EVENT_ALLOWNAVIGATIONCHANGED] is EventHandler eh) - { - eh(this, e); - } - } - - protected virtual void OnParentRowsVisibleChanged(EventArgs e) - { - if (Events[EVENT_PARENTROWSVISIBLECHANGED] is EventHandler eh) - { - eh(this, e); - } - } - - protected virtual void OnParentRowsLabelStyleChanged(EventArgs e) - { - if (Events[EVENT_PARENTROWSLABELSTYLECHANGED] is EventHandler eh) - { - eh(this, e); - } - } - - protected virtual void OnReadOnlyChanged(EventArgs e) - { - if (Events[EVENT_READONLYCHANGED] is EventHandler eh) - { - eh(this, e); - } - } - - /// - /// Raises the - /// event. - /// - protected void OnNavigate(NavigateEventArgs e) - { - onNavigate?.Invoke(this, e); - } - - /* - /// - /// Raises the event. - /// - protected void OnColumnResize(EventArgs e) { - RaiseEvent(EVENT_COLUMNRESIZE, e); - } - - internal void OnLinkClick(EventArgs e) { - RaiseEvent(EVENT_LINKCLICKED, e); - } - */ - - internal void OnNodeClick(EventArgs e) - { - // if we expanded/collapsed the RelationshipRow - // then we need to layout the vertical scroll bar - // - PerformLayout(); - - // also, we need to let the hosted edit control that its - // boundaries possibly changed. do this with a call to Edit() - // do this only if the firstVisibleColumn is the editColumn - // - GridColumnStylesCollection columns = myGridTable.GridColumnStyles; - if (firstVisibleCol > -1 && firstVisibleCol < columns.Count && columns[firstVisibleCol] == editColumn) - { - Edit(); - } - - // Raise the event for the event listeners - ((EventHandler)Events[EVENT_NODECLICKED])?.Invoke(this, e); - } - - /// - /// Raises the event. - /// - protected void OnRowHeaderClick(EventArgs e) - { - onRowHeaderClick?.Invoke(this, e); - } - - /// - /// Raises the event. - /// - protected void OnScroll(EventArgs e) - { - // reset the toolTip information - if (ToolTipProvider != null) - { - ResetToolTip(); - } ((EventHandler)Events[EVENT_SCROLL])?.Invoke(this, e); - } - - /// - /// Listens - /// for the horizontal scrollbar's scroll - /// event. - /// - protected virtual void GridHScrolled(object sender, ScrollEventArgs se) - { - if (!Enabled) - { - return; - } - - if (DataSource == null) - { - Debug.Fail("Horizontal Scrollbar should be disabled without a DataSource."); - return; - } - - gridState[GRIDSTATE_isScrolling] = true; - -#if DEBUG - - Debug.WriteLineIf(CompModSwitches.DataGridScrolling.TraceVerbose, "DataGridScrolling: in GridHScrolled: the scroll event type:"); - switch (se.Type) - { - case ScrollEventType.SmallIncrement: - Debug.WriteLineIf(CompModSwitches.DataGridScrolling.TraceVerbose, "small increment"); - break; - case ScrollEventType.SmallDecrement: - Debug.WriteLineIf(CompModSwitches.DataGridScrolling.TraceVerbose, "small decrement"); - break; - case ScrollEventType.LargeIncrement: - Debug.WriteLineIf(CompModSwitches.DataGridScrolling.TraceVerbose, "Large decrement"); - break; - case ScrollEventType.LargeDecrement: - Debug.WriteLineIf(CompModSwitches.DataGridScrolling.TraceVerbose, "small decrement"); - break; - case ScrollEventType.ThumbPosition: - Debug.WriteLineIf(CompModSwitches.DataGridScrolling.TraceVerbose, "Thumb Position"); - break; - case ScrollEventType.ThumbTrack: - Debug.WriteLineIf(CompModSwitches.DataGridScrolling.TraceVerbose, "Thumb Track"); - break; - case ScrollEventType.First: - Debug.WriteLineIf(CompModSwitches.DataGridScrolling.TraceVerbose, "First"); - break; - case ScrollEventType.Last: - Debug.WriteLineIf(CompModSwitches.DataGridScrolling.TraceVerbose, "Last"); - break; - case ScrollEventType.EndScroll: - Debug.WriteLineIf(CompModSwitches.DataGridScrolling.TraceVerbose, "EndScroll"); - break; - } - -#endif // DEBUG - - if (se.Type == ScrollEventType.SmallIncrement || - se.Type == ScrollEventType.SmallDecrement) - { - int dCols = (se.Type == ScrollEventType.SmallIncrement) ? 1 : -1; - if (se.Type == ScrollEventType.SmallDecrement && negOffset == 0) - { - GridColumnStylesCollection cols = myGridTable.GridColumnStyles; - // if the column before the first visible column has width == 0 then skip it - for (int i = firstVisibleCol - 1; i >= 0 && cols[i].Width == 0; i--) - { - dCols--; - } - } - - if (se.Type == ScrollEventType.SmallIncrement && negOffset == 0) - { - GridColumnStylesCollection cols = myGridTable.GridColumnStyles; - for (int i = firstVisibleCol; i > -1 && i < cols.Count && cols[i].Width == 0; i++) - { - dCols++; - } - } - - ScrollRight(dCols); - se.NewValue = HorizontalOffset; - } - else if (se.Type != ScrollEventType.EndScroll) - { - HorizontalOffset = se.NewValue; - } - - gridState[GRIDSTATE_isScrolling] = false; - } - - /// - /// Listens - /// for the vertical scrollbar's scroll event. - /// - protected virtual void GridVScrolled(object sender, ScrollEventArgs se) - { - if (!Enabled) - { - return; - } - - if (DataSource == null) - { - Debug.Fail("Vertical Scrollbar should be disabled without a DataSource."); - return; - } - - gridState[GRIDSTATE_isScrolling] = true; - - try - { - se.NewValue = Math.Min(se.NewValue, DataGridRowsLength - numTotallyVisibleRows); - int dRows = se.NewValue - firstVisibleRow; - ScrollDown(dRows); - } - finally - { - gridState[GRIDSTATE_isScrolling] = false; - } - } - - private void HandleEndCurrentEdit() - { - int currentRowSaved = currentRow; - int currentColSaved = currentCol; - - string errorMessage = null; - - try - { - listManager.EndCurrentEdit(); - } - catch (Exception e) - { - errorMessage = e.Message; - } - - if (errorMessage != null) - { - DialogResult result = RTLAwareMessageBox.Show(null, string.Format(SR.DataGridPushedIncorrectValueIntoColumn, - errorMessage), SR.DataGridErrorMessageBoxCaption, MessageBoxButtons.YesNo, - MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, 0); - - if (result == DialogResult.Yes) - { - currentRow = currentRowSaved; - currentCol = currentColSaved; - Debug.Assert(currentRow == ListManager.Position || listManager.Position == -1, "the position in the list manager (" + ListManager.Position + ") is out of sync with the currentRow (" + currentRow + ")" + " and the exception is '" + errorMessage + "'"); - // also, make sure that we get the row selector on the currentrow, too - InvalidateRowHeader(currentRow); - Edit(); - } - else - { - // if the user committed a row that used to be addNewRow and the backEnd rejects it, - // and then it tries to navigate down then we should stay in the addNewRow - // in this particular scenario, CancelCurrentEdit will cause the last row to be deleted, - // and this will ultimately call InvalidateRow w/ a row number larger than the number of rows - // so set the currentRow here: - Debug.Assert(result == DialogResult.No, "we only put cancel and ok on the error message box"); - listManager.PositionChanged -= positionChangedHandler; - listManager.CancelCurrentEdit(); - listManager.Position = currentRow; - listManager.PositionChanged += positionChangedHandler; - } - } - } - - /// - /// Listens - /// for the caption's back button clicked event. - /// - protected void OnBackButtonClicked(object sender, EventArgs e) - { - NavigateBack(); - - ((EventHandler)Events[EVENT_BACKBUTTONCLICK])?.Invoke(this, e); - } - - protected override void OnBackColorChanged(EventArgs e) - { - backBrush = new SolidBrush(BackColor); - Invalidate(); - - base.OnBackColorChanged(e); - } - - protected override void OnBindingContextChanged(EventArgs e) - { - if (DataSource != null && !gridState[GRIDSTATE_inSetListManager]) - { - try - { - Set_ListManager(DataSource, DataMember, true, false); // we do not want to create columns - // if the columns are already created - // the grid should not rely on OnBindingContextChanged - // to create columns. - } - catch - { - // at runtime we will rethrow the exception - if (Site == null || !Site.DesignMode) - { - throw; - } - - RTLAwareMessageBox.Show(null, SR.DataGridExceptionInPaint, null, - MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, 0); - - if (Visible) - { - BeginUpdateInternal(); - } - - ResetParentRows(); - - Set_ListManager(null, string.Empty, true); - if (Visible) - { - EndUpdateInternal(); - } - } - } - - base.OnBindingContextChanged(e); - } - - protected virtual void OnDataSourceChanged(EventArgs e) - { - if (Events[EVENT_DATASOURCECHANGED] is EventHandler eh) - { - eh(this, e); - } - } - - /// - /// Listens for - /// the caption's down button clicked event. - /// - protected void OnShowParentDetailsButtonClicked(object sender, EventArgs e) - { - // we need to fire the ParentRowsVisibleChanged event - // and the ParentRowsVisible property just calls SetParentRowsVisibility and - // then fires the event. - ParentRowsVisible = !caption.ToggleDownButtonDirection(); - - ((EventHandler)Events[EVENT_DOWNBUTTONCLICK])?.Invoke(this, e); - } - - protected override void OnForeColorChanged(EventArgs e) - { - foreBrush = new SolidBrush(ForeColor); - Invalidate(); - - base.OnForeColorChanged(e); - } - - protected override void OnFontChanged(EventArgs e) - { - // let the caption know about the event changed - // - Caption.OnGridFontChanged(); - RecalculateFonts(); - RecreateDataGridRows(); - // get all the rows in the parentRows stack, and modify their height - if (originalState != null) - { - Debug.Assert(!parentRows.IsEmpty(), "if the originalState is not null, then parentRows contains at least one row"); - Stack parentStack = new Stack(); - // this is a huge performance hit: - // everytime we get/put something from/to - // the parentRows, the buttons in the dataGridCaption - // are invalidated - while (!parentRows.IsEmpty()) - { - DataGridState dgs = parentRows.PopTop(); - int rowCount = dgs.DataGridRowsLength; - - for (int i = 0; i < rowCount; i++) - { - // performance hit: this will cause to invalidate a bunch of - // stuff - - dgs.DataGridRows[i].Height = dgs.DataGridRows[i].MinimumRowHeight(dgs.GridColumnStyles); - } - parentStack.Push(dgs); - } - - while (parentStack.Count != 0) - { - parentRows.AddParent((DataGridState)parentStack.Pop()); - } - } - - base.OnFontChanged(e); - } - - /// - /// Raises the - /// event. - /// - protected override void OnPaintBackground(PaintEventArgs ebe) - { - // null body - } - - /// - /// Raises the event which - /// repositions controls - /// and updates scroll bars. - /// - protected override void OnLayout(LayoutEventArgs levent) - { - // if we get a OnLayout event while the editControl changes, then just - // ignore it - // - if (gridState[GRIDSTATE_editControlChanging]) - { - return; - } - - Debug.WriteLineIf(CompModSwitches.DataGridLayout.TraceVerbose, "DataGridLayout: OnLayout"); - base.OnLayout(levent); - - if (gridState[GRIDSTATE_layoutSuspended]) - { - return; - } - - gridState[GRIDSTATE_canFocus] = false; - try - { - if (IsHandleCreated) - { - if (layout.ParentRowsVisible) - { - parentRows.OnLayout(); - } - - // reset the toolTip information - if (ToolTipProvider != null) - { - ResetToolTip(); - } - - ComputeLayout(); - } - } - finally - { - gridState[GRIDSTATE_canFocus] = true; - } - - } - - /// - /// Raises the - /// event. - /// - protected override void OnHandleCreated(EventArgs e) - { - base.OnHandleCreated(e); - - // toolTipping - toolTipProvider = new DataGridToolTip(this); - toolTipProvider.CreateToolTipHandle(); - toolTipId = 0; - - PerformLayout(); - } - - /// - /// Raises the - /// event. - /// - protected override void OnHandleDestroyed(EventArgs e) - { - base.OnHandleDestroyed(e); - - // toolTipping - if (toolTipProvider != null) - { - toolTipProvider.Destroy(); - toolTipProvider = null; - } - toolTipId = 0; - } - - /// - /// Raises the - /// event. - /// - protected override void OnEnter(EventArgs e) - { - if (gridState[GRIDSTATE_canFocus] && !gridState[GRIDSTATE_editControlChanging]) - { - if (Bound) - { - Edit(); - } - base.OnEnter(e); - } - } - - /// - /// Raises the - /// event. - /// - protected override void OnLeave(EventArgs e) - { - OnLeave_Grid(); - base.OnLeave(e); - } - - private void OnLeave_Grid() - { - gridState[GRIDSTATE_canFocus] = false; - try - { - EndEdit(); - if (listManager != null && !gridState[GRIDSTATE_editControlChanging]) - { - if (gridState[GRIDSTATE_inAddNewRow]) - { - // if the user did not type anything - // in the addNewRow, then cancel the currentedit - listManager.CancelCurrentEdit(); - // set the addNewRow back - DataGridRow[] localGridRows = DataGridRows; - localGridRows[DataGridRowsLength - 1] = new DataGridAddNewRow(this, myGridTable, DataGridRowsLength - 1); - SetDataGridRows(localGridRows, DataGridRowsLength); - } - else - { - // this.listManager.EndCurrentEdit(); - HandleEndCurrentEdit(); - } - } - } - finally - { - gridState[GRIDSTATE_canFocus] = true; - // inAddNewRow should be set to false if the control was - // not changing - if (!gridState[GRIDSTATE_editControlChanging]) - { - gridState[GRIDSTATE_inAddNewRow] = false; - } - } - } - - /// - /// Raises the - /// event. - /// - protected override void OnKeyDown(KeyEventArgs ke) - { - Debug.WriteLineIf(CompModSwitches.DataGridKeys.TraceVerbose, "DataGridKeys: OnKeyDown "); - base.OnKeyDown(ke); - ProcessGridKey(ke); - } - - /// - /// Raises the event. - /// - protected override void OnKeyPress(KeyPressEventArgs kpe) - { - Debug.WriteLineIf(CompModSwitches.DataGridKeys.TraceVerbose, "DataGridKeys: OnKeyPress " + TypeDescriptor.GetConverter(typeof(Keys)).ConvertToString(kpe.KeyChar)); - - base.OnKeyPress(kpe); - GridColumnStylesCollection coll = myGridTable.GridColumnStyles; - if (coll != null && currentCol > 0 && currentCol < coll.Count) - { - if (!coll[currentCol].ReadOnly) - { - if (kpe.KeyChar > 32) - { - Edit(new string(new char[] { (char)kpe.KeyChar })); - } - } - } - } - - /// - /// Raises the event. - /// - protected override void OnMouseDown(MouseEventArgs e) - { - base.OnMouseDown(e); - - gridState[GRIDSTATE_childLinkFocused] = false; - gridState[GRIDSTATE_dragging] = false; - if (listManager == null) - { - return; - } - - HitTestInfo location = HitTest(e.X, e.Y); - Keys nModifier = ModifierKeys; - bool isControlDown = (nModifier & Keys.Control) == Keys.Control && (nModifier & Keys.Alt) == 0; - bool isShiftDown = (nModifier & Keys.Shift) == Keys.Shift; - - // Only left clicks for now - if (e.Button != MouseButtons.Left) - { - return; - } - - // Check column resize - if (location.type == HitTestType.ColumnResize) - { - if (e.Clicks > 1) - { - ColAutoResize(location.col); - } - else - { - ColResizeBegin(e, location.col); - } - - return; - } - - // Check row resize - if (location.type == HitTestType.RowResize) - { - if (e.Clicks > 1) - { - RowAutoResize(location.row); - } - else - { - RowResizeBegin(e, location.row); - } - return; - } - - // Check column headers - if (location.type == HitTestType.ColumnHeader) - { - trackColumnHeader = myGridTable.GridColumnStyles[location.col].PropertyDescriptor; - return; - } - - if (location.type == HitTestType.Caption) - { - Rectangle captionRect = layout.Caption; - caption.MouseDown(e.X - captionRect.X, e.Y - captionRect.Y); - return; - } - - if (layout.Data.Contains(e.X, e.Y) || layout.RowHeaders.Contains(e.X, e.Y)) - { - // Check with the row underneath the mouse - int row = GetRowFromY(e.Y); - if (row > -1) - { - Point p = NormalizeToRow(e.X, e.Y, row); - DataGridRow[] localGridRows = DataGridRows; - if (localGridRows[row].OnMouseDown(p.X, p.Y, - layout.RowHeaders, - isRightToLeft())) - { - CommitEdit(); - - // possibly this was the last row, so then the link may not - // be visible. make it visible, by making the row visible. - // how can we be sure that the user did not click - // on a relationship and navigated to the child rows? - // check if the row is expanded: if the row is expanded, then the user clicked - // on the node. when we navigate to child rows the rows are recreated - // and are initially collapsed - localGridRows = DataGridRows; - if (row < DataGridRowsLength && (localGridRows[row] is DataGridRelationshipRow) && ((DataGridRelationshipRow)localGridRows[row]).Expanded) - { - EnsureVisible(row, 0); - } - - // show the edit box - // - Edit(); - return; - } - } - } - - // Check row headers - // - if (location.type == HitTestType.RowHeader) - { - EndEdit(); - if (!(DataGridRows[location.row] is DataGridAddNewRow)) - { - int savedCurrentRow = currentRow; - CurrentCell = new DataGridCell(location.row, currentCol); - if (location.row != savedCurrentRow && - currentRow != location.row && - currentRow == savedCurrentRow) - { - // The data grid was not able to move away from its previous current row. - // Be defensive and don't select the row. - return; - } - } - - if (isControlDown) - { - if (IsSelected(location.row)) - { - UnSelect(location.row); - } - else - { - Select(location.row); - } - } - else - { - if (lastRowSelected == -1 || !isShiftDown) - { - ResetSelection(); - Select(location.row); - } - else - { - int lowerRow = Math.Min(lastRowSelected, location.row); - int upperRow = Math.Max(lastRowSelected, location.row); - - // we need to reset the old SelectedRows. - // ResetSelection() will also reset lastRowSelected, so we - // need to save it - int saveLastRowSelected = lastRowSelected; - ResetSelection(); - lastRowSelected = saveLastRowSelected; - - DataGridRow[] rows = DataGridRows; - for (int i = lowerRow; i <= upperRow; i++) - { - rows[i].Selected = true; - numSelectedRows++; - } - - // hide the edit box: - // - EndEdit(); - return; - } - } - - lastRowSelected = location.row; - // OnRowHeaderClick(EventArgs.Empty); - return; - } - - // Check parentRows - // - if (location.type == HitTestType.ParentRows) - { - EndEdit(); - parentRows.OnMouseDown(e.X, e.Y, isRightToLeft()); - } - - // Check cell clicks - // - if (location.type == HitTestType.Cell) - { - if (myGridTable.GridColumnStyles[location.col].MouseDown(location.row, e.X, e.Y)) - { - return; - } - - DataGridCell target = new DataGridCell(location.row, location.col); - if (policy.AllowEdit && CurrentCell.Equals(target)) - { - ResetSelection(); - // - // what if only a part of the current cell is visible? - // - EnsureVisible(currentRow, currentCol); - Edit(); - } - else - { - ResetSelection(); - CurrentCell = target; - } - } - } - - /// - /// Creates the - /// event. - /// - protected override void OnMouseLeave(EventArgs e) - { - base.OnMouseLeave(e); - if (oldRow != -1) - { - DataGridRow[] localGridRows = DataGridRows; - localGridRows[oldRow].OnMouseLeft(layout.RowHeaders, isRightToLeft()); - } - if (gridState[GRIDSTATE_overCaption]) - { - caption.MouseLeft(); - } - // when the mouse leaves the grid control, reset the cursor to arrow - Cursor = null; - } - - internal void TextBoxOnMouseWheel(MouseEventArgs e) - { - OnMouseWheel(e); - } - - /// - /// Raises the - /// event. - /// - protected override void OnMouseMove(MouseEventArgs e) - { - base.OnMouseMove(e); - if (listManager == null) - { - return; - } - - HitTestInfo location = HitTest(e.X, e.Y); - - bool alignToRight = isRightToLeft(); - - // We need to give UI feedback when the user is resizing a column - if (gridState[GRIDSTATE_trackColResize]) - { - ColResizeMove(e); - } - - if (gridState[GRIDSTATE_trackRowResize]) - { - RowResizeMove(e); - } - - if (gridState[GRIDSTATE_trackColResize] || location.type == HitTestType.ColumnResize) - { - Cursor = Cursors.SizeWE; - return; - } - else if (gridState[GRIDSTATE_trackRowResize] || location.type == HitTestType.RowResize) - { - Cursor = Cursors.SizeNS; - return; - } - else - { - Cursor = null; - } - - if ((layout.Data.Contains(e.X, e.Y) - || (layout.RowHeadersVisible && layout.RowHeaders.Contains(e.X, e.Y)))) - { - // && (isNavigating || isEditing)) { - DataGridRow[] localGridRows = DataGridRows; - // If we are over a row, let it know about the mouse move. - int rowOver = GetRowFromY(e.Y); - // set the dragging bit: - if (lastRowSelected != -1 && !gridState[GRIDSTATE_dragging]) - { - int topRow = GetRowTop(lastRowSelected); - int bottomRow = topRow + localGridRows[lastRowSelected].Height; - int dragHeight = SystemInformation.DragSize.Height; - gridState[GRIDSTATE_dragging] = ((e.Y - topRow < dragHeight && topRow - e.Y < dragHeight) || (e.Y - bottomRow < dragHeight && bottomRow - e.Y < dragHeight)); - } - if (rowOver > -1) - { - Point p = NormalizeToRow(e.X, e.Y, rowOver); - if (!localGridRows[rowOver].OnMouseMove(p.X, p.Y, layout.RowHeaders, alignToRight) && gridState[GRIDSTATE_dragging]) - { - // if the row did not use this, see if selection can use it - MouseButtons mouse = MouseButtons; - if (lastRowSelected != -1 && (mouse & MouseButtons.Left) == MouseButtons.Left - && !(((Control.ModifierKeys & Keys.Control) == Keys.Control) && (Control.ModifierKeys & Keys.Alt) == 0)) - { - // ResetSelection() will reset the lastRowSelected too - // - int saveLastRowSelected = lastRowSelected; - ResetSelection(); - lastRowSelected = saveLastRowSelected; - - int lowerRow = Math.Min(lastRowSelected, rowOver); - int upperRow = Math.Max(lastRowSelected, rowOver); - - DataGridRow[] rows = DataGridRows; - for (int i = lowerRow; i <= upperRow; i++) - { - rows[i].Selected = true; - numSelectedRows++; - } - } - } - } - - if (oldRow != rowOver && oldRow != -1) - { - localGridRows[oldRow].OnMouseLeft(layout.RowHeaders, alignToRight); - } - oldRow = rowOver; - } - - // check parentRows - // - if (location.type == HitTestType.ParentRows) - { - if (parentRows != null) - { - parentRows.OnMouseMove(e.X, e.Y); - } - } - - if (location.type == HitTestType.Caption) - { - gridState[GRIDSTATE_overCaption] = true; - Rectangle captionRect = layout.Caption; - caption.MouseOver(e.X - captionRect.X, e.Y - captionRect.Y); - return; - } - else - { - if (gridState[GRIDSTATE_overCaption]) - { - gridState[GRIDSTATE_overCaption] = false; - caption.MouseLeft(); - } - } - } - - /// - /// Raises the event. - /// - protected override void OnMouseUp(MouseEventArgs e) - { - base.OnMouseUp(e); - gridState[GRIDSTATE_dragging] = false; - if (listManager == null || myGridTable == null) - { - return; - } - - if (gridState[GRIDSTATE_trackColResize]) - { - ColResizeEnd(e); - } - - if (gridState[GRIDSTATE_trackRowResize]) - { - RowResizeEnd(e); - } - - gridState[GRIDSTATE_trackColResize] = false; - gridState[GRIDSTATE_trackRowResize] = false; - - HitTestInfo ci = HitTest(e.X, e.Y); - if ((ci.type & HitTestType.Caption) == HitTestType.Caption) - { - caption.MouseUp(e.X, e.Y); - } - - // Check column headers - if (ci.type == HitTestType.ColumnHeader) - { - PropertyDescriptor prop = myGridTable.GridColumnStyles[ci.col].PropertyDescriptor; - if (prop == trackColumnHeader) - { - ColumnHeaderClicked(trackColumnHeader); - } - } - - trackColumnHeader = null; - } - - /// - /// Raises the event. - /// - protected override void OnMouseWheel(MouseEventArgs e) - { - base.OnMouseWheel(e); - - if (e is HandledMouseEventArgs) - { - if (((HandledMouseEventArgs)e).Handled) - { - // The application event handler handled the scrolling - don't do anything more. - return; - } - ((HandledMouseEventArgs)e).Handled = true; - } - - bool wheelingDown = true; - if ((ModifierKeys & Keys.Control) != 0) - { - wheelingDown = false; - } - - if (listManager == null || myGridTable == null) - { - return; - } - - ScrollBar sb = wheelingDown ? vertScrollBar : horizScrollBar; - if (!sb.Visible) - { - return; - } - - // so we scroll. we have to know this, cause otherwise we will call EndEdit - // and that would be wrong. - gridState[GRIDSTATE_isScrolling] = true; - wheelDelta += e.Delta; - float movePerc = (float)wheelDelta / (float)NativeMethods.WHEEL_DELTA; - int move = (int)((float)SystemInformation.MouseWheelScrollLines * movePerc); - if (move != 0) - { - wheelDelta = 0; - Debug.WriteLineIf(CompModSwitches.DataGridLayout.TraceVerbose, "DataGridLayout: OnMouseWheel move=" + move.ToString(CultureInfo.InvariantCulture)); - if (wheelingDown) - { - int newRow = firstVisibleRow - move; - newRow = Math.Max(0, Math.Min(newRow, DataGridRowsLength - numTotallyVisibleRows)); - ScrollDown(newRow - firstVisibleRow); - } - else - { - int newValue = horizScrollBar.Value + (move < 0 ? 1 : -1) * horizScrollBar.LargeChange; - HorizontalOffset = newValue; - } - } - - gridState[GRIDSTATE_isScrolling] = false; - } - - /// - /// Raises the - /// event. - /// - protected override void OnPaint(PaintEventArgs pe) - { - try - { - CheckHierarchyState(); - - if (layout.dirty) - { - ComputeLayout(); - } - - Graphics g = pe.Graphics; - - Region clipRegion = g.Clip; - if (layout.CaptionVisible) - { - caption.Paint(g, layout.Caption, isRightToLeft()); - } - - if (layout.ParentRowsVisible) - { - Debug.WriteLineIf(CompModSwitches.DataGridParents.TraceVerbose, "DataGridParents: Painting ParentRows " + layout.ParentRows.ToString()); - g.FillRectangle(SystemBrushes.AppWorkspace, layout.ParentRows); - parentRows.Paint(g, layout.ParentRows, isRightToLeft()); - } - - Rectangle gridRect = layout.Data; - if (layout.RowHeadersVisible) - { - gridRect = Rectangle.Union(gridRect, layout.RowHeaders); - } - - if (layout.ColumnHeadersVisible) - { - gridRect = Rectangle.Union(gridRect, layout.ColumnHeaders); - } - - g.SetClip(gridRect); - PaintGrid(g, gridRect); - g.Clip = clipRegion; - clipRegion.Dispose(); - PaintBorder(g, layout.ClientRectangle); - - g.FillRectangle(DefaultHeaderBackBrush, layout.ResizeBoxRect); - - base.OnPaint(pe); // raise paint event - } - catch - { - // at runtime we will rethrow the exception - if (Site == null || !Site.DesignMode) - { - throw; - } - - gridState[GRIDSTATE_exceptionInPaint] = true; - try - { - RTLAwareMessageBox.Show(null, SR.DataGridExceptionInPaint, null, MessageBoxButtons.OK, - MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, 0); - - if (Visible) - { - BeginUpdateInternal(); - } - - ResetParentRows(); - - Set_ListManager(null, string.Empty, true); - } - finally - { - gridState[GRIDSTATE_exceptionInPaint] = false; - if (Visible) - { - EndUpdateInternal(); - } - } - } - } - - // Since Win32 only invalidates the area that gets uncovered, - // we have to manually invalidate the old border area - /// - /// Raises the event. - /// - protected override void OnResize(EventArgs e) - { - Debug.WriteLineIf(CompModSwitches.DataGridLayout.TraceVerbose, "DataGridLayout: OnResize"); - - if (layout.CaptionVisible) - { - Invalidate(layout.Caption); - } - - if (layout.ParentRowsVisible) - { - parentRows.OnResize(layout.ParentRows); - } - - int borderWidth = BorderWidth; - Rectangle right; - Rectangle bottom; - Rectangle oldClientRectangle = layout.ClientRectangle; - - right = new Rectangle(oldClientRectangle.X + oldClientRectangle.Width - borderWidth, - oldClientRectangle.Y, - borderWidth, - oldClientRectangle.Height); - bottom = new Rectangle(oldClientRectangle.X, - oldClientRectangle.Y + oldClientRectangle.Height - borderWidth, - oldClientRectangle.Width, - borderWidth); - - Rectangle newClientRectangle = ClientRectangle; - if (newClientRectangle.Width != oldClientRectangle.Width) - { - Invalidate(right); - right = new Rectangle(newClientRectangle.X + newClientRectangle.Width - borderWidth, - newClientRectangle.Y, - borderWidth, - newClientRectangle.Height); - Invalidate(right); - } - if (newClientRectangle.Height != oldClientRectangle.Height) - { - Invalidate(bottom); - bottom = new Rectangle(newClientRectangle.X, - newClientRectangle.Y + newClientRectangle.Height - borderWidth, - newClientRectangle.Width, - borderWidth); - Invalidate(bottom); - } - - //also, invalidate the ResizeBoxRect - if (!layout.ResizeBoxRect.IsEmpty) - { - Invalidate(layout.ResizeBoxRect); - } - - layout.ClientRectangle = newClientRectangle; - - int oldFirstVisibleRow = firstVisibleRow; - base.OnResize(e); - if (isRightToLeft() || oldFirstVisibleRow != firstVisibleRow) - { - Invalidate(); - } - } - - internal void OnRowHeightChanged(DataGridRow row) - { - ClearRegionCache(); - int cy = GetRowTop(row.RowNumber); - if (cy > 0) - { - Rectangle refresh = new Rectangle - { - Y = cy, - X = layout.Inside.X, - Width = layout.Inside.Width, - Height = layout.Inside.Bottom - cy - }; - Invalidate(refresh); - } - } - - internal void ParentRowsDataChanged() - { - Debug.Assert(originalState != null, "how can we get a list changed event from another listmanager/list while not navigating"); - - // do the reset work that is done in SetDataBindings, set_DataSource, set_DataMember; - parentRows.Clear(); - caption.BackButtonActive = caption.DownButtonActive = caption.BackButtonVisible = false; - caption.SetDownButtonDirection(!layout.ParentRowsVisible); - object dSource = originalState.DataSource; - string dMember = originalState.DataMember; - // we don't need to set the GRIDSTATE_metaDataChanged bit, cause - // the listManager from the originalState should be different from the current listManager - // - // set the originalState to null so that Set_ListManager knows that - // it has to unhook the MetaDataChanged events - originalState = null; - Set_ListManager(dSource, dMember, true); - } - - // =------------------------------------------------------------------ - // = Methods - // =------------------------------------------------------------------ - - private void AbortEdit() - { - Debug.WriteLineIf(CompModSwitches.DataGridEditing.TraceVerbose, "DataGridEditing: \t! AbortEdit"); - - // the same rules from editColumn.OnEdit - // while changing the editControl's visibility, do not - // PerformLayout on the entire DataGrid - gridState[GRIDSTATE_editControlChanging] = true; - - editColumn.Abort(editRow.RowNumber); - - // reset the editControl flag: - gridState[GRIDSTATE_editControlChanging] = false; - - gridState[GRIDSTATE_isEditing] = false; - editRow = null; - editColumn = null; - } - - /// - /// Occurs when the user navigates to a new table. - /// - [SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.DataGridNavigateEventDescr))] - public event NavigateEventHandler Navigate - { - add => onNavigate += value; - remove => onNavigate -= value; - } - - /// - /// Occurs when a row header is clicked. - /// - protected event EventHandler RowHeaderClick - { - add => onRowHeaderClick += value; - remove => onRowHeaderClick -= value; - } - - /// - /// Adds an event handler for the 'System.Windows.Forms.DataGrid.OnNodeClick' - /// event. - /// - [SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.DataGridNodeClickEventDescr))] - internal event EventHandler NodeClick - { - add => Events.AddHandler(EVENT_NODECLICKED, value); - remove => Events.RemoveHandler(EVENT_NODECLICKED, value); - } - - /// - /// Occurs when the user scrolls the control. - /// - [SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.DataGridScrollEventDescr))] - public event EventHandler Scroll - { - add => Events.AddHandler(EVENT_SCROLL, value); - remove => Events.RemoveHandler(EVENT_SCROLL, value); - } - - public override ISite Site - { - get - { - return base.Site; - } - set - { - ISite temp = Site; - base.Site = value; - if (value != temp && !Disposing) - { - // we should site the tables and the columns - // only when our site changes - SubObjectsSiteChange(false); - SubObjectsSiteChange(true); - } - } - } - - internal void AddNewRow() - { - EnsureBound(); - ResetSelection(); - // EndEdit(); - UpdateListManager(); - gridState[GRIDSTATE_inListAddNew] = true; - gridState[GRIDSTATE_inAddNewRow] = true; - try - { - ListManager.AddNew(); - } - catch - { - gridState[GRIDSTATE_inListAddNew] = false; - gridState[GRIDSTATE_inAddNewRow] = false; - PerformLayout(); - InvalidateInside(); - throw; - } - gridState[GRIDSTATE_inListAddNew] = false; - } - - /// - /// Attempts to - /// put the grid into a state where editing is - /// allowed. - /// - public bool BeginEdit(DataGridColumnStyle gridColumn, int rowNumber) - { - if (DataSource == null || myGridTable == null) - { - return false; - } - - // We deny edit requests if we are already editing a cell. - if (gridState[GRIDSTATE_isEditing]) - { - return false; - } - else - { - int col = -1; - if ((col = myGridTable.GridColumnStyles.IndexOf(gridColumn)) < 0) - { - return false; - } - - CurrentCell = new DataGridCell(rowNumber, col); - ResetSelection(); - Edit(); - return true; - } - } - - /// - /// Specifies the beginning of the initialization code. - /// - public void BeginInit() - { - if (inInit) - { - throw new InvalidOperationException(SR.DataGridBeginInit); - } - - inInit = true; - } - - private Rectangle CalcRowResizeFeedbackRect(MouseEventArgs e) - { - Rectangle inside = layout.Data; - Rectangle r = new Rectangle(inside.X, e.Y, inside.Width, 3); - r.Y = Math.Min(inside.Bottom - 3, r.Y); - r.Y = Math.Max(r.Y, 0); - return r; - } - - private Rectangle CalcColResizeFeedbackRect(MouseEventArgs e) - { - Rectangle inside = layout.Data; - Rectangle r = new Rectangle(e.X, inside.Y, 3, inside.Height); - r.X = Math.Min(inside.Right - 3, r.X); - r.X = Math.Max(r.X, 0); - return r; - } - - private void CancelCursorUpdate() - { - Debug.WriteLineIf(CompModSwitches.DataGridCursor.TraceVerbose, "DataGridCursor: Requesting CancelEdit()"); - if (listManager != null) - { - EndEdit(); - listManager.CancelCurrentEdit(); - } - } - - private void CheckHierarchyState() - { - if (checkHierarchy && listManager != null && myGridTable != null) - { - if (myGridTable == null) - { - // there was nothing to check - return; - } - - for (int j = 0; j < myGridTable.GridColumnStyles.Count; j++) - { - DataGridColumnStyle gridColumn = myGridTable.GridColumnStyles[j]; - } - - checkHierarchy = false; - } - } - - /// - /// The DataGrid caches an array of rectangular areas - /// which represent the area which scrolls left to right. - /// This method is invoked whenever the DataGrid's - /// scrollable regions change in such a way as to require - /// a re-recalculation. - /// - private void ClearRegionCache() - { - cachedScrollableRegion = null; - } - - /// - /// Determines the best fit size for the given column. - /// - private void ColAutoResize(int col) - { - Debug.WriteLineIf(CompModSwitches.DataGridLayout.TraceVerbose, "DataGridLayout: ColAutoResize"); - EndEdit(); - CurrencyManager listManager = this.listManager; - if (listManager == null) - { - return; - } - - int size; - Graphics g = CreateGraphicsInternal(); - try - { - DataGridColumnStyle column = myGridTable.GridColumnStyles[col]; - string columnName = column.HeaderText; - - Font headerFont; - if (myGridTable.IsDefault) - { - headerFont = HeaderFont; - } - else - { - headerFont = myGridTable.HeaderFont; - } - - size = (int)g.MeasureString(columnName, headerFont).Width + layout.ColumnHeaders.Height + 1; // The sort triangle's width is equal to it's height - int rowCount = listManager.Count; - for (int row = 0; row < rowCount; ++row) - { - object value = column.GetColumnValueAtRow(listManager, row); - int width = column.GetPreferredSize(g, value).Width; - if (width > size) - { - size = width; - } - } - - if (column.Width != size) - { - column._width = size; - - ComputeVisibleColumns(); - - bool lastColumnIsLastTotallyVisibleCol = true; - if (lastTotallyVisibleCol != -1) - { - for (int i = lastTotallyVisibleCol + 1; i < myGridTable.GridColumnStyles.Count; i++) - { - if (myGridTable.GridColumnStyles[i].PropertyDescriptor != null) - { - lastColumnIsLastTotallyVisibleCol = false; - break; - } - } - } - else - { - lastColumnIsLastTotallyVisibleCol = false; - } - - // if the column shrank and the last totally visible column was the last column - // then we need to recompute the horizontalOffset, firstVisibleCol, negOffset. - // lastTotallyVisibleCol remains the last column - if (lastColumnIsLastTotallyVisibleCol && - (negOffset != 0 || horizontalOffset != 0)) - { - - // update the column width - column._width = size; - - int cx = 0; - int colCount = myGridTable.GridColumnStyles.Count; - int visibleWidth = layout.Data.Width; - GridColumnStylesCollection cols = myGridTable.GridColumnStyles; - - // assume everything fits - negOffset = 0; - horizontalOffset = 0; - firstVisibleCol = 0; - - for (int i = colCount - 1; i >= 0; i--) - { - if (cols[i].PropertyDescriptor == null) - { - continue; - } - - cx += cols[i].Width; - if (cx > visibleWidth) - { - if (negOffset == 0) - { - firstVisibleCol = i; - negOffset = cx - visibleWidth; - horizontalOffset = negOffset; - numVisibleCols++; - } - else - { - horizontalOffset += cols[i].Width; - } - } - else - { - numVisibleCols++; - } - } - - // refresh the horizontal scrollbar - PerformLayout(); - - // we need to invalidate the layout.Data and layout.ColumnHeaders - Invalidate(Rectangle.Union(layout.Data, layout.ColumnHeaders)); - } - else - { - // need to refresh the scroll bar - PerformLayout(); - - Rectangle rightArea = layout.Data; - if (layout.ColumnHeadersVisible) - { - rightArea = Rectangle.Union(rightArea, layout.ColumnHeaders); - } - - int left = GetColBeg(col); - - if (!isRightToLeft()) - { - rightArea.Width -= left - rightArea.X; - rightArea.X = left; - } - else - { - rightArea.Width -= left; - } - - Invalidate(rightArea); - } - } - } - finally - { - g.Dispose(); - } - - if (horizScrollBar.Visible) - { - horizScrollBar.Value = HorizontalOffset; - } - // OnColumnResize(EventArgs.Empty); - } - - /// - /// Collapses child relations, if any exist for all rows, or for a - /// specified row. - /// - public void Collapse(int row) - { - SetRowExpansionState(row, false); - } - - private void ColResizeBegin(MouseEventArgs e, int col) - { - Debug.WriteLineIf(CompModSwitches.DataGridLayout.TraceVerbose, "DataGridLayout: ColResizeBegin"); - Debug.Assert(myGridTable != null, "Column resizing operations can't be called when myGridTable == null."); - - int x = e.X; - EndEdit(); - Rectangle clip = Rectangle.Union(layout.ColumnHeaders, layout.Data); - if (isRightToLeft()) - { - clip.Width = GetColBeg(col) - layout.Data.X - 2; - } - else - { - int leftEdge = GetColBeg(col); - clip.X = leftEdge + 3; - clip.Width = layout.Data.X + layout.Data.Width - leftEdge - 2; - } - - CaptureInternal = true; - Cursor.ClipInternal = RectangleToScreen(clip); - gridState[GRIDSTATE_trackColResize] = true; - trackColAnchor = x; - trackColumn = col; - - DrawColSplitBar(e); - lastSplitBar = e; - } - - private void ColResizeMove(MouseEventArgs e) - { - if (lastSplitBar != null) - { - DrawColSplitBar(lastSplitBar); - lastSplitBar = e; - } - DrawColSplitBar(e); - } - - private void ColResizeEnd(MouseEventArgs e) - { - Debug.WriteLineIf(CompModSwitches.DataGridLayout.TraceVerbose, "DataGridLayout: ColResizeEnd"); - Debug.Assert(myGridTable != null, "Column resizing operations can't be called when myGridTable == null."); - - gridState[GRIDSTATE_layoutSuspended] = true; - try - { - if (lastSplitBar != null) - { - DrawColSplitBar(lastSplitBar); - lastSplitBar = null; - } - - bool rightToLeft = isRightToLeft(); - - int x = rightToLeft ? Math.Max(e.X, layout.Data.X) : Math.Min(e.X, layout.Data.Right + 1); - int delta = x - GetColEnd(trackColumn); - if (rightToLeft) - { - delta = -delta; - } - - if (trackColAnchor != x && delta != 0) - { - DataGridColumnStyle column = myGridTable.GridColumnStyles[trackColumn]; - int proposed = column.Width + delta; - proposed = Math.Max(proposed, 3); - column.Width = proposed; - - // refresh scrolling data: horizontalOffset, negOffset, firstVisibleCol, numVisibleCols, lastTotallyVisibleCol - ComputeVisibleColumns(); - - bool lastColumnIsLastTotallyVisibleCol = true; - for (int i = lastTotallyVisibleCol + 1; i < myGridTable.GridColumnStyles.Count; i++) - { - if (myGridTable.GridColumnStyles[i].PropertyDescriptor != null) - { - lastColumnIsLastTotallyVisibleCol = false; - break; - } - } - - if (lastColumnIsLastTotallyVisibleCol && - (negOffset != 0 || horizontalOffset != 0)) - { - - int cx = 0; - int colCount = myGridTable.GridColumnStyles.Count; - int visibleWidth = layout.Data.Width; - GridColumnStylesCollection cols = myGridTable.GridColumnStyles; - - // assume everything fits - negOffset = 0; - horizontalOffset = 0; - firstVisibleCol = 0; - - for (int i = colCount - 1; i > -1; i--) - { - if (cols[i].PropertyDescriptor == null) - { - continue; - } - - cx += cols[i].Width; - - if (cx > visibleWidth) - { - if (negOffset == 0) - { - negOffset = cx - visibleWidth; - firstVisibleCol = i; - horizontalOffset = negOffset; - numVisibleCols++; - } - else - { - horizontalOffset += cols[i].Width; - } - } - else - { - numVisibleCols++; - } - } - - // and invalidate pretty much everything - Invalidate(Rectangle.Union(layout.Data, layout.ColumnHeaders)); - } - else - { - - Rectangle rightArea = Rectangle.Union(layout.ColumnHeaders, layout.Data); - int left = GetColBeg(trackColumn); - rightArea.Width -= rightToLeft ? rightArea.Right - left : left - rightArea.X; - rightArea.X = rightToLeft ? layout.Data.X : left; - Invalidate(rightArea); - } - } - } - finally - { - Cursor.ClipInternal = Rectangle.Empty; - CaptureInternal = false; - gridState[GRIDSTATE_layoutSuspended] = false; - } - - PerformLayout(); - - if (horizScrollBar.Visible) - { - horizScrollBar.Value = HorizontalOffset; - } - // OnColumnResize(EventArgs.Empty); - } - - private void MetaDataChanged() - { - // when we reset the Binding in the grid, we need to clear the parent rows. - // the same goes for all the caption UI: reset it when the datasource changes. - // - parentRows.Clear(); - caption.BackButtonActive = caption.DownButtonActive = caption.BackButtonVisible = false; - caption.SetDownButtonDirection(!layout.ParentRowsVisible); - - gridState[GRIDSTATE_metaDataChanged] = true; - try - { - if (originalState != null) - { - // set the originalState to null so that Set_ListManager knows that - // it has to unhook the MetaDataChanged events - Set_ListManager(originalState.DataSource, originalState.DataMember, true); - originalState = null; - } - else - { - Set_ListManager(DataSource, DataMember, true); - } - } - finally - { - gridState[GRIDSTATE_metaDataChanged] = false; - } - } - - // =------------------------------------------------------------------ - // = Functions to resize rows - // =------------------------------------------------------------------ - - // will autoResize "row" - private void RowAutoResize(int row) - { - Debug.WriteLineIf(CompModSwitches.DataGridLayout.TraceVerbose, "DataGridLayout: RowAutoResize"); - - EndEdit(); - CurrencyManager listManager = ListManager; - if (listManager == null) - { - return; - } - - Graphics g = CreateGraphicsInternal(); - try - { - GridColumnStylesCollection columns = myGridTable.GridColumnStyles; - DataGridRow resizeRow = DataGridRows[row]; - int rowCount = listManager.Count; - int resizeHeight = 0; - - // compute the height that we should resize to: - int columnsCount = columns.Count; - for (int col = 0; col < columnsCount; col++) - { - object value = columns[col].GetColumnValueAtRow(listManager, row); - resizeHeight = Math.Max(resizeHeight, columns[col].GetPreferredHeight(g, value)); - } - - if (resizeRow.Height != resizeHeight) - { - resizeRow.Height = resizeHeight; - - // needed to refresh scrollbar properties - PerformLayout(); - - Rectangle rightArea = layout.Data; - if (layout.RowHeadersVisible) - { - rightArea = Rectangle.Union(rightArea, layout.RowHeaders); - } - - int top = GetRowTop(row); - rightArea.Height -= rightArea.Y - top; - rightArea.Y = top; - Invalidate(rightArea); - } - } - finally - { - g.Dispose(); - } - - // OnRowResize(EventArgs.Empty); - return; - } - - private void RowResizeBegin(MouseEventArgs e, int row) - { - Debug.WriteLineIf(CompModSwitches.DataGridLayout.TraceVerbose, "DataGridLayout: RowResizeBegin"); - Debug.Assert(myGridTable != null, "Row resizing operations can't be called when myGridTable == null."); - - int y = e.Y; - EndEdit(); - Rectangle clip = Rectangle.Union(layout.RowHeaders, layout.Data); - int topEdge = GetRowTop(row); - clip.Y = topEdge + 3; - clip.Height = layout.Data.Y + layout.Data.Height - topEdge - 2; - - CaptureInternal = true; - Cursor.ClipInternal = RectangleToScreen(clip); - gridState[GRIDSTATE_trackRowResize] = true; - trackRowAnchor = y; - trackRow = row; - - DrawRowSplitBar(e); - lastSplitBar = e; - } - - private void RowResizeMove(MouseEventArgs e) - { - if (lastSplitBar != null) - { - DrawRowSplitBar(lastSplitBar); - lastSplitBar = e; - } - DrawRowSplitBar(e); - } - - private void RowResizeEnd(MouseEventArgs e) - { - Debug.WriteLineIf(CompModSwitches.DataGridLayout.TraceVerbose, "DataGridLayout: RowResizeEnd"); - Debug.Assert(myGridTable != null, "Row resizing operations can't be called when myGridTable == null."); - - try - { - if (lastSplitBar != null) - { - DrawRowSplitBar(lastSplitBar); - lastSplitBar = null; - } - - int y = Math.Min(e.Y, layout.Data.Y + layout.Data.Height + 1); - int delta = y - GetRowBottom(trackRow); - if (trackRowAnchor != y && delta != 0) - { - DataGridRow row = DataGridRows[trackRow]; - int proposed = row.Height + delta; - proposed = Math.Max(proposed, 3); - row.Height = proposed; - - // needed to refresh scrollbar properties - PerformLayout(); - - Rectangle rightArea = Rectangle.Union(layout.RowHeaders, layout.Data); - int top = GetRowTop(trackRow); - rightArea.Height -= rightArea.Y - top; - rightArea.Y = top; - Invalidate(rightArea); - } - } - finally - { - Cursor.ClipInternal = Rectangle.Empty; - CaptureInternal = false; - } - // OnRowResize(EventArgs.Empty); - } - - /// - /// Fires the ColumnHeaderClicked event and handles column - /// sorting. - /// - private void ColumnHeaderClicked(PropertyDescriptor prop) - { - if (!CommitEdit()) - { - return; - } - - // OnColumnHeaderClick(EventArgs.Empty); - bool allowSorting; - if (myGridTable.IsDefault) - { - allowSorting = AllowSorting; - } - else - { - allowSorting = myGridTable.AllowSorting; - } - - if (!allowSorting) - { - return; - } - - // if (CompModSwitches.DataGridCursor.OutputVerbose) Debug.WriteLine("DataGridCursor: We are about to sort column " + col.ToString()); - ListSortDirection direction = ListManager.GetSortDirection(); - PropertyDescriptor sortColumn = ListManager.GetSortProperty(); - if (sortColumn != null && sortColumn.Equals(prop)) - { - direction = (direction == ListSortDirection.Ascending) ? ListSortDirection.Descending : ListSortDirection.Ascending; - } - else - { - // defaultSortDirection : ascending - direction = ListSortDirection.Ascending; - } - - if (listManager.Count == 0) - { - return; - } - - ListManager.SetSort(prop, direction); - ResetSelection(); - - InvalidateInside(); - } - - /// - /// Attempts to commit editing if a cell is being edited. - /// Return true if successfully commited editing. - /// Return false if editing can not be completed and the gird must - /// remain in our current Edit state. - /// - private bool CommitEdit() - { - Debug.WriteLineIf(CompModSwitches.DataGridEditing.TraceVerbose, "DataGridEditing: \t CommitEdit " + (editRow == null ? "" : editRow.RowNumber.ToString(CultureInfo.InvariantCulture))); - - // we want to commit the editing if - // 1. the user was editing or navigating around the data grid and - // 2. this is not the result of moving focus inside the data grid and - // 3. if the user was scrolling - if (!gridState[GRIDSTATE_isEditing] && !gridState[GRIDSTATE_isNavigating] || (gridState[GRIDSTATE_editControlChanging] && !gridState[GRIDSTATE_isScrolling])) - { - return true; - } - - // the same rules from editColumn.OnEdit - // flag that we are editing the Edit control, so if we get a OnLayout on the - // datagrid side of things while the edit control changes its visibility and bounds - // the datagrid does not perform a layout - gridState[GRIDSTATE_editControlChanging] = true; - - if ((editColumn != null && editColumn.ReadOnly) || gridState[GRIDSTATE_inAddNewRow]) - { - bool focusTheGrid = false; - if (ContainsFocus) - { - focusTheGrid = true; - } - - if (focusTheGrid && gridState[GRIDSTATE_canFocus]) - { - Focus(); - } - - editColumn.ConcedeFocus(); - - // set the focus back to the grid - if (focusTheGrid && gridState[GRIDSTATE_canFocus] && CanFocus && !Focused) - { - Focus(); - } - - // reset the editControl flag - gridState[GRIDSTATE_editControlChanging] = false; - return true; - } - - bool retVal = editColumn?.Commit(ListManager, currentRow) ?? true; - - // reset the editControl flag - gridState[GRIDSTATE_editControlChanging] = false; - - if (retVal) - { - gridState[GRIDSTATE_isEditing] = false; - } - - return retVal; - } - - /// - /// Figure out how many rows we need to scroll down - /// to move targetRow into visibility. - /// - private int ComputeDeltaRows(int targetRow) - { - //Debug.WriteLineIf(CompModSwitches.DataGridScrolling.TraceVerbose, "DataGridScrolling: ComputeDeltaRows, firstVisibleRow = " - // + firstVisibleRow.ToString() + ", " - // + "targetRow = " + targetRow.ToString()); - - if (firstVisibleRow == targetRow) - { - return 0; - } - - int dRows = 0; - int firstVisibleRowLogicalTop = -1; - int targetRowLogicalTop = -1; - int nRows = DataGridRowsLength; - int cy = 0; - DataGridRow[] localGridRows = DataGridRows; - - for (int row = 0; row < nRows; ++row) - { - if (row == firstVisibleRow) - { - firstVisibleRowLogicalTop = cy; - } - - if (row == targetRow) - { - targetRowLogicalTop = cy; - } - - if (targetRowLogicalTop != -1 && firstVisibleRowLogicalTop != -1) - { - break; - } - - cy += localGridRows[row].Height; - } - - int targetRowLogicalBottom = targetRowLogicalTop + localGridRows[targetRow].Height; - int dataLogicalBottom = layout.Data.Height + firstVisibleRowLogicalTop; - if (targetRowLogicalBottom > dataLogicalBottom) - { - // we need to move down. - int downDelta = targetRowLogicalBottom - dataLogicalBottom; - firstVisibleRowLogicalTop += downDelta; - } - else if (firstVisibleRowLogicalTop < targetRowLogicalTop) - { - // we don't need to move - return 0; - } - else - { - // we need to move up. - int upDelta = firstVisibleRowLogicalTop - targetRowLogicalTop; - firstVisibleRowLogicalTop -= upDelta; - } - int newFirstRow = ComputeFirstVisibleRow(firstVisibleRowLogicalTop); - dRows = (newFirstRow - firstVisibleRow); - //Debug.WriteLineIf(CompModSwitches.DataGridScrolling.TraceVerbose, "DataGridScrolling: ComputeDeltaRows returning " + dRows.ToString()); - return dRows; - } - - /// - /// Given the a logical vertical offset, figure out - /// which row number should be the first fully visible - /// row on or after the offset. - /// - private int ComputeFirstVisibleRow(int firstVisibleRowLogicalTop) - { - int first; - int nRows = DataGridRowsLength; - int cy = 0; - DataGridRow[] localGridRows = DataGridRows; - for (first = 0; first < nRows; ++first) - { - if (cy >= firstVisibleRowLogicalTop) - { - break; - } - - cy += localGridRows[first].Height; - } - return first; - } - - /// - /// Constructs an updated Layout object. - /// - private void ComputeLayout() - { - Debug.WriteLineIf(CompModSwitches.DataGridLayout.TraceVerbose, "DataGridLayout: ComputeLayout"); - - bool alignLeft = !isRightToLeft(); - Rectangle oldResizeRect = layout.ResizeBoxRect; - - // hide the EditBox - EndEdit(); - - ClearRegionCache(); - - // NOTE : Since Rectangles are structs, then assignment is a - // : copy. Therefore, after saying "Rectangle inside = newLayout.Inside", - // : we must always assign back to newLayout.Inside. - // - - // Important since all of the visibility flags will move - // to the new layout here. - LayoutData newLayout = new LayoutData(layout) - { - - // Inside - Inside = ClientRectangle - }; - Rectangle inside = newLayout.Inside; - int borderWidth = BorderWidth; - inside.Inflate(-borderWidth, -borderWidth); - - Rectangle insideLeft = inside; - - // Caption - if (layout.CaptionVisible) - { - int captionHeight = captionFontHeight + 6; - Rectangle cap = newLayout.Caption; - cap = insideLeft; - cap.Height = captionHeight; - insideLeft.Y += captionHeight; - insideLeft.Height -= captionHeight; - - newLayout.Caption = cap; - } - else - { - newLayout.Caption = Rectangle.Empty; - } - - // Parent Rows - if (layout.ParentRowsVisible) - { - Rectangle parents = newLayout.ParentRows; - int parentHeight = parentRows.Height; - parents = insideLeft; - parents.Height = parentHeight; - insideLeft.Y += parentHeight; - insideLeft.Height -= parentHeight; - - newLayout.ParentRows = parents; - } - else - { - newLayout.ParentRows = Rectangle.Empty; - } - - // Headers - // - int columnHeaderHeight = headerFontHeight + 6; - if (layout.ColumnHeadersVisible) - { - Rectangle colHeaders = newLayout.ColumnHeaders; - colHeaders = insideLeft; - colHeaders.Height = columnHeaderHeight; - insideLeft.Y += columnHeaderHeight; - insideLeft.Height -= columnHeaderHeight; - - newLayout.ColumnHeaders = colHeaders; - } - else - { - newLayout.ColumnHeaders = Rectangle.Empty; - } - - bool newRowHeadersVisible = myGridTable.IsDefault ? RowHeadersVisible : myGridTable.RowHeadersVisible; - int newRowHeaderWidth = myGridTable.IsDefault ? RowHeaderWidth : myGridTable.RowHeaderWidth; - newLayout.RowHeadersVisible = newRowHeadersVisible; - if (myGridTable != null && newRowHeadersVisible) - { - Rectangle rowHeaders = newLayout.RowHeaders; - if (alignLeft) - { - rowHeaders = insideLeft; - rowHeaders.Width = newRowHeaderWidth; - insideLeft.X += newRowHeaderWidth; - insideLeft.Width -= newRowHeaderWidth; - } - else - { - rowHeaders = insideLeft; - rowHeaders.Width = newRowHeaderWidth; - rowHeaders.X = insideLeft.Right - newRowHeaderWidth; - insideLeft.Width -= newRowHeaderWidth; - } - newLayout.RowHeaders = rowHeaders; - - if (layout.ColumnHeadersVisible) - { - Rectangle topLeft = newLayout.TopLeftHeader; - Rectangle colHeaders = newLayout.ColumnHeaders; - if (alignLeft) - { - topLeft = colHeaders; - topLeft.Width = newRowHeaderWidth; - colHeaders.Width -= newRowHeaderWidth; - colHeaders.X += newRowHeaderWidth; - } - else - { - topLeft = colHeaders; - topLeft.Width = newRowHeaderWidth; - topLeft.X = colHeaders.Right - newRowHeaderWidth; - colHeaders.Width -= newRowHeaderWidth; - } - - newLayout.TopLeftHeader = topLeft; - newLayout.ColumnHeaders = colHeaders; - } - else - { - newLayout.TopLeftHeader = Rectangle.Empty; - } - } - else - { - newLayout.RowHeaders = Rectangle.Empty; - newLayout.TopLeftHeader = Rectangle.Empty; - } - - // The Data region - newLayout.Data = insideLeft; - newLayout.Inside = inside; - - layout = newLayout; - - LayoutScrollBars(); - - // if the user shrank the grid client area, then OnResize invalidated the old - // resize area. however, we need to invalidate the left upper corner in the new ResizeArea - // note that we can't take the Invalidate call from the OnResize method, because if the - // user enlarges the form then the old area will not be invalidated. - // - if (!oldResizeRect.Equals(layout.ResizeBoxRect) && !layout.ResizeBoxRect.IsEmpty) - { - Invalidate(layout.ResizeBoxRect); - } - - layout.dirty = false; - Debug.WriteLineIf(CompModSwitches.DataGridLayout.TraceVerbose, "DataGridLayout: " + layout.ToString()); - } - - /// - /// Computes the number of pixels to scroll to scroll from one - /// row to another. - /// - private int ComputeRowDelta(int from, int to) - { - int first = from; - int last = to; - int sign = -1; - if (first > last) - { - first = to; - last = from; - sign = 1; - } - DataGridRow[] localGridRows = DataGridRows; - int delta = 0; - for (int row = first; row < last; ++row) - { - delta += localGridRows[row].Height; - } - return sign * delta; - } - - internal int MinimumRowHeaderWidth() - { - return minRowHeaderWidth; - } - - internal void ComputeMinimumRowHeaderWidth() - { - minRowHeaderWidth = errorRowBitmapWidth; // the size of the pencil, star and row selector images are the same as the image for the error bitmap - if (ListHasErrors) - { - minRowHeaderWidth += errorRowBitmapWidth; - } - - if (myGridTable != null && myGridTable.RelationsList.Count != 0) - { - minRowHeaderWidth += 15; // the size of the plus/minus glyph and spacing around it - } - } - - /// - /// Updates the internal variables with the number of columns visible - /// inside the Grid's client rectangle. - /// - private void ComputeVisibleColumns() - { - Debug.WriteLineIf(CompModSwitches.DataGridLayout.TraceVerbose, "DataGridLayout: ComputeVisibleColumns"); - EnsureBound(); - - GridColumnStylesCollection columns = myGridTable.GridColumnStyles; - - int nGridCols = columns.Count; - int cx = -negOffset; - int visibleColumns = 0; - int visibleWidth = layout.Data.Width; - int curCol = firstVisibleCol; - - // the same problem with negative numbers: - // if the width passed in is negative, then return 0 - // - // added the check for the columns.Count == 0 - // - if (visibleWidth < 0 || columns.Count == 0) - { - numVisibleCols = firstVisibleCol = 0; - lastTotallyVisibleCol = -1; - return; - } - - while (cx < visibleWidth && curCol < nGridCols) - { - // if (columns.Visible && columns.PropertyDescriptor != null) - if (columns[curCol].PropertyDescriptor != null) - { - cx += columns[curCol].Width; - } - - curCol++; - visibleColumns++; - } - - numVisibleCols = visibleColumns; - - // if we inflate the data area - // then we paint columns to the left of firstVisibleColumn - if (cx < visibleWidth) - { - for (int i = firstVisibleCol - 1; i > 0; i--) - { - if (cx + columns[i].Width > visibleWidth) - { - break; - } - // if (columns.Visible && columns.PropertyDescriptor != null) - if (columns[i].PropertyDescriptor != null) - { - cx += columns[i].Width; - } - - visibleColumns++; - firstVisibleCol--; - } - - if (numVisibleCols != visibleColumns) - { - Debug.Assert(numVisibleCols < visibleColumns, "the number of visible columns can only grow"); - // is there space for more columns than were visible? - // if so, then we need to repaint Data and ColumnHeaders - Invalidate(layout.Data); - Invalidate(layout.ColumnHeaders); - - // update the number of visible columns to the new reality - numVisibleCols = visibleColumns; - } - } - - lastTotallyVisibleCol = firstVisibleCol + numVisibleCols - 1; - if (cx > visibleWidth) - { - if (numVisibleCols <= 1 || (numVisibleCols == 2 && negOffset != 0)) - { - // no column is entirely visible - lastTotallyVisibleCol = -1; - } - else - { - lastTotallyVisibleCol--; - } - } - } - - /// - /// Determines which column is the first visible given - /// the object's horizontalOffset. - /// - private int ComputeFirstVisibleColumn() - { - int first = 0; - if (horizontalOffset == 0) - { - negOffset = 0; - return 0; - } - - // we will check to see if myGridTables.GridColumns.Count != 0 - // because when we reset the dataGridTable, we don't have any columns, and we still - // call HorizontalOffset = 0, and that will call ComputeFirstVisibleColumn with an empty collection of columns. - if (myGridTable != null && myGridTable.GridColumnStyles != null && myGridTable.GridColumnStyles.Count != 0) - { - GridColumnStylesCollection columns = myGridTable.GridColumnStyles; - int cx = 0; - int nGridCols = columns.Count; - - if (columns[0].Width == -1) - { - // the columns are not initialized yet - // -#if DEBUG - for (int i = 0; i < nGridCols; i++) - { - Debug.Assert(columns[i].Width == -1, "the columns' widths should not be initialized"); - } -#endif // DEBUG - negOffset = 0; - return 0; - } - - for (first = 0; first < nGridCols; first++) - { - // if (columns[first].Visible && columns[first].PropertyDescriptor != null); - if (columns[first].PropertyDescriptor != null) - { - cx += columns[first].Width; - } - - if (cx > horizontalOffset) - { - break; - } - } - // first may actually be the number of columns - // in that case all the columns fit in the layout data - if (first == nGridCols) - { - Debug.Assert(cx <= horizontalOffset, "look at the for loop before: we only exit that loop early if the cx is over the horizontal offset"); - negOffset = 0; - return 0; - } - negOffset = columns[first].Width - (cx - horizontalOffset); - //Debug.WriteLineIf(CompModSwitches.DataGridScrolling.TraceVerbose, "DataGridScrolling: ComputeFirstVisibleColumn, ret = " + first.ToString() + ", negOffset = " + negOffset.ToString()); - } - return first; - } - - /// - /// Updates the internal variables with the number of rows visible - /// in a given DataGrid Layout. - /// - private void ComputeVisibleRows() - { - Debug.WriteLineIf(CompModSwitches.DataGridLayout.TraceVerbose, "DataGridLayout: ComputeVisibleRows"); - EnsureBound(); - - Rectangle data = layout.Data; - int visibleHeight = data.Height; - int cy = 0; - int visibleRows = 0; - DataGridRow[] localGridRows = DataGridRows; - int numRows = DataGridRowsLength; - - // when minimizing the dataGrid window, we will get negative values for the - // layout.Data.Width and layout.Data.Height ( is this a - - if (visibleHeight < 0) - { - numVisibleRows = numTotallyVisibleRows = 0; - return; - } - - for (int i = firstVisibleRow; i < numRows; ++i) - { - if (cy > visibleHeight) - { - break; - } - - cy += localGridRows[i].Height; - visibleRows++; - } - - if (cy < visibleHeight) - { - for (int i = firstVisibleRow - 1; i >= 0; i--) - { - int height = localGridRows[i].Height; - if (cy + height > visibleHeight) - { - break; - } - - cy += height; - firstVisibleRow--; - visibleRows++; - } - } - - numVisibleRows = numTotallyVisibleRows = visibleRows; - if (cy > visibleHeight) - { - numTotallyVisibleRows--; - } - - Debug.Assert(numVisibleRows >= 0, "the number of visible rows can't be negative"); - Debug.Assert(numTotallyVisibleRows >= 0, "the number of totally visible rows can't be negative"); - } - - /// - /// Constructs the new instance of the accessibility object for this control. Subclasses - /// should not call base.CreateAccessibilityObject. - /// - protected override AccessibleObject CreateAccessibilityInstance() - { - return new DataGridAccessibleObject(this); - } - - /// - /// Creates a DataGridState representing the child table retrieved - /// from the passed DataRelation. - /// - private DataGridState CreateChildState(string relationName, DataGridRow source) - { - DataGridState dgs = new DataGridState(); - - string newDataMember; - if (string.IsNullOrEmpty(DataMember)) - { - newDataMember = relationName; - } - else - { - newDataMember = DataMember + "." + relationName; - } - - CurrencyManager childLM = (CurrencyManager)BindingContext[DataSource, newDataMember]; - - dgs.DataSource = DataSource; - dgs.DataMember = newDataMember; - dgs.ListManager = childLM; - - dgs.DataGridRows = null; - dgs.DataGridRowsLength = childLM.Count + (policy.AllowAdd ? 1 : 0); - - return dgs; - } - - /// - /// Constructs a Layout object containing the state - /// for a newly constructed DataGrid. - /// - private LayoutData CreateInitialLayoutState() - { - Debug.WriteLineIf(CompModSwitches.DataGridLayout.TraceVerbose, "DataGridLayout: CreateInitialLayoutState"); - LayoutData newLayout = new LayoutData - { - Inside = new Rectangle(), - TopLeftHeader = new Rectangle(), - ColumnHeaders = new Rectangle(), - RowHeaders = new Rectangle(), - Data = new Rectangle(), - Caption = new Rectangle(), - ParentRows = new Rectangle(), - ResizeBoxRect = new Rectangle(), - ColumnHeadersVisible = true, - RowHeadersVisible = true, - CaptionVisible = defaultCaptionVisible, - ParentRowsVisible = defaultParentRowsVisible, - ClientRectangle = ClientRectangle - }; - return newLayout; - } - - /// - /// The DataGrid caches an array of rectangular areas - /// which represent the area which scrolls left to right. - /// This method is invoked whenever the DataGrid needs - /// this scrollable region. - /// - private RECT[] CreateScrollableRegion(Rectangle scroll) - { - if (cachedScrollableRegion != null) - { - return cachedScrollableRegion; - } - - bool alignToRight = isRightToLeft(); - - using (Region region = new Region(scroll)) - { - int nRows = numVisibleRows; - int cy = layout.Data.Y; - int cx = layout.Data.X; - DataGridRow[] localGridRows = DataGridRows; - for (int r = firstVisibleRow; r < nRows; r++) - { - int rowHeight = localGridRows[r].Height; - Rectangle rowExclude = localGridRows[r].GetNonScrollableArea(); - rowExclude.X += cx; - rowExclude.X = MirrorRectangle(rowExclude, layout.Data, alignToRight); - if (!rowExclude.IsEmpty) - { - region.Exclude(new Rectangle(rowExclude.X, - rowExclude.Y + cy, - rowExclude.Width, - rowExclude.Height)); - } - cy += rowHeight; - } - - using (Graphics graphics = CreateGraphicsInternal()) - { - IntPtr handle = region.GetHrgn(graphics); - if (handle != IntPtr.Zero) - { - cachedScrollableRegion = UnsafeNativeMethods.GetRectsFromRegion(handle); - - region.ReleaseHrgn(handle); - } - } - } - - return cachedScrollableRegion; - } - - /// - /// Disposes of the resources (other than memory) used - /// by the . - /// - protected override void Dispose(bool disposing) - { - if (disposing) - { - if (vertScrollBar != null) - { - vertScrollBar.Dispose(); - } - - if (horizScrollBar != null) - { - horizScrollBar.Dispose(); - } - - if (toBeDisposedEditingControl != null) - { - toBeDisposedEditingControl.Dispose(); - toBeDisposedEditingControl = null; - } - - GridTableStylesCollection tables = TableStyles; - if (tables != null) - { -#if DEBUG - Debug.Assert(myGridTable == null || myGridTable.IsDefault || tables.Contains(myGridTable), "how come that the currentTable is not in the list of tables?"); -#endif // DEBUG - for (int i = 0; i < tables.Count; i++) - { - tables[i].Dispose(); - } - } - } - base.Dispose(disposing); - } - - /// - /// Draws an XOR region to give UI feedback for Column Resizing. - /// This looks just like the Splitter control's UI when resizing. - /// - private void DrawColSplitBar(MouseEventArgs e) - { - Rectangle r = CalcColResizeFeedbackRect(e); - DrawSplitBar(r); - } - - /// - /// Draws an XOR region to give UI feedback for Row Resizing. - /// This looks just like the Splitter control's UI when resizing. - /// - private void DrawRowSplitBar(MouseEventArgs e) - { - Rectangle r = CalcRowResizeFeedbackRect(e); - DrawSplitBar(r); - } - - /// - /// Draws an XOR region to give UI feedback for Column/Row Resizing. - /// This looks just like the Splitter control's UI when resizing. - /// - private void DrawSplitBar(Rectangle r) - { - IntPtr parentHandle = Handle; - IntPtr dc = UnsafeNativeMethods.GetDCEx(new HandleRef(this, parentHandle), NativeMethods.NullHandleRef, NativeMethods.DCX_CACHE | NativeMethods.DCX_LOCKWINDOWUPDATE); - IntPtr halftone = ControlPaint.CreateHalftoneHBRUSH(); - IntPtr saveBrush = Gdi32.SelectObject(dc, halftone); - SafeNativeMethods.PatBlt(new HandleRef(this, dc), r.X, r.Y, r.Width, r.Height, NativeMethods.PATINVERT); - Gdi32.SelectObject(dc, saveBrush); - Gdi32.DeleteObject(halftone); - User32.ReleaseDC(new HandleRef(this, parentHandle), dc); - } - - /// - /// Begin in-place editing of a cell. Any editing is commited - /// before the new edit takes place. - /// - /// This will always edit the currentCell - /// If you want to edit another cell than the current one, just reset CurrentCell - /// - private void Edit() - { - Edit(null); - } - - private void Edit(string displayText) - { - EnsureBound(); - - // we want to be able to edit a cell which is not visible, as in the case with editing and scrolling - // at the same time. So do not call Ensure Visible - // - // EnsureVisible(currentRow, currentCol); - - bool cellIsVisible = true; - - // whoever needs to call ResetSelection should not rely on - // Edit() to call it; - // - // ResetSelection(); - - EndEdit(); - - Debug.WriteLineIf(CompModSwitches.DataGridEditing.TraceVerbose, "DataGridEditing: Edit, currentRow = " + currentRow.ToString(CultureInfo.InvariantCulture) + - ", currentCol = " + currentCol.ToString(CultureInfo.InvariantCulture) + (displayText != null ? ", displayText= " + displayText : "")); - - /* allow navigation even if the policy does not allow editing - if (!policy.AllowEdit) - return; - */ - - DataGridRow[] localGridRows = DataGridRows; - - // what do you want to edit when there are no rows? - if (DataGridRowsLength == 0) - { - return; - } - - localGridRows[currentRow].OnEdit(); - editRow = localGridRows[currentRow]; - - // if the list has no columns, then what good is an edit? - if (myGridTable.GridColumnStyles.Count == 0) - { - return; - } - - // what if the currentCol does not have a propDesc? - editColumn = myGridTable.GridColumnStyles[currentCol]; - if (editColumn.PropertyDescriptor == null) - { - return; - } - - Rectangle cellBounds = Rectangle.Empty; - if (currentRow < firstVisibleRow || currentRow > firstVisibleRow + numVisibleRows || - currentCol < firstVisibleCol || currentCol > firstVisibleCol + numVisibleCols - 1 || - (currentCol == firstVisibleCol && negOffset != 0)) - { - cellIsVisible = false; - } - else - { - cellBounds = GetCellBounds(currentRow, currentCol); - } - - gridState[GRIDSTATE_isNavigating] = true; - gridState[GRIDSTATE_isEditing] = false; - - // once we call editColumn.Edit on a DataGridTextBoxColumn - // the edit control will become visible, and its bounds will get set. - // both actions cause Edit.Parent.OnLayout - // so we flag this change, cause we don't want to PerformLayout on the entire DataGrid - // everytime the edit column gets edited - gridState[GRIDSTATE_editControlChanging] = true; - - editColumn.Edit(ListManager, - currentRow, - cellBounds, - myGridTable.ReadOnly || ReadOnly || !policy.AllowEdit, - displayText, - cellIsVisible); - - // reset the editControlChanging to false - gridState[GRIDSTATE_editControlChanging] = false; - } - - /// - /// Requests an end to an edit operation taking place on the - /// - /// control. - /// - public bool EndEdit(DataGridColumnStyle gridColumn, int rowNumber, bool shouldAbort) - { - bool ret = false; - if (gridState[GRIDSTATE_isEditing]) - { - if (gridColumn != editColumn) - { - Debug.WriteLineIf(CompModSwitches.DataGridEditing.TraceVerbose, "DataGridEditing: EndEdit requested on a column we are not editing."); - } - if (rowNumber != editRow.RowNumber) - { - Debug.WriteLineIf(CompModSwitches.DataGridEditing.TraceVerbose, "DataGridEditing: EndEdit requested on a row we are not editing."); - } - if (shouldAbort) - { - AbortEdit(); - ret = true; - } - else - { - ret = CommitEdit(); - } - } - return ret; - } - - /// - /// Ends any editing in progress by attempting to commit and then - /// aborting if not possible. - /// - private void EndEdit() - { - Debug.WriteLineIf(CompModSwitches.DataGridEditing.TraceVerbose, "DataGridEditing: EndEdit"); - - if (!gridState[GRIDSTATE_isEditing] && !gridState[GRIDSTATE_isNavigating]) - { - return; - } - - if (!CommitEdit()) - { - AbortEdit(); - } - } - - // PERF: we attempt to create a ListManager for the DataSource/DateMember combination - // we do this in order to check for a valid DataMember - // if the check succeeds, then it means that we actully put the listManager in the BindingContext's - // list of BindingManagers. this is fine, cause if the check succeds, then Set_ListManager - // will be called, and this will get the listManager from the bindingManagerBase hashTable kept in the BindingContext - // - // this will work if the dataMember does not contain any dots ('.') - // if the dataMember contains dots, then it will be more complicated: maybe part of the binding path - // is valid w/ the new dataSource - // but we can leave w/ this, cause in the designer the dataMember will be only a column name. and the DataSource/DataMember - // properties are for use w/ the designer. - // - private void EnforceValidDataMember(object value) - { - Debug.Assert(value != null, "we should not have a null dataSource when we want to check for a valid dataMember"); - if (DataMember == null || DataMember.Length == 0) - { - return; - } - - if (BindingContext == null) - { - return; - } - // - try - { - BindingManagerBase bm = BindingContext[value, dataMember]; - } - catch - { - dataMember = string.Empty; - } - } - - // will be used by the columns to tell the grid that - // editing is taken place (ie, the grid is no longer in the - // editOrNavigateMode) - // - // also, tell the current row to lose child focus - // - internal protected virtual void ColumnStartedEditing(Rectangle bounds) - { - Debug.Assert(currentRow >= firstVisibleRow && currentRow <= firstVisibleRow + numVisibleRows, "how can one edit a row which is invisible?"); - DataGridRow[] localGridRows = DataGridRows; - - if (bounds.IsEmpty && editColumn is DataGridTextBoxColumn && currentRow != -1 && currentCol != -1) - { - // set the bounds on the control - // this will only work w/ our DataGridTexBox control - DataGridTextBoxColumn col = editColumn as DataGridTextBoxColumn; - Rectangle editBounds = GetCellBounds(currentRow, currentCol); - - gridState[GRIDSTATE_editControlChanging] = true; - try - { - col.TextBox.Bounds = editBounds; - } - finally - { - gridState[GRIDSTATE_editControlChanging] = false; - } - } - - if (gridState[GRIDSTATE_inAddNewRow]) - { - int currentRowCount = DataGridRowsLength; - DataGridRow[] newDataGridRows = new DataGridRow[currentRowCount + 1]; - for (int i = 0; i < currentRowCount; i++) - { - newDataGridRows[i] = localGridRows[i]; - } - - // put the AddNewRow - newDataGridRows[currentRowCount] = new DataGridAddNewRow(this, myGridTable, currentRowCount); - SetDataGridRows(newDataGridRows, currentRowCount + 1); - - Edit(); - // put this after the call to edit so that - // CommitEdit knows that the inAddNewRow is true; - gridState[GRIDSTATE_inAddNewRow] = false; - gridState[GRIDSTATE_isEditing] = true; - gridState[GRIDSTATE_isNavigating] = false; - return; - } - - gridState[GRIDSTATE_isEditing] = true; - gridState[GRIDSTATE_isNavigating] = false; - InvalidateRowHeader(currentRow); - - // tell the current row to lose the childFocuse - if (currentRow < localGridRows.Length) - { - localGridRows[currentRow].LoseChildFocus(layout.RowHeaders, isRightToLeft()); - } - } - - internal protected virtual void ColumnStartedEditing(Control editingControl) - { - if (editingControl == null) - { - return; - } - - ColumnStartedEditing(editingControl.Bounds); - } - - /// - /// Displays child relations, if any exist, for all rows or a - /// specific row. - /// - public void Expand(int row) - { - SetRowExpansionState(row, true); - } - - /// - /// Creates a using the specified . - /// - // protected and virtual because the SimpleDropdownDataGrid will override this - protected virtual DataGridColumnStyle CreateGridColumn(PropertyDescriptor prop, bool isDefault) - { - return myGridTable?.CreateGridColumn(prop, isDefault); - } - - protected virtual DataGridColumnStyle CreateGridColumn(PropertyDescriptor prop) - { - return myGridTable?.CreateGridColumn(prop); - } - -#if PARENT_LINKS - - private ListManager ListManagerForChildColumn(ListManager childListManager, PropertyDescriptor prop) - { - /* - DataKey key; - RelationsCollection relCollection = dataColumn.Table.ParentRelations; - */ - - // this will give us the list of properties of the child - PropertyDescriptorCollection propCollection = childListManager.GetItemProperties(); - - int relCount = propCollection.Count; - for (int i=0;i - /// Specifies the end of the initialization code. - /// - public void EndInit() - { - inInit = false; - if (myGridTable == null && ListManager != null) - { - SetDataGridTable(TableStyles[ListManager.GetListName()], true); // true for forcing column creation - } - if (myGridTable != null) - { - myGridTable.DataGrid = this; - } - } - - /// - /// Given a x coordinate, returns the column it is over. - /// - private int GetColFromX(int x) - { - if (myGridTable == null) - { - return -1; - } - - Rectangle inside = layout.Data; - Debug.Assert(x >= inside.X && x < inside.Right, "x must be inside the horizontal bounds of layout.Data"); - - x = MirrorPoint(x, inside, isRightToLeft()); - - GridColumnStylesCollection columns = myGridTable.GridColumnStyles; - int columnCount = columns.Count; - - int cx = inside.X - negOffset; - int col = firstVisibleCol; - while (cx < inside.Width + inside.X && col < columnCount) - { - // if (columns[col].Visible && columns[col].PropertyDescriptor != null) - if (columns[col].PropertyDescriptor != null) - { - cx += columns[col].Width; - } - - if (cx > x) - { - return col; - } - - ++col; - } - return -1; - } - - /// - /// Returns the coordinate of the left edge of the given column - /// Bi-Di: if the grid has the RightToLeft property set to RightToLeft.Yes, this will - /// return what appears as the right edge of the column - /// - internal int GetColBeg(int col) - { - Debug.Assert(myGridTable != null, "GetColBeg can't be called when myGridTable == null."); - - int offset = layout.Data.X - negOffset; - GridColumnStylesCollection columns = myGridTable.GridColumnStyles; - - int lastCol = Math.Min(col, columns.Count); - for (int i = firstVisibleCol; i < lastCol; ++i) - { - // if (columns[i].Visible && columns[i].PropertyDescriptor != null) - if (columns[i].PropertyDescriptor != null) - { - offset += columns[i].Width; - } - } - return MirrorPoint(offset, layout.Data, isRightToLeft()); - } - - /// - /// Returns the coordinate of the right edge of the given column - /// Bi-Di: if the grid has the RightToLeft property set to RightToLeft.Yes, this will - /// return what appears as the left edge of the column - /// - internal int GetColEnd(int col) - { - // return MirrorPoint(GetColBeg(col) + myGridTable.GridColumnStyles[col].Width, layout.Data, isRightToLeft()); - int colBeg = GetColBeg(col); - Debug.Assert(myGridTable.GridColumnStyles[col].PropertyDescriptor != null, "why would we need the coordinate of a column that is not visible?"); - int width = myGridTable.GridColumnStyles[col].Width; - return isRightToLeft() ? colBeg - width : colBeg + width; - } - - private int GetColumnWidthSum() - { - int sum = 0; - if (myGridTable != null && myGridTable.GridColumnStyles != null) - { - GridColumnStylesCollection columns = myGridTable.GridColumnStyles; - - int columnsCount = columns.Count; - for (int i = 0; i < columnsCount; i++) - { - // if (columns[i].Visible && columns[i].PropertyDescriptor != null) - if (columns[i].PropertyDescriptor != null) - { - sum += columns[i].Width; - } - } - } - return sum; - } - - /// - /// Not all rows in the DataGrid are expandable, - /// this computes which ones are and returns an array - /// of references to them. - /// - private DataGridRelationshipRow[] GetExpandableRows() - { - int nExpandableRows = DataGridRowsLength; - DataGridRow[] localGridRows = DataGridRows; - if (policy.AllowAdd) - { - nExpandableRows = Math.Max(nExpandableRows - 1, 0); - } - - DataGridRelationshipRow[] expandableRows = new DataGridRelationshipRow[nExpandableRows]; - for (int i = 0; i < nExpandableRows; i++) - { - expandableRows[i] = (DataGridRelationshipRow)localGridRows[i]; - } - - return expandableRows; - } - - /// - /// Returns the row number underneath the given y coordinate. - /// - private int GetRowFromY(int y) - { - Rectangle inside = layout.Data; - Debug.Assert(y >= inside.Y && y < inside.Bottom, "y must be inside the vertical bounds of the data"); - - int cy = inside.Y; - int row = firstVisibleRow; - int rowCount = DataGridRowsLength; - DataGridRow[] localGridRows = DataGridRows; - int bottom = inside.Bottom; - while (cy < bottom && row < rowCount) - { - cy += localGridRows[row].Height; - if (cy > y) - { - return row; - } - ++row; - } - return -1; - } - - internal Rectangle GetRowHeaderRect() - { - return layout.RowHeaders; - } - - internal Rectangle GetColumnHeadersRect() - { - return layout.ColumnHeaders; - } - - /// - /// Determines where on the control's ClientRectangle a given row is - /// painting to. - /// - private Rectangle GetRowRect(int rowNumber) - { - Rectangle inside = layout.Data; - int cy = inside.Y; - DataGridRow[] localGridRows = DataGridRows; - for (int row = firstVisibleRow; row <= rowNumber; ++row) - { - if (cy > inside.Bottom) - { - break; - } - if (row == rowNumber) - { - Rectangle rowRect = new Rectangle(inside.X, - cy, - inside.Width, - localGridRows[row].Height); - if (layout.RowHeadersVisible) - { - rowRect.Width += layout.RowHeaders.Width; - rowRect.X -= isRightToLeft() ? 0 : layout.RowHeaders.Width; - } - return rowRect; - } - cy += localGridRows[row].Height; - } - return Rectangle.Empty; - } - - /// - /// Returns the coordinate of the top edge of the given row - /// - private int GetRowTop(int row) - { - DataGridRow[] localGridRows = DataGridRows; - int offset = layout.Data.Y; - int lastRow = Math.Min(row, DataGridRowsLength); - for (int i = firstVisibleRow; i < lastRow; ++i) - { - offset += localGridRows[i].Height; - } - for (int i = firstVisibleRow; i > lastRow; i--) - { - offset -= localGridRows[i].Height; - } - return offset; - } - - /// - /// Returns the coordinate of the bottom edge of the given row - /// - private int GetRowBottom(int row) - { - DataGridRow[] localGridRows = DataGridRows; - - return GetRowTop(row) + localGridRows[row].Height; - } - - /// - /// This method is called on methods that need the grid - /// to be bound to a DataTable to work. - /// - private void EnsureBound() - { - if (!Bound) - { - throw new InvalidOperationException(SR.DataGridUnbound); - } - } - - private void EnsureVisible(int row, int col) - { - if (row < firstVisibleRow - || row >= firstVisibleRow + numTotallyVisibleRows) - { - int dRows = ComputeDeltaRows(row); - ScrollDown(dRows); - } - - if (firstVisibleCol == 0 && numVisibleCols == 0 && lastTotallyVisibleCol == -1) - { - // no columns are displayed whatsoever - // some sanity checks - Debug.Assert(negOffset == 0, " no columns are displayed so the negative offset should be 0"); - return; - } - - int previousFirstVisibleCol = firstVisibleCol; - int previousNegOffset = negOffset; - int previousLastTotallyVisibleCol = lastTotallyVisibleCol; - - while (col < firstVisibleCol - || col == firstVisibleCol && negOffset != 0 - || lastTotallyVisibleCol == -1 && col > firstVisibleCol - || lastTotallyVisibleCol > -1 && col > lastTotallyVisibleCol) - { - - ScrollToColumn(col); - - if (previousFirstVisibleCol == firstVisibleCol && - previousNegOffset == negOffset && - previousLastTotallyVisibleCol == lastTotallyVisibleCol) - { - // nothing changed since the last iteration - // don't get into an infinite loop - break; - } - previousFirstVisibleCol = firstVisibleCol; - previousNegOffset = negOffset; - previousLastTotallyVisibleCol = lastTotallyVisibleCol; - - // continue to scroll to the right until the scrollTo column is the totally last visible column or it is the first visible column - } - } - - /// - /// Gets a - /// that specifies the four corners of the selected cell. - /// - public Rectangle GetCurrentCellBounds() - { - DataGridCell current = CurrentCell; - return GetCellBounds(current.RowNumber, current.ColumnNumber); - } - - /// - /// Gets the of the cell specified by row and column number. - /// - public Rectangle GetCellBounds(int row, int col) - { - DataGridRow[] localGridRows = DataGridRows; - Rectangle cellBounds = localGridRows[row].GetCellBounds(col); - cellBounds.Y += GetRowTop(row); - cellBounds.X += layout.Data.X - negOffset; - cellBounds.X = MirrorRectangle(cellBounds, layout.Data, isRightToLeft()); - return cellBounds; - } - - /// - /// Gets the of the cell specified by . - /// - public Rectangle GetCellBounds(DataGridCell dgc) - { - return GetCellBounds(dgc.RowNumber, dgc.ColumnNumber); - } - - // - - internal Rectangle GetRowBounds(DataGridRow row) - { - Rectangle rowBounds = new Rectangle - { - Y = GetRowTop(row.RowNumber), - X = layout.Data.X, - Height = row.Height, - Width = layout.Data.Width - }; - return rowBounds; - } - - /// - /// Gets information, such as row and column number of a - /// clicked point on - /// the grid, - /// using the x - /// and y coordinate passed to the method. - /// - public HitTestInfo HitTest(int x, int y) - { - int topOfData = layout.Data.Y; - HitTestInfo ci = new HitTestInfo(); - - if (layout.CaptionVisible && layout.Caption.Contains(x, y)) - { - ci.type = HitTestType.Caption; - return ci; - } - if (layout.ParentRowsVisible && layout.ParentRows.Contains(x, y)) - { - ci.type = HitTestType.ParentRows; - return ci; - } - - if (!layout.Inside.Contains(x, y)) - { - return ci; - } - - if (layout.TopLeftHeader.Contains(x, y)) - { - return ci; - } - - // check for column resize - if (layout.ColumnHeaders.Contains(x, y)) - { - ci.type = HitTestType.ColumnHeader; - ci.col = GetColFromX(x); - if (ci.col < 0) - { - return HitTestInfo.Nowhere; - } - - int right = GetColBeg(ci.col + 1); - bool rightToLeft = isRightToLeft(); - if ((rightToLeft && x - right < 8) || (!rightToLeft && right - x < 8)) - { - ci.type = HitTestType.ColumnResize; - } - return (allowColumnResize ? ci : HitTestInfo.Nowhere); - } - - //check for RowResize: - if (layout.RowHeaders.Contains(x, y)) - { - ci.type = HitTestType.RowHeader; - ci.row = GetRowFromY(y); - if (ci.row < 0) - { - return HitTestInfo.Nowhere; - } - - // find out if the click was a RowResize click - DataGridRow[] localGridRows = DataGridRows; - int bottomBorder = GetRowTop(ci.row) + localGridRows[ci.row].Height; - if (bottomBorder - y - BorderWidth < 2 && !(localGridRows[ci.row] is DataGridAddNewRow)) - { - ci.type = HitTestType.RowResize; - } - - return (allowRowResize ? ci : HitTestInfo.Nowhere); - } - - if (layout.Data.Contains(x, y)) - { - ci.type = HitTestType.Cell; - ci.col = GetColFromX(x); - ci.row = GetRowFromY(y); - if (ci.col < 0 || ci.row < 0) - { - return HitTestInfo.Nowhere; - } - - return ci; - } - return ci; - } - - /// - /// Gets information, such as row and column number of a - /// clicked point on the grid, about the - /// grid using a specific - /// . - /// - public HitTestInfo HitTest(Point position) - { - return HitTest(position.X, position.Y); - } - - /// - /// Initializes the values for column widths in the table. - /// - private void InitializeColumnWidths() - { - if (myGridTable == null) - { - return; - } - - GridColumnStylesCollection columns = myGridTable.GridColumnStyles; - int numCols = columns.Count; - - // Resize the columns to a approximation of a best fit. - // We find the best fit width of NumRowsForAutoResize rows - // and use it for each column. - int preferredColumnWidth = myGridTable.IsDefault ? PreferredColumnWidth : myGridTable.PreferredColumnWidth; - // if we set the PreferredColumnWidth to something else than AutoColumnSize - // then use that value - // - for (int col = 0; col < numCols; col++) - { - // if the column width is not -1, then this column was initialized already - if (columns[col]._width != -1) - { - continue; - } - - columns[col]._width = preferredColumnWidth; - } - } - - /// - /// Invalidates the scrollable area of the DataGrid. - /// - internal void InvalidateInside() - { - Invalidate(layout.Inside); - } - - /// - /// Invalidates the caption area of the DataGrid. - /// - internal void InvalidateCaption() - { - if (layout.CaptionVisible) - { - Invalidate(layout.Caption); - } - } - - /// - /// Invalidates a rectangle normalized to the caption's - /// visual bounds. - /// - internal void InvalidateCaptionRect(Rectangle r) - { - if (layout.CaptionVisible) - { - Invalidate(r); - } - } - - /// - /// Invalidates the display region of a given DataGridColumn. - /// - internal void InvalidateColumn(int column) - { - GridColumnStylesCollection gridColumns = myGridTable.GridColumnStyles; - if (column < 0 || gridColumns == null || gridColumns.Count <= column) - { - return; - } - - Debug.Assert(gridColumns[column].PropertyDescriptor != null, "how can we invalidate a column that is invisible?"); - // bail if the column is not visible. - if (column < firstVisibleCol || column > firstVisibleCol + numVisibleCols - 1) - { - return; - } - - Rectangle columnArea = new Rectangle - { - Height = layout.Data.Height, - Width = gridColumns[column].Width, - Y = layout.Data.Y - }; - - int x = layout.Data.X - negOffset; - int gridColumnsCount = gridColumns.Count; - for (int i = firstVisibleCol; i < gridColumnsCount; ++i) - { - if (i == column) - { - break; - } - - x += gridColumns[i].Width; - } - columnArea.X = x; - columnArea.X = MirrorRectangle(columnArea, layout.Data, isRightToLeft()); - Invalidate(columnArea); - } - - /// - /// Invalidates the parent rows area of the DataGrid - /// - internal void InvalidateParentRows() - { - if (layout.ParentRowsVisible) - { - Invalidate(layout.ParentRows); - } - } - - /// - /// Invalidates a rectangle normalized to the parent - /// rows area's visual bounds. - /// - internal void InvalidateParentRowsRect(Rectangle r) - { - Rectangle parentRowsRect = layout.ParentRows; - Invalidate(r); - if (!parentRowsRect.IsEmpty) - { - //Invalidate(new Rectangle(parentRowsRect.X + r.X, parentRowsRect.Y + r.Y, - // r.Width, r.Height)); - } - } - - /// - /// Invalidate the painting region for the row specified. - /// - internal void InvalidateRow(int rowNumber) - { - Rectangle rowRect = GetRowRect(rowNumber); - if (!rowRect.IsEmpty) - { - Debug.WriteLineIf(CompModSwitches.DataGridPainting.TraceVerbose, "DataGridPainting: Invalidating row " + rowNumber.ToString(CultureInfo.InvariantCulture)); - Invalidate(rowRect); - } - } - - private void InvalidateRowHeader(int rowNumber) - { - if (rowNumber >= firstVisibleRow && rowNumber < firstVisibleRow + numVisibleRows) - { - if (!layout.RowHeadersVisible) - { - return; - } - - Rectangle invalid = new Rectangle - { - Y = GetRowTop(rowNumber), - X = layout.RowHeaders.X, - Width = layout.RowHeaders.Width, - Height = DataGridRows[rowNumber].Height - }; - Invalidate(invalid); - } - } - - // NOTE: - // because of Rtl, we assume that the only place that calls InvalidateRowRect is - // the DataGridRelationshipRow - internal void InvalidateRowRect(int rowNumber, Rectangle r) - { - Rectangle rowRect = GetRowRect(rowNumber); - if (!rowRect.IsEmpty) - { - Debug.WriteLineIf(CompModSwitches.DataGridPainting.TraceVerbose, "DataGridPainting: Invalidating a rect in row " + rowNumber.ToString(CultureInfo.InvariantCulture)); - Rectangle inner = new Rectangle(rowRect.X + r.X, rowRect.Y + r.Y, r.Width, r.Height); - if (vertScrollBar.Visible && isRightToLeft()) - { - inner.X -= vertScrollBar.Width; - } - - Invalidate(inner); - } - } - - /// - /// Gets a value that indicates whether a specified row's node is expanded or collapsed. - /// - public bool IsExpanded(int rowNumber) - { - if (rowNumber < 0 || rowNumber > DataGridRowsLength) - { - throw new ArgumentOutOfRangeException(nameof(rowNumber)); - } - - DataGridRow[] localGridRows = DataGridRows; - - // - - DataGridRow row = localGridRows[rowNumber]; - if (row is DataGridRelationshipRow relRow) - { - return relRow.Expanded; - } - else - { - return false; - } - } - - /// - /// Gets a value indicating whether a - /// specified row is selected. - /// - public bool IsSelected(int row) - { - // - DataGridRow[] localGridRows = DataGridRows; - return localGridRows[row].Selected; - } - - internal static bool IsTransparentColor(Color color) - { - return color.A < 255; - } - - /// - /// Determines if Scrollbars should be visible, - /// updates their bounds and the bounds of all - /// other regions in the DataGrid's Layout. - /// - private void LayoutScrollBars() - { - // if we set the dataSource to null, then take away the scrollbars. - if (listManager == null || myGridTable == null) - { - horizScrollBar.Visible = false; - vertScrollBar.Visible = false; - return; - } - - // Scrollbars are a tricky issue. - // We need to see if we can cram our columns and rows - // in without scrollbars and if they don't fit, we make - // scrollbars visible and then fixup our regions for the - // data and headers. - bool needHorizScrollbar = false; - bool needVertScrollbar = false; - bool recountRows = false; - bool alignToRight = isRightToLeft(); - - int nGridCols = myGridTable.GridColumnStyles.Count; - - // if we call LayoutScrollBars before CreateDataGridRows - // then the columns will have their default width ( 100 ) - // CreateDataGridRows will possibly change the columns' width - // - // and anyway, ComputeVisibleRows will call the DataGridRows accessor - // - DataGridRow[] gridRows = DataGridRows; - - // at this stage, the data grid columns may have their width set to -1 ( ie, their width is uninitialized ) - // make sure that the totalWidth is at least 0 - int totalWidth = Math.Max(0, GetColumnWidthSum()); - - if (totalWidth > layout.Data.Width && !needHorizScrollbar) - { - int horizHeight = horizScrollBar.Height; - layout.Data.Height -= horizHeight; - if (layout.RowHeadersVisible) - { - layout.RowHeaders.Height -= horizHeight; - } - - needHorizScrollbar = true; - } - - int oldFirstVisibleRow = firstVisibleRow; - - ComputeVisibleRows(); - if (numTotallyVisibleRows != DataGridRowsLength && !needVertScrollbar) - { - int vertWidth = vertScrollBar.Width; - layout.Data.Width -= vertWidth; - if (layout.ColumnHeadersVisible) - { - if (alignToRight) - { - layout.ColumnHeaders.X += vertWidth; - } - - layout.ColumnHeaders.Width -= vertWidth; - } - needVertScrollbar = true; - } - - firstVisibleCol = ComputeFirstVisibleColumn(); - // we compute the number of visible columns only after we set up the vertical scroll bar. - ComputeVisibleColumns(); - - if (needVertScrollbar && totalWidth > layout.Data.Width && !needHorizScrollbar) - { - firstVisibleRow = oldFirstVisibleRow; - int horizHeight = horizScrollBar.Height; - layout.Data.Height -= horizHeight; - if (layout.RowHeadersVisible) - { - layout.RowHeaders.Height -= horizHeight; - } - - needHorizScrollbar = true; - recountRows = true; - } - - if (recountRows) - { - ComputeVisibleRows(); - if (numTotallyVisibleRows != DataGridRowsLength && !needVertScrollbar) - { - int vertWidth = vertScrollBar.Width; - layout.Data.Width -= vertWidth; - if (layout.ColumnHeadersVisible) - { - if (alignToRight) - { - layout.ColumnHeaders.X += vertWidth; - } - - layout.ColumnHeaders.Width -= vertWidth; - } - needVertScrollbar = true; - } - } - - layout.ResizeBoxRect = new Rectangle(); - if (needVertScrollbar && needHorizScrollbar) - { - Rectangle data = layout.Data; - layout.ResizeBoxRect = new Rectangle(alignToRight ? data.X : data.Right, - data.Bottom, - vertScrollBar.Width, - horizScrollBar.Height); - } - - if (needHorizScrollbar && nGridCols > 0) - { - //Debug.WriteLineIf(CompModSwitches.DataGridScrolling.TraceVerbose, "DataGridScrolling: foo"); - - int widthNotVisible = totalWidth - layout.Data.Width; - - horizScrollBar.Minimum = 0; - horizScrollBar.Maximum = totalWidth; - horizScrollBar.SmallChange = 1; - horizScrollBar.LargeChange = Math.Max(totalWidth - widthNotVisible, 0); - horizScrollBar.Enabled = Enabled; - horizScrollBar.RightToLeft = RightToLeft; - horizScrollBar.Bounds = new Rectangle(alignToRight ? layout.Inside.X + layout.ResizeBoxRect.Width : layout.Inside.X, - layout.Data.Bottom, - layout.Inside.Width - layout.ResizeBoxRect.Width, - horizScrollBar.Height); - horizScrollBar.Visible = true; - } - else - { - HorizontalOffset = 0; - horizScrollBar.Visible = false; - } - - if (needVertScrollbar) - { - int vertScrollBarTop = layout.Data.Y; - if (layout.ColumnHeadersVisible) - { - vertScrollBarTop = layout.ColumnHeaders.Y; - } - // if numTotallyVisibleRows == 0 ( the height of the row is bigger than the height of - // the grid ) then scroll in increments of 1. - vertScrollBar.LargeChange = numTotallyVisibleRows != 0 ? numTotallyVisibleRows : 1; - vertScrollBar.Bounds = new Rectangle(alignToRight ? layout.Data.X : layout.Data.Right, - vertScrollBarTop, - vertScrollBar.Width, - layout.Data.Height + layout.ColumnHeaders.Height); - vertScrollBar.Enabled = Enabled; - vertScrollBar.Visible = true; - if (alignToRight) - { - layout.Data.X += vertScrollBar.Width; - } - } - else - { - vertScrollBar.Visible = false; - } - } - - /// - /// Navigates back to the table previously displayed in the grid. - /// - public void NavigateBack() - { - if (!CommitEdit() || parentRows.IsEmpty()) - { - return; - } - // when navigating back, if the grid is inAddNewRow state, cancel the currentEdit. - // we do not need to recreate the rows cause we are navigating back. - // the grid will catch any exception that happens. - if (gridState[GRIDSTATE_inAddNewRow]) - { - gridState[GRIDSTATE_inAddNewRow] = false; - try - { - listManager.CancelCurrentEdit(); - } - catch - { - } - } - else - { - UpdateListManager(); - } - - DataGridState newState = parentRows.PopTop(); - - ResetMouseState(); - - newState.PullState(this, false); // we do not want to create columns when navigating back - - // we need to have originalState != null when we process - // Set_ListManager in the NavigateBack/NavigateTo methods. - // otherwise the DataSource_MetaDataChanged event will not get registered - // properly - if (parentRows.GetTopParent() == null) - { - originalState = null; - } - - DataGridRow[] localGridRows = DataGridRows; - // what if the user changed the ReadOnly property - // on the grid while the user was navigating to the child rows? - // - // what if the policy does not allow for allowAdd? - // - if ((ReadOnly || !policy.AllowAdd) == (localGridRows[DataGridRowsLength - 1] is DataGridAddNewRow)) - { - int newDataGridRowsLength = (ReadOnly || !policy.AllowAdd) ? DataGridRowsLength - 1 : DataGridRowsLength + 1; - DataGridRow[] newDataGridRows = new DataGridRow[newDataGridRowsLength]; - for (int i = 0; i < Math.Min(newDataGridRowsLength, DataGridRowsLength); i++) - { - newDataGridRows[i] = DataGridRows[i]; - } - if (!ReadOnly && policy.AllowAdd) - { - newDataGridRows[newDataGridRowsLength - 1] = new DataGridAddNewRow(this, myGridTable, newDataGridRowsLength - 1); - } - - SetDataGridRows(newDataGridRows, newDataGridRowsLength); - } - - // when we navigate back from a child table, - // it may be the case that in between the user added a tableStyle that is different - // from the one that is currently in the grid - // in that case, we need to reset the dataGridTableStyle in the rows - localGridRows = DataGridRows; - if (localGridRows != null && localGridRows.Length != 0) - { - DataGridTableStyle dgTable = localGridRows[0].DataGridTableStyle; - if (dgTable != myGridTable) - { - for (int i = 0; i < localGridRows.Length; i++) - { - localGridRows[i].DataGridTableStyle = myGridTable; - } - } - } - - // if we have the default table, when we navigate back - // we also have the default gridColumns, w/ width = -1 - // we need to set the width on the new gridColumns - // - if (myGridTable.GridColumnStyles.Count > 0 && myGridTable.GridColumnStyles[0].Width == -1) - { -#if DEBUG - GridColumnStylesCollection cols = myGridTable.GridColumnStyles; - for (int i = 0; i < cols.Count; i++) - { - Debug.Assert(cols[i].Width == -1, "Sanity check"); - } - Debug.Assert(myGridTable.IsDefault, "when we navigate to the parent rows and the columns have widths -1 we are using the default table"); -#endif // DEBUG - InitializeColumnWidths(); - } - - // reset the currentRow to the old position in the listmanager: - currentRow = ListManager.Position == -1 ? 0 : ListManager.Position; - - // if the AllowNavigation changed while the user was navigating the - // child tables, so that the new navigation mode does not allow childNavigation anymore - // then reset the rows - if (!AllowNavigation) - { - RecreateDataGridRows(); - } - - caption.BackButtonActive = (parentRows.GetTopParent() != null) && AllowNavigation; - caption.BackButtonVisible = caption.BackButtonActive; - caption.DownButtonActive = (parentRows.GetTopParent() != null); - - PerformLayout(); - Invalidate(); - // reposition the scroll bar - if (vertScrollBar.Visible) - { - vertScrollBar.Value = firstVisibleRow; - } - - if (horizScrollBar.Visible) - { - horizScrollBar.Value = HorizontalOffset + negOffset; - } - - Edit(); - OnNavigate(new NavigateEventArgs(false)); - } - - /// - /// Navigates to the table specified by row and relation - /// name. - /// - public void NavigateTo(int rowNumber, string relationName) - { - // do not navigate if AllowNavigation is set to false - if (!AllowNavigation) - { - return; - } - - DataGridRow[] localGridRows = DataGridRows; - if (rowNumber < 0 || rowNumber > DataGridRowsLength - (policy.AllowAdd ? 2 : 1)) - { - throw new ArgumentOutOfRangeException(nameof(rowNumber)); - } - EnsureBound(); - - DataGridRow source = localGridRows[rowNumber]; - - NavigateTo(relationName, source, false); - } - - internal void NavigateTo(string relationName, DataGridRow source, bool fromRow) - { - // do not navigate if AllowNavigation is set to false - if (!AllowNavigation) - { - return; - } - // Commit the edit if possible - if (!CommitEdit()) - { - return; - } - - DataGridState childState; - try - { - childState = CreateChildState(relationName, source); - } - catch - { - // if we get an error when creating the RelatedCurrencyManager - // then navigateBack and ignore the exception. - // - NavigateBack(); - return; - } - - // call EndCurrentEdit before navigating. - // if we get an exception, we do not navigate. - // - try - { - listManager.EndCurrentEdit(); - } - catch - { - return; - } - - // Preserve our current state - // we need to do this after the EndCurrentEdit, otherwise the - // DataGridState will get the listChanged event from the EndCurrentEdit - DataGridState dgs = new DataGridState(this) - { - LinkingRow = source - }; - - // we need to update the Position in the ListManager - // ( the RelatedListManager uses only the position in the parentManager - // to create the childRows - // - // before the code was calling CurrentCell = this and such - // we should only call EndCurrentEdit ( which the code was doing anyway ) - // and then set the position in the listManager to the new row. - // - if (source.RowNumber != CurrentRow) - { - listManager.Position = source.RowNumber; - } - - // We save our state if the parent rows stack is empty. - if (parentRows.GetTopParent() == null) - { - originalState = dgs; - } - - parentRows.AddParent(dgs); - - NavigateTo(childState); - - OnNavigate(new NavigateEventArgs(true)); - if (fromRow) - { - // OnLinkClick(EventArgs.Empty); - } - } - - private void NavigateTo(DataGridState childState) - { - // we are navigating... better stop editing. - EndEdit(); - - // also, we are no longer in editOrNavigate mode either - gridState[GRIDSTATE_isNavigating] = false; - - // reset hot tracking - ResetMouseState(); - - // Retrieve the child state - childState.PullState(this, true); // true for creating columns when we navigate to child rows - - if (listManager.Position != currentRow) - { - currentRow = listManager.Position == -1 ? 0 : listManager.Position; - } - - if (parentRows.GetTopParent() != null) - { - caption.BackButtonActive = AllowNavigation; - caption.BackButtonVisible = caption.BackButtonActive; - caption.DownButtonActive = true; - } - - HorizontalOffset = 0; - PerformLayout(); - Invalidate(); - } - - /// - /// Given a coordinate in the control this method returns - /// the equivalent point for a row. - /// - private Point NormalizeToRow(int x, int y, int row) - { - Debug.Assert(row >= firstVisibleRow && row < firstVisibleRow + numVisibleRows, - "Row " + row.ToString(CultureInfo.InvariantCulture) + "is not visible! firstVisibleRow = " + - firstVisibleRow.ToString(CultureInfo.InvariantCulture) + ", numVisibleRows = " + - numVisibleRows.ToString(CultureInfo.InvariantCulture)); - Point origin = new Point(0, layout.Data.Y); - - DataGridRow[] localGridRows = DataGridRows; - for (int r = firstVisibleRow; r < row; ++r) - { - origin.Y += localGridRows[r].Height; - } - // when hittesting for the PlusMinus, the code in the DataGridRelationshipRow - // will use real X coordinate ( the one from layout.RowHeaders ) to paint the glyph - // - return new Point(x, y - origin.Y); - } - - internal void OnColumnCollectionChanged(object sender, CollectionChangeEventArgs e) - { - DataGridTableStyle table = (DataGridTableStyle)sender; - if (table.Equals(myGridTable)) - { - // if we changed the column collection, then we need to set the property - // descriptors in the column collection. - // unless the user set the propertyDescriptor in the columnCollection - // - if (!myGridTable.IsDefault) - { - // if the element in the collectionChangeEventArgs is not null - // and the action is refresh, then it means that the user - // set the propDesc. we do not want to override this. - if (e.Action != CollectionChangeAction.Refresh || e.Element == null) - { - PairTableStylesAndGridColumns(listManager, myGridTable, false); - } - } - Invalidate(); - PerformLayout(); - } - } - - /// - /// Paints column headers. - /// - private void PaintColumnHeaders(Graphics g) - { - bool alignToLeft = isRightToLeft(); - Rectangle boundingRect = layout.ColumnHeaders; - if (!alignToLeft) - { - boundingRect.X -= negOffset; - } - - boundingRect.Width += negOffset; - - int columnHeaderWidth = PaintColumnHeaderText(g, boundingRect); - - if (alignToLeft) - { - boundingRect.X = boundingRect.Right - columnHeaderWidth; - } - - boundingRect.Width = columnHeaderWidth; - if (!FlatMode) - { - ControlPaint.DrawBorder3D(g, boundingRect, Border3DStyle.RaisedInner); - boundingRect.Inflate(-1, -1); - // g.SetPen(OldSystemPens.Control); - // g.OldBrush = (OldSystemBrushes.Hollow); - boundingRect.Width--; - boundingRect.Height--; - g.DrawRectangle(SystemPens.Control, boundingRect); - } - } - - private int PaintColumnHeaderText(Graphics g, Rectangle boundingRect) - { - int cx = 0; - Rectangle textBounds = boundingRect; - GridColumnStylesCollection gridColumns = myGridTable.GridColumnStyles; - bool alignRight = isRightToLeft(); - - int nGridCols = gridColumns.Count; - // for sorting - PropertyDescriptor sortProperty = null; - sortProperty = ListManager.GetSortProperty(); - - // Now paint the column header text! - for (int col = firstVisibleCol; col < nGridCols; ++col) - { - if (gridColumns[col].PropertyDescriptor == null) - { - continue; - } - - if (cx > boundingRect.Width) - { - break; - } - - bool columnSorted = sortProperty != null && sortProperty.Equals(gridColumns[col].PropertyDescriptor); - TriangleDirection whichWay = TriangleDirection.Up; - if (columnSorted) - { - ListSortDirection direction = ListManager.GetSortDirection(); - if (direction == ListSortDirection.Descending) - { - whichWay = TriangleDirection.Down; - } - } - - if (alignRight) - { - textBounds.Width = gridColumns[col].Width - - (columnSorted ? textBounds.Height : 0); - textBounds.X = boundingRect.Right - cx - textBounds.Width; - } - else - { - textBounds.X = boundingRect.X + cx; - textBounds.Width = gridColumns[col].Width - - (columnSorted ? textBounds.Height : 0); - } - - // at the moment we paint some pixels twice. - // we should not call FilLRectangle, once the real GDI+ is there, we will have no need to do that - - // if the user set the HeaderBackBrush property on the - // dataGrid, then use that property - Brush headerBrush; - if (myGridTable.IsDefault) - { - headerBrush = HeaderBackBrush; - } - else - { - headerBrush = myGridTable.HeaderBackBrush; - } - - g.FillRectangle(headerBrush, textBounds); - // granted, the code would be a lot cleaner if we were using a "new Rectangle" - // but like this will be faster - if (alignRight) - { - textBounds.X -= 2; - textBounds.Y += 2; - } - else - { - textBounds.X += 2; - textBounds.Y += 2; - } - - StringFormat format = new StringFormat(); - - // the columnHeaderText alignment should be the same as - // the alignment in the column - // - HorizontalAlignment colAlignment = gridColumns[col].Alignment; - format.Alignment = colAlignment == HorizontalAlignment.Right ? StringAlignment.Far : - colAlignment == HorizontalAlignment.Center ? StringAlignment.Center : - StringAlignment.Near; - - // part 1, section 1: the column headers should not wrap - format.FormatFlags |= StringFormatFlags.NoWrap; - - if (alignRight) - { - format.FormatFlags |= StringFormatFlags.DirectionRightToLeft; - format.Alignment = StringAlignment.Near; - } - g.DrawString(gridColumns[col].HeaderText, - myGridTable.IsDefault ? HeaderFont : myGridTable.HeaderFont, - myGridTable.IsDefault ? HeaderForeBrush : myGridTable.HeaderForeBrush, - textBounds, - format); - format.Dispose(); - - if (alignRight) - { - textBounds.X += 2; - textBounds.Y -= 2; - } - else - { - textBounds.X -= 2; - textBounds.Y -= 2; - } - - if (columnSorted) - { - // - - Rectangle triBounds = new Rectangle(alignRight ? textBounds.X - textBounds.Height : textBounds.Right, - textBounds.Y, - textBounds.Height, - textBounds.Height); - - g.FillRectangle(headerBrush, triBounds); - int deflateValue = Math.Max(0, (textBounds.Height - 5) / 2); - triBounds.Inflate(-deflateValue, -deflateValue); - - Pen pen1 = new Pen(BackgroundBrush); - Pen pen2 = new Pen(myGridTable.BackBrush); - Triangle.Paint(g, triBounds, whichWay, headerBrush, pen1, pen2, pen1, true); - pen1.Dispose(); - pen2.Dispose(); - } - int paintedWidth = textBounds.Width + (columnSorted ? textBounds.Height : 0); - - if (!FlatMode) - { - if (alignRight && columnSorted) - { - textBounds.X -= textBounds.Height; - } - - textBounds.Width = paintedWidth; - - ControlPaint.DrawBorder3D(g, textBounds, Border3DStyle.RaisedInner); - } - cx += paintedWidth; - } - - // paint the possible exposed portion to the right ( or left, as the case may be) - if (cx < boundingRect.Width) - { - textBounds = boundingRect; - - if (!alignRight) - { - textBounds.X += cx; - } - - textBounds.Width -= cx; - g.FillRectangle(backgroundBrush, textBounds); - } - return cx; - } - - /// - /// Paints a border around the bouding rectangle given - /// - private void PaintBorder(Graphics g, Rectangle bounds) - { - if (BorderStyle == BorderStyle.None) - { - return; - } - - if (BorderStyle == BorderStyle.Fixed3D) - { - Border3DStyle style = Border3DStyle.Sunken; - ControlPaint.DrawBorder3D(g, bounds, style); - } - else if (BorderStyle == BorderStyle.FixedSingle) - { - Brush br; - - if (myGridTable.IsDefault) - { - br = HeaderForeBrush; - } - else - { - br = myGridTable.HeaderForeBrush; - } - - g.FillRectangle(br, bounds.X, bounds.Y, bounds.Width + 2, 2); - g.FillRectangle(br, bounds.Right - 2, bounds.Y, 2, bounds.Height + 2); - g.FillRectangle(br, bounds.X, bounds.Bottom - 2, bounds.Width + 2, 2); - g.FillRectangle(br, bounds.X, bounds.Y, 2, bounds.Height + 2); - } - else - { - Pen pen = SystemPens.WindowFrame; - bounds.Width--; - bounds.Height--; - g.DrawRectangle(pen, bounds); - } - } - - /// - /// Paints the grid in the bounding rectangle given. - /// This includes the column headers and each visible row. - /// - private void PaintGrid(Graphics g, Rectangle gridBounds) - { - Debug.WriteLineIf(CompModSwitches.DataGridPainting.TraceVerbose, "DataGridPainting: PaintGrid on " + gridBounds.ToString()); - - Rectangle rc = gridBounds; - - if (listManager != null) - { - if (layout.ColumnHeadersVisible) - { - Region r = g.Clip; - g.SetClip(layout.ColumnHeaders); - PaintColumnHeaders(g); - g.Clip = r; - r.Dispose(); - int columnHeaderHeight = layout.ColumnHeaders.Height; - rc.Y += columnHeaderHeight; - rc.Height -= columnHeaderHeight; - } - - if (layout.TopLeftHeader.Width > 0) - { - if (myGridTable.IsDefault) - { - g.FillRectangle(HeaderBackBrush, layout.TopLeftHeader); - } - else - { - g.FillRectangle(myGridTable.HeaderBackBrush, layout.TopLeftHeader); - } - - if (!FlatMode) - { - ControlPaint.DrawBorder3D(g, layout.TopLeftHeader, Border3DStyle.RaisedInner); - } - } - - PaintRows(g, ref rc); - } - - // paint the possible exposed portion below - if (rc.Height > 0) - { - g.FillRectangle(backgroundBrush, rc); - } - } - - private void DeleteDataGridRows(int deletedRows) - { - if (deletedRows == 0) - { - return; - } - - int currentRowCount = DataGridRowsLength; - int newDataGridRowsLength = currentRowCount - deletedRows + (gridState[GRIDSTATE_inAddNewRow] ? 1 : 0); - DataGridRow[] newDataGridRows = new DataGridRow[newDataGridRowsLength]; - DataGridRow[] gridRows = DataGridRows; - - // the number of selected entries so far in the array - int selectedEntries = 0; - - for (int i = 0; i < currentRowCount; i++) - { - if (gridRows[i].Selected) - { - selectedEntries++; - } - else - { - newDataGridRows[i - selectedEntries] = gridRows[i]; - newDataGridRows[i - selectedEntries].number = i - selectedEntries; - } - } - - if (gridState[GRIDSTATE_inAddNewRow]) - { - newDataGridRows[currentRowCount - selectedEntries] = new DataGridAddNewRow(this, myGridTable, currentRowCount - selectedEntries); - gridState[GRIDSTATE_inAddNewRow] = false; - } - - Debug.Assert(selectedEntries == deletedRows, "all the rows that would have been deleted should have been selected: selectedGridEntries " + selectedEntries.ToString(CultureInfo.InvariantCulture) + " deletedRows " + deletedRows.ToString(CultureInfo.InvariantCulture)); - - SetDataGridRows(newDataGridRows, newDataGridRowsLength); - } - - /// - /// Paints the visible rows on the grid. - /// - private void PaintRows(Graphics g, ref Rectangle boundingRect) - { - int cy = 0; - bool alignRight = isRightToLeft(); - Rectangle rowBounds = boundingRect; - Rectangle dataBounds = Rectangle.Empty; - bool paintRowHeaders = layout.RowHeadersVisible; - Rectangle headerBounds = Rectangle.Empty; - - int numRows = DataGridRowsLength; - DataGridRow[] localGridRows = DataGridRows; - int numCols = myGridTable.GridColumnStyles.Count - firstVisibleCol; - - for (int row = firstVisibleRow; row < numRows; row++) - { - if (cy > boundingRect.Height) - { - break; - } - - rowBounds = boundingRect; - rowBounds.Height = localGridRows[row].Height; - rowBounds.Y = boundingRect.Y + cy; - - // will add some errors -#if false - if (forDebug == 0 || forDebug == 1) - { - object dRowView = listManager[row]; - DataRow dRow= ((DataRowView) dRowView).Row; - // dRow.RowError = "Error " + forDebug.ToString(); - dRow.SetColumnError(forDebug, "another error " + forDebug.ToString()); - - /* - if (localGridRows[row].DataRow != null) - { - localGridRows[row].DataRow.RowError = "error " + forDebug.ToString(); - localGridRows[row].DataRow.SetColumnError(forDebug, "another error " + forDebug.ToString()); - } - */ - forDebug ++; - } -#endif // false - if (paintRowHeaders) - { - headerBounds = rowBounds; - headerBounds.Width = layout.RowHeaders.Width; - - if (alignRight) - { - headerBounds.X = rowBounds.Right - headerBounds.Width; - } - - if (g.IsVisible(headerBounds)) - { - localGridRows[row].PaintHeader(g, headerBounds, alignRight, gridState[GRIDSTATE_isEditing]); - g.ExcludeClip(headerBounds); - } - - if (!alignRight) - { - rowBounds.X += headerBounds.Width; - } - - rowBounds.Width -= headerBounds.Width; - } - if (g.IsVisible(rowBounds)) - { - dataBounds = rowBounds; - if (!alignRight) - { - dataBounds.X -= negOffset; - } - - dataBounds.Width += negOffset; - - localGridRows[row].Paint(g, dataBounds, rowBounds, firstVisibleCol, numCols, alignRight); - } - cy += rowBounds.Height; - } - boundingRect.Y += cy; - boundingRect.Height -= cy; - } - - /// - /// Gets or sets a value that indicates whether a key should be processed - /// further. - /// - protected override bool ProcessDialogKey(Keys keyData) - { - Debug.WriteLineIf(CompModSwitches.DataGridKeys.TraceVerbose, "DataGridKeys: ProcessDialogKey " + TypeDescriptor.GetConverter(typeof(Keys)).ConvertToString(keyData)); - DataGridRow[] localGridRows = DataGridRows; - if (listManager != null && DataGridRowsLength > 0 && localGridRows[currentRow].OnKeyPress(keyData)) - { - Debug.WriteLineIf(CompModSwitches.DataGridKeys.TraceVerbose, "DataGridKeys: Current Row ate the keystroke"); - return true; - } - - switch (keyData & Keys.KeyCode) - { - case Keys.Tab: - case Keys.Up: - case Keys.Down: - case Keys.Left: - case Keys.Right: - case Keys.Next: - case Keys.Prior: - case Keys.Enter: - case Keys.Escape: - case Keys.Oemplus: - case Keys.Add: - case Keys.OemMinus: - case Keys.Subtract: - case Keys.Space: - case Keys.Delete: - case Keys.A: - KeyEventArgs ke = new KeyEventArgs(keyData); - if (ProcessGridKey(ke)) - { - return true; - } - - break; - - case Keys.C: - if ((keyData & Keys.Control) != 0 && (keyData & Keys.Alt) == 0) - { - // the user pressed Ctrl-C - if (!Bound) - { - break; - } - - // need to distinguish between selecting a set of rows, and - // selecting just one column. - if (numSelectedRows == 0) - { - // copy the data from one column only - if (currentRow < ListManager.Count) - { - GridColumnStylesCollection columns = myGridTable.GridColumnStyles; - if (currentCol >= 0 && currentCol < columns.Count) - { - DataGridColumnStyle column = columns[currentCol]; - string text = column.GetDisplayText(column.GetColumnValueAtRow(ListManager, currentRow)); - - // copy the data to the clipboard - Clipboard.SetDataObject(text); - return true; - } - } - } - else - { - // the user selected a set of rows to copy the data from - - int numRowsOutputted = 0; // the number of rows written to "text" - string text = string.Empty; - - for (int i = 0; i < DataGridRowsLength; ++i) - { - if (localGridRows[i].Selected) - { - GridColumnStylesCollection columns = myGridTable.GridColumnStyles; - int numCols = columns.Count; - for (int j = 0; j < numCols; j++) - { - DataGridColumnStyle column = columns[j]; - text += column.GetDisplayText(column.GetColumnValueAtRow(ListManager, i)); - - // do not put the delimiter at the end of the last column - if (j < numCols - 1) - { - text += GetOutputTextDelimiter(); - } - } - - // put the hard enter "\r\n" only if this is not the last selected row - if (numRowsOutputted < numSelectedRows - 1) - { - text += "\r\n"; - } - - numRowsOutputted++; - } - } - - // copy the data to the clipboard - Clipboard.SetDataObject(text); - return true; - } - - } - break; - } - return base.ProcessDialogKey(keyData); - } - - private void DeleteRows(DataGridRow[] localGridRows) - { - int rowsDeleted = 0; - - int currentRowsCount = listManager == null ? 0 : listManager.Count; - - if (Visible) - { - BeginUpdateInternal(); - } - - try - { - if (ListManager != null) - { - for (int i = 0; i < DataGridRowsLength; i++) - { - if (localGridRows[i].Selected) - { - if (localGridRows[i] is DataGridAddNewRow) - { - Debug.Assert(i == DataGridRowsLength - 1, "the location of addNewRow is " + i.ToString(CultureInfo.InvariantCulture) + " and there are " + DataGridRowsLength.ToString(CultureInfo.InvariantCulture) + " rows "); - localGridRows[i].Selected = false; - } - else - { - ListManager.RemoveAt(i - rowsDeleted); - rowsDeleted++; - } - } - } - } - } - catch - { - // if we got an exception from the back end - // when deleting the rows then we should reset - // our rows and re-throw the exception - // - RecreateDataGridRows(); - gridState[GRIDSTATE_inDeleteRow] = false; - if (Visible) - { - EndUpdateInternal(); - } - - throw; - } - // keep the copy of the old rows in place - // it may be the case that deleting one row could cause multiple rows to be deleted in the same list - // - if (listManager != null && currentRowsCount == listManager.Count + rowsDeleted) - { - DeleteDataGridRows(rowsDeleted); - } - else - { - RecreateDataGridRows(); - } - - gridState[GRIDSTATE_inDeleteRow] = false; - if (Visible) - { - EndUpdateInternal(); - } - - if (listManager != null && currentRowsCount != listManager.Count + rowsDeleted) - { - Invalidate(); - } - } - - // convention: - // if we return -1 it means that the user was going left and there were no visible columns to the left of the current one - // if we return cols.Count + 1 it means that the user was going right and there were no visible columns to the right of the currrent - private int MoveLeftRight(GridColumnStylesCollection cols, int startCol, bool goRight) - { - int i; - if (goRight) - { - for (i = startCol + 1; i < cols.Count; i++) - { - // if (cols[i].Visible && cols[i].PropertyDescriptor != null) - if (cols[i].PropertyDescriptor != null) - { - return i; - } - } - return i; - } - else - { - for (i = startCol - 1; i >= 0; i--) - { - // if (cols[i].Visible && cols[i].PropertyDescriptor != null) - if (cols[i].PropertyDescriptor != null) - { - return i; - } - } - return i; - } - } - - /// - /// Processes keys for grid navigation. - /// - protected bool ProcessGridKey(KeyEventArgs ke) - { - Debug.WriteLineIf(CompModSwitches.DataGridKeys.TraceVerbose, "DataGridKeys: ProcessGridKey " + TypeDescriptor.GetConverter(typeof(Keys)).ConvertToString(ke.KeyCode)); - if (listManager == null || myGridTable == null) - { - return false; - } - - DataGridRow[] localGridRows = DataGridRows; - KeyEventArgs biDiKe = ke; - // check for Bi-Di - // - if (isRightToLeft()) - { - switch (ke.KeyCode) - { - case Keys.Left: - biDiKe = new KeyEventArgs((Keys.Right | ke.Modifiers)); - break; - case Keys.Right: - biDiKe = new KeyEventArgs((Keys.Left | ke.Modifiers)); - break; - default: - break; - } - } - - GridColumnStylesCollection cols = myGridTable.GridColumnStyles; - int firstColumnMarkedVisible = 0; - int lastColumnMarkedVisible = cols.Count; - for (int i = 0; i < cols.Count; i++) - { - if (cols[i].PropertyDescriptor != null) - { - firstColumnMarkedVisible = i; - break; - } - } - - for (int i = cols.Count - 1; i >= 0; i--) - { - if (cols[i].PropertyDescriptor != null) - { - lastColumnMarkedVisible = i; - break; - } - } - - switch (biDiKe.KeyCode) - { - case Keys.Tab: - return ProcessTabKey(biDiKe.KeyData); - case Keys.Up: - gridState[GRIDSTATE_childLinkFocused] = false; - if (dataGridRowsLength == 0) - { - return true; - } - - if (biDiKe.Control && !biDiKe.Alt) - { - if (biDiKe.Shift) - { - DataGridRow[] gridRows = DataGridRows; - - int savedCurrentRow = currentRow; - CurrentRow = 0; - - ResetSelection(); - - for (int i = 0; i <= savedCurrentRow; i++) - { - gridRows[i].Selected = true; - } - - numSelectedRows = savedCurrentRow + 1; - // hide the edit box - // - EndEdit(); - return true; - } - // do not make the parentRowsVisible = false; - // ParentRowsVisible = false; - ResetSelection(); - CurrentRow = 0; - Debug.Assert(ListManager.Position == CurrentCell.RowNumber || listManager.Count == 0, "current row out of ssync with DataSource"); - return true; - } - else if (biDiKe.Shift) - { - DataGridRow[] gridRows = DataGridRows; - // keep a continous selected region - if (gridRows[currentRow].Selected) - { - if (currentRow >= 1) - { - if (gridRows[currentRow - 1].Selected) - { - if (currentRow >= DataGridRowsLength - 1 || !gridRows[currentRow + 1].Selected) - { - numSelectedRows--; - gridRows[currentRow].Selected = false; - } - } - else - { - numSelectedRows += gridRows[currentRow - 1].Selected ? 0 : 1; - gridRows[currentRow - 1].Selected = true; - } - CurrentRow--; - } - } - else - { - numSelectedRows++; - gridRows[currentRow].Selected = true; - if (currentRow >= 1) - { - numSelectedRows += gridRows[currentRow - 1].Selected ? 0 : 1; - gridRows[currentRow - 1].Selected = true; - CurrentRow--; - } - } - - // hide the edit box: - // - EndEdit(); - Debug.Assert(ListManager.Position == CurrentCell.RowNumber || listManager.Count == 0, "current row out of ssync with DataSource"); - return true; - } - else if (biDiKe.Alt) - { - // will need to collapse all child table links - // -1 is for all rows, and false is for collapsing the rows - SetRowExpansionState(-1, false); - Debug.Assert(ListManager.Position == CurrentCell.RowNumber || listManager.Count == 0, "current row out of ssync with DataSource"); - return true; - } - ResetSelection(); - CurrentRow -= 1; - Edit(); - Debug.Assert(ListManager.Position == CurrentCell.RowNumber || listManager.Count == 0, "current row out of ssync with DataSource"); - break; - case Keys.Down: - gridState[GRIDSTATE_childLinkFocused] = false; - if (dataGridRowsLength == 0) - { - return true; - } - - if (biDiKe.Control && !biDiKe.Alt) - { - if (biDiKe.Shift) - { - int savedCurrentRow = currentRow; - CurrentRow = Math.Max(0, DataGridRowsLength - (policy.AllowAdd ? 2 : 1)); - DataGridRow[] gridRows = DataGridRows; - - ResetSelection(); - - for (int i = savedCurrentRow; i <= currentRow; i++) - { - gridRows[i].Selected = true; - } - - numSelectedRows = currentRow - savedCurrentRow + 1; - // hide the edit box - // - EndEdit(); - return true; - } - // do not make the parentRowsVisible = true; - // ParentRowsVisible = true; - ResetSelection(); - CurrentRow = Math.Max(0, DataGridRowsLength - (policy.AllowAdd ? 2 : 1)); - Debug.Assert(ListManager.Position == CurrentCell.RowNumber || listManager.Count == 0, "current row out of ssync with DataSource"); - return true; - } - else if (biDiKe.Shift) - { - DataGridRow[] gridRows = DataGridRows; - - // keep a continous selected region - if (gridRows[currentRow].Selected) - { - - // -1 because we index from 0 - if (currentRow < DataGridRowsLength - (policy.AllowAdd ? 1 : 0) - 1) - { - if (gridRows[currentRow + 1].Selected) - { - if (currentRow == 0 || !gridRows[currentRow - 1].Selected) - { - numSelectedRows--; - gridRows[currentRow].Selected = false; - } - } - else - { - numSelectedRows += gridRows[currentRow + 1].Selected ? 0 : 1; - gridRows[currentRow + 1].Selected = true; - } - - CurrentRow++; - } - } - else - { - numSelectedRows++; - gridRows[currentRow].Selected = true; - // -1 because we index from 0, and -1 so this is not the last row - // so it adds to -2 - if (currentRow < DataGridRowsLength - (policy.AllowAdd ? 1 : 0) - 1) - { - CurrentRow++; - numSelectedRows += gridRows[currentRow].Selected ? 0 : 1; - gridRows[currentRow].Selected = true; - } - } - - // hide the edit box: - // - EndEdit(); - Debug.Assert(ListManager.Position == CurrentCell.RowNumber || listManager.Count == 0, "current row out of ssync with DataSource"); - return true; - } - else if (biDiKe.Alt) - { - // will need to expande all child table links - // -1 is for all rows, and true is for expanding the rows - SetRowExpansionState(-1, true); - return true; - } - ResetSelection(); - Edit(); - CurrentRow += 1; - Debug.Assert(ListManager.Position == CurrentCell.RowNumber || listManager.Count == 0, "current row out of ssync with DataSource"); - break; - case Keys.OemMinus: - case Keys.Subtract: - gridState[GRIDSTATE_childLinkFocused] = false; - if (biDiKe.Control && !biDiKe.Alt) - { - SetRowExpansionState(-1, false); - return true; - } - return false; - case Keys.Oemplus: - case Keys.Add: - gridState[GRIDSTATE_childLinkFocused] = false; - if (biDiKe.Control) - { - SetRowExpansionState(-1, true); - // hide the edit box - // - EndEdit(); - return true; - } - return false; - case Keys.Space: - gridState[GRIDSTATE_childLinkFocused] = false; - if (dataGridRowsLength == 0) - { - return true; - } - - if (biDiKe.Shift) - { - ResetSelection(); - EndEdit(); - DataGridRow[] gridRows = DataGridRows; - gridRows[currentRow].Selected = true; - numSelectedRows = 1; - - return true; - } - return false; - case Keys.Next: - gridState[GRIDSTATE_childLinkFocused] = false; - if (dataGridRowsLength == 0) - { - return true; - } - - if (biDiKe.Shift) - { - int savedCurrentRow = currentRow; - CurrentRow = Math.Min(DataGridRowsLength - (policy.AllowAdd ? 2 : 1), currentRow + numTotallyVisibleRows); - - DataGridRow[] gridRows = DataGridRows; - for (int i = savedCurrentRow; i <= currentRow; i++) - { - if (!gridRows[i].Selected) - { - gridRows[i].Selected = true; - numSelectedRows++; - } - } - // hide edit box - // - EndEdit(); - } - else if (biDiKe.Control && !biDiKe.Alt) - { - // map ctrl-pageDown to show the parentRows - ParentRowsVisible = true; - } - else - { - ResetSelection(); - CurrentRow = Math.Min(DataGridRowsLength - (policy.AllowAdd ? 2 : 1), - CurrentRow + numTotallyVisibleRows); - } - break; - case Keys.Prior: - if (dataGridRowsLength == 0) - { - return true; - } - - gridState[GRIDSTATE_childLinkFocused] = false; - if (biDiKe.Shift) - { - int savedCurrentRow = currentRow; - CurrentRow = Math.Max(0, CurrentRow - numTotallyVisibleRows); - - DataGridRow[] gridRows = DataGridRows; - for (int i = savedCurrentRow; i >= currentRow; i--) - { - if (!gridRows[i].Selected) - { - gridRows[i].Selected = true; - numSelectedRows++; - } - } - - // hide the edit box - // - EndEdit(); - } - else if (biDiKe.Control && !biDiKe.Alt) - { - // map ctrl-pageUp to hide the parentRows - ParentRowsVisible = false; - } - else - { - ResetSelection(); - CurrentRow = Math.Max(0, - CurrentRow - numTotallyVisibleRows); - } - break; - case Keys.Left: - gridState[GRIDSTATE_childLinkFocused] = false; - ResetSelection(); - if ((biDiKe.Modifiers & Keys.Modifiers) == Keys.Alt) - { - if (Caption.BackButtonVisible) - { - NavigateBack(); - } - - return true; - } - - if ((biDiKe.Modifiers & Keys.Control) == Keys.Control) - { - // we should navigate to the first visible column - CurrentColumn = firstColumnMarkedVisible; - break; - } - - if (currentCol == firstColumnMarkedVisible && currentRow != 0) - { - CurrentRow -= 1; - int newCol = MoveLeftRight(myGridTable.GridColumnStyles, myGridTable.GridColumnStyles.Count, false); - Debug.Assert(newCol != -1, "there should be at least a visible column, right?"); - CurrentColumn = newCol; - } - else - { - int newCol = MoveLeftRight(myGridTable.GridColumnStyles, currentCol, false); - if (newCol == -1) - { - if (currentRow == 0) - { - return true; - } - else - { - // go to the previous row: - CurrentRow -= 1; - CurrentColumn = lastColumnMarkedVisible; - } - } - else - { - CurrentColumn = newCol; - } - } - break; - case Keys.Right: - gridState[GRIDSTATE_childLinkFocused] = false; - ResetSelection(); - if ((biDiKe.Modifiers & Keys.Control) == Keys.Control && !biDiKe.Alt) - { - // we should navigate to the last column that is marked as Visible - CurrentColumn = lastColumnMarkedVisible; - break; - } - - if (currentCol == lastColumnMarkedVisible && currentRow != DataGridRowsLength - 1) - { - CurrentRow += 1; - // navigate to the first visible column - CurrentColumn = firstColumnMarkedVisible; - } - else - { - int newCol = MoveLeftRight(myGridTable.GridColumnStyles, currentCol, true); - if (newCol == cols.Count + 1) - { - // navigate to the first visible column - // and the next row - // - CurrentColumn = firstColumnMarkedVisible; - CurrentRow++; - } - else - { - CurrentColumn = newCol; - } - } - break; - case Keys.F2: - gridState[GRIDSTATE_childLinkFocused] = false; - ResetSelection(); - Edit(); - break; -#if DEBUG - case Keys.F12: - gridState[GRIDSTATE_childLinkFocused] = false; - AddNewRow(); - break; -#endif - case Keys.Home: - gridState[GRIDSTATE_childLinkFocused] = false; - if (dataGridRowsLength == 0) - { - return true; - } - - ResetSelection(); - CurrentColumn = 0; - if (biDiKe.Control && !biDiKe.Alt) - { - int currentRowSaved = currentRow; - CurrentRow = 0; - - if (biDiKe.Shift) - { - // Ctrl-Shift-Home will select all the rows up to the first one - DataGridRow[] gridRows = DataGridRows; - for (int i = 0; i <= currentRowSaved; i++) - { - gridRows[i].Selected = true; - numSelectedRows++; - } - // hide the edit box: - EndEdit(); - } - Debug.Assert(ListManager.Position == CurrentCell.RowNumber || listManager.Count == 0, "current row out of ssync with DataSource"); - return true; - } - Debug.Assert(ListManager.Position == CurrentCell.RowNumber || listManager.Count == 0, "current row out of ssync with DataSource"); - break; - case Keys.Delete: - gridState[GRIDSTATE_childLinkFocused] = false; - if (policy.AllowRemove && numSelectedRows > 0) - { -#if DEBUG - // when the list is empty, then the position - // in the listManager is -1, and the currentPosition in the grid is 0 - if (ListManager != null && ListManager.Count > 0) - { - Debug.Assert(ListManager.Position == currentRow, - "Current row out of sync with DataSource", - "The DataSource's Position property should be mirrored by the CurrentCell.RowNumber of the DataGrid."); - } -#endif // DEBUG - - gridState[GRIDSTATE_inDeleteRow] = true; - DeleteRows(localGridRows); - // set the currentRow to the position in the list - currentRow = listManager.Count == 0 ? 0 : listManager.Position; - numSelectedRows = 0; - } - else - { - // if we did not use the the Delete key, let the dataGridTextBox use it - return false; - } - break; - case Keys.End: - gridState[GRIDSTATE_childLinkFocused] = false; - if (dataGridRowsLength == 0) - { - return true; - } - - ResetSelection(); - // go the the last visible column - CurrentColumn = lastColumnMarkedVisible; - - if (biDiKe.Control && !biDiKe.Alt) - { - int savedCurrentRow = currentRow; - CurrentRow = Math.Max(0, DataGridRowsLength - (policy.AllowAdd ? 2 : 1)); - - if (biDiKe.Shift) - { - // Ctrl-Shift-Home will select all the rows up to the first one - DataGridRow[] gridRows = DataGridRows; - for (int i = savedCurrentRow; i <= currentRow; i++) - { - gridRows[i].Selected = true; - } - numSelectedRows = currentRow - savedCurrentRow + 1; - // hide the edit box - // - EndEdit(); - } - Debug.Assert(ListManager.Position == CurrentCell.RowNumber || listManager.Count == 0, "current row out of ssync with DataSource"); - return true; - } - Debug.Assert(ListManager.Position == CurrentCell.RowNumber || listManager.Count == 0, "current row out of ssync with DataSource"); - break; - case Keys.Enter: - gridState[GRIDSTATE_childLinkFocused] = false; - ResetSelection(); - - // yield the return key if there is no editing - if (!gridState[GRIDSTATE_isEditing]) - { - return false; - } - - // Ctrl-Enter will call EndCurrentEdit - if ((biDiKe.Modifiers & Keys.Control) != 0 && !biDiKe.Alt) - { - EndEdit(); - HandleEndCurrentEdit(); - Edit(); // put the edit box on the screen - } - else - { - // Do not commit the edit, cause reseting the - // current cell will do that - // - // CommitEdit(); - - CurrentRow = currentRow + 1; - } - - break; - case Keys.A: - gridState[GRIDSTATE_childLinkFocused] = false; - if (biDiKe.Control && !biDiKe.Alt) - { - DataGridRow[] gridRows = DataGridRows; - for (int i = 0; i < DataGridRowsLength; i++) - { - if (gridRows[i] is DataGridRelationshipRow) - { - gridRows[i].Selected = true; - } - } - - numSelectedRows = DataGridRowsLength - (policy.AllowAdd ? 1 : 0); - // hide the edit box - // - EndEdit(); - return true; - } - return false; - case Keys.Escape: - gridState[GRIDSTATE_childLinkFocused] = false; - ResetSelection(); - if (gridState[GRIDSTATE_isEditing]) - { - // rollback - AbortEdit(); - - // we have to invalidate the row header ( make it display the row selector instead of the pencil ) - if (layout.RowHeadersVisible && currentRow > -1) - { - Rectangle rowHdrRect = GetRowRect(currentRow); - rowHdrRect.Width = layout.RowHeaders.Width; - Invalidate(rowHdrRect); - } - - // now put the edit column back on the screen - Edit(); - } - else - { - // add this protected virtual method for the XML designer team - CancelEditing(); - Edit(); - return false; - } - break; - } - return true; - } - - /// - /// Previews a keyboard message and returns a value indicating if the key was - /// consumed. - /// - protected override bool ProcessKeyPreview(ref Message m) - { - if (m.Msg == WindowMessages.WM_KEYDOWN) - { - KeyEventArgs ke = new KeyEventArgs((Keys)(unchecked((int)(long)m.WParam)) | ModifierKeys); - switch (ke.KeyCode) - { - case Keys.Up: - case Keys.Down: - case Keys.Prior: - case Keys.Next: - case Keys.Right: - case Keys.Left: - case Keys.Tab: - case Keys.Escape: - case Keys.Enter: - case Keys.OemMinus: - case Keys.Subtract: - case Keys.Oemplus: - case Keys.Add: - case Keys.Space: - case Keys.Home: - case Keys.End: - case Keys.F2: - case Keys.Delete: - case Keys.A: - return ProcessGridKey(ke); - } - // Ctrl-Tab will be sent as a tab paired w/ a control on the KeyUp message - // - } - else if (m.Msg == WindowMessages.WM_KEYUP) - { - KeyEventArgs ke = new KeyEventArgs((Keys)(unchecked((int)(long)m.WParam)) | ModifierKeys); - if (ke.KeyCode == Keys.Tab) - { - return ProcessGridKey(ke); - } - } - - return base.ProcessKeyPreview(ref m); - } - - /// - /// Gets a value indicating whether the Tab key should be processed. - /// - protected bool ProcessTabKey(Keys keyData) - { - if (listManager == null || myGridTable == null) - { - return false; - } - - bool wasEditing = false; - int columnCount = myGridTable.GridColumnStyles.Count; - bool biDi = isRightToLeft(); - ResetSelection(); - - // Try to commit changes to cell if we were editing - if (gridState[GRIDSTATE_isEditing]) - { - wasEditing = true; - if (!CommitEdit()) - { - //MessageBox.Show("Could not commit changes! Press Escape to abort edit"); - Edit(); // if we can't commit the value put the edit box so that the user sees where the focus is - return true; - } - } - - if ((keyData & Keys.Control) == Keys.Control) - { - // when the user hits ctrl-alt-tab just ignore it. - if ((keyData & Keys.Alt) == Keys.Alt) - { - return true; - } - - // navigate to the next control in the form - Keys ke = keyData & ~(Keys.Control); - EndEdit(); - - gridState[GRIDSTATE_editControlChanging] = true; - try - { - Focus(); - } - finally - { - gridState[GRIDSTATE_editControlChanging] = false; - } - - return base.ProcessDialogKey(ke); - } - - // see if the child relationships can use this TAB key - DataGridRow[] localRows = DataGridRows; - GridColumnStylesCollection cols = myGridTable.GridColumnStyles; - - int lastColumnMarkedVisible = 0; - int firstColumnMarkedVisible = cols.Count - 1; - // - - if (localRows.Length == 0) - { - EndEdit(); - - return base.ProcessDialogKey(keyData); - } - - for (int i = 0; i < cols.Count; i++) - { - // if (cols[i].Visible && cols[i].PropertyDescriptor != null) { - if (cols[i].PropertyDescriptor != null) - { - firstColumnMarkedVisible = i; - break; - } - } - for (int i = cols.Count - 1; i >= 0; i--) - { - // if (cols[i].Visible && cols[i].PropertyDescriptor != null) { - if (cols[i].PropertyDescriptor != null) - { - lastColumnMarkedVisible = i; - break; - } - } - - if (CurrentColumn == lastColumnMarkedVisible) - { - if (gridState[GRIDSTATE_childLinkFocused] || (!gridState[GRIDSTATE_childLinkFocused] && (keyData & Keys.Shift) != Keys.Shift)) - { - if (localRows[CurrentRow].ProcessTabKey(keyData, layout.RowHeaders, isRightToLeft())) - { - if (cols.Count > 0) - { - cols[CurrentColumn].ConcedeFocus(); - } - - gridState[GRIDSTATE_childLinkFocused] = true; - // let the grid regain focus - // introduced because of that BeginInvoke thing in the OnLeave method.... - if (gridState[GRIDSTATE_canFocus] && CanFocus && !Focused) - { - Focus(); - } - - return true; - } - } - - // actually, it turns out that we should leave the - // control if we are in the last row - if ((currentRow == DataGridRowsLength - 1) && ((keyData & Keys.Shift) == 0)) - { - - EndEdit(); - return base.ProcessDialogKey(keyData); - } - } - - if (CurrentColumn == firstColumnMarkedVisible) - { - // if the childLink is focused, then navigate within the relations - // in the row, otherwise expand the relations list for the row above - if (!gridState[GRIDSTATE_childLinkFocused]) - { - if (CurrentRow != 0 && (keyData & Keys.Shift) == Keys.Shift) - { - if (localRows[CurrentRow - 1].ProcessTabKey(keyData, layout.RowHeaders, isRightToLeft())) - { - CurrentRow--; - if (cols.Count > 0) - { - cols[CurrentColumn].ConcedeFocus(); - } - - gridState[GRIDSTATE_childLinkFocused] = true; - // let the grid regain focus - // introduced because of that BeginInvoke thing in the OnLeave method.... - if (gridState[GRIDSTATE_canFocus] && CanFocus && !Focused) - { - Focus(); - } - - return true; - } - } - } - else - { - if (localRows[CurrentRow].ProcessTabKey(keyData, layout.RowHeaders, isRightToLeft())) - { - return true; - } - else - { - // we were on the firstColumn, previously the link was focused - // we have to navigate to the last column - gridState[GRIDSTATE_childLinkFocused] = false; - CurrentColumn = lastColumnMarkedVisible; - return true; - } - } - - // if we are on the first cell ( not on the addNewRow ) - // then shift - tab should move to the next control on the form - if (currentRow == 0 && ((keyData & Keys.Shift) == Keys.Shift)) - { - EndEdit(); - return base.ProcessDialogKey(keyData); - } - } - - // move - if ((keyData & Keys.Shift) != Keys.Shift) - { - // forward - if (CurrentColumn == lastColumnMarkedVisible) - { - if (CurrentRow != DataGridRowsLength - 1) - { - CurrentColumn = firstColumnMarkedVisible; - } - - CurrentRow += 1; - } - else - { - int nextCol = MoveLeftRight(cols, currentCol, true); // true for going right; - Debug.Assert(nextCol < cols.Count, "we already checked that we are not at the lastColumnMarkedVisible"); - CurrentColumn = nextCol; - } - } - else - { - // backward - if (CurrentColumn == firstColumnMarkedVisible) - { - if (CurrentRow != 0) - { - CurrentColumn = lastColumnMarkedVisible; - } - if (!gridState[GRIDSTATE_childLinkFocused]) // - { - CurrentRow--; - } - } - else if (gridState[GRIDSTATE_childLinkFocused] && CurrentColumn == lastColumnMarkedVisible) - { - // part deux: when we hilite the childLink and then press shift-tab, we - // don't want to navigate at the second to last column - InvalidateRow(currentRow); - Edit(); - } - else - { - int prevCol = MoveLeftRight(cols, currentCol, false); // false for going left - Debug.Assert(prevCol != -1, "we already checked that we are not at the first columnMarked visible"); - CurrentColumn = prevCol; - } - } - - // if we got here, then invalidate childLinkFocused - // - gridState[GRIDSTATE_childLinkFocused] = false; - - // Begin another edit if we were editing before - if (wasEditing) - { - ResetSelection(); - Edit(); - } - return true; - } - - virtual protected void CancelEditing() - { - CancelCursorUpdate(); - // yield the escape key if there is no editing - // make the last row a DataGridAddNewRow - if (gridState[GRIDSTATE_inAddNewRow]) - { - gridState[GRIDSTATE_inAddNewRow] = false; - DataGridRow[] localGridRows = DataGridRows; - - localGridRows[DataGridRowsLength - 1] = new DataGridAddNewRow(this, myGridTable, DataGridRowsLength - 1); - SetDataGridRows(localGridRows, DataGridRowsLength); - } - } - - internal void RecalculateFonts() - { - try - { - linkFont = new Font(Font, FontStyle.Underline); - } - catch - { - } - fontHeight = Font.Height; - linkFontHeight = LinkFont.Height; - captionFontHeight = CaptionFont.Height; - - if (myGridTable == null || myGridTable.IsDefault) - { - headerFontHeight = HeaderFont.Height; - } - else - { - headerFontHeight = myGridTable.HeaderFont.Height; - } - } - - // the BackButtonClicked event: - // - /// - /// Occurs when the BackButton is clicked. - /// - [ - SRCategory(nameof(SR.CatAction)), - SRDescription(nameof(SR.DataGridBackButtonClickDescr)) - ] - public event EventHandler BackButtonClick - { - add => Events.AddHandler(EVENT_BACKBUTTONCLICK, value); - remove => Events.RemoveHandler(EVENT_BACKBUTTONCLICK, value); - } - - // the DownButtonClick event - // - /// - /// Occurs when the Down button is clicked. - /// - [ - SRCategory(nameof(SR.CatAction)), - SRDescription(nameof(SR.DataGridDownButtonClickDescr)) - ] - public event EventHandler ShowParentDetailsButtonClick - { - add => Events.AddHandler(EVENT_DOWNBUTTONCLICK, value); - remove => Events.RemoveHandler(EVENT_DOWNBUTTONCLICK, value); - } - - private void ResetMouseState() - { - oldRow = -1; - gridState[GRIDSTATE_overCaption] = true; - } - - /// - /// Turns off selection for all rows that are selected. - /// - protected void ResetSelection() - { - if (numSelectedRows > 0) - { - DataGridRow[] localGridRows = DataGridRows; - for (int i = 0; i < DataGridRowsLength; ++i) - { - if (localGridRows[i].Selected) - { - localGridRows[i].Selected = false; - } - } - } - numSelectedRows = 0; - lastRowSelected = -1; - } - - private void ResetParentRows() - { - parentRows.Clear(); - originalState = null; - caption.BackButtonActive = caption.DownButtonActive = caption.BackButtonVisible = false; - caption.SetDownButtonDirection(!layout.ParentRowsVisible); - } - - /// - /// Re-initializes all UI related state. - /// - private void ResetUIState() - { - gridState[GRIDSTATE_childLinkFocused] = false; - ResetSelection(); - ResetMouseState(); - PerformLayout(); - Invalidate(); // we want to invalidate after we set up the scrollbars - - // invalidate the horizontalscrollbar and the vertical scrollbar - // - if (horizScrollBar.Visible) - { - horizScrollBar.Invalidate(); - } - - if (vertScrollBar.Visible) - { - vertScrollBar.Invalidate(); - } - } - - /// - /// Scrolls the datagrid down an arbritrary number of rows. - /// - private void ScrollDown(int rows) - { - //Debug.WriteLineIf(CompModSwitches.DataGridScrolling.TraceVerbose, "DataGridScrolling: ScrollDown, rows = " + rows.ToString()); - if (rows != 0) - { - ClearRegionCache(); - - // we should put "dataGridRowsLength -1" - int newFirstRow = Math.Max(0, Math.Min(firstVisibleRow + rows, DataGridRowsLength - 1)); - int oldFirstRow = firstVisibleRow; - firstVisibleRow = newFirstRow; - vertScrollBar.Value = newFirstRow; - bool wasEditing = gridState[GRIDSTATE_isEditing]; - ComputeVisibleRows(); - - if (gridState[GRIDSTATE_isScrolling]) - { - Edit(); - // isScrolling is set to TRUE when the user scrolls. - // once we move the edit box, we finished processing the scroll event, so set isScrolling to FALSE - // to set isScrolling to TRUE, we need another scroll event. - gridState[GRIDSTATE_isScrolling] = false; - } - else - { - EndEdit(); - } - - int deltaY = ComputeRowDelta(oldFirstRow, newFirstRow); - Rectangle rowsRect = layout.Data; - if (layout.RowHeadersVisible) - { - rowsRect = Rectangle.Union(rowsRect, layout.RowHeaders); - } - - RECT scrollArea = rowsRect; - SafeNativeMethods.ScrollWindow(new HandleRef(this, Handle), 0, deltaY, ref scrollArea, ref scrollArea); - OnScroll(EventArgs.Empty); - - if (wasEditing) - { - // invalidate the rowHeader for the - InvalidateRowHeader(currentRow); - } - } - } - - /// - /// Scrolls the datagrid right an arbritrary number of columns. - /// - private void ScrollRight(int columns) - { - Debug.WriteLineIf(CompModSwitches.DataGridScrolling.TraceVerbose, "DataGridScrolling: ScrollRight, columns = " + columns.ToString(CultureInfo.InvariantCulture)); - int newCol = firstVisibleCol + columns; - - GridColumnStylesCollection gridColumns = myGridTable.GridColumnStyles; - int newColOffset = 0; - int nGridCols = gridColumns.Count; - int nVisibleCols = 0; - - // if we try to scroll past the last totally visible column, - // then the toolTips will dissapear - if (myGridTable.IsDefault) - { - nVisibleCols = nGridCols; - } - else - { - for (int i = 0; i < nGridCols; i++) - { - if (gridColumns[i].PropertyDescriptor != null) - { - nVisibleCols++; - } - } - } - - if (lastTotallyVisibleCol == nVisibleCols - 1 && columns > 0 || - firstVisibleCol == 0 && columns < 0 && negOffset == 0) - { - return; - } - - newCol = Math.Min(newCol, nGridCols - 1); - - for (int i = 0; i < newCol; i++) - { - // if (gridColumns[i].Visible && gridColumns[i].PropertyDescriptor != null) - if (gridColumns[i].PropertyDescriptor != null) - { - newColOffset += gridColumns[i].Width; - } - } - - HorizontalOffset = newColOffset; - } - - /// - /// Scrolls a given column into visibility. - /// - private void ScrollToColumn(int targetCol) - { - // do not flush the columns to the left - // so, scroll only as many columns as is necessary. - // - - int dCols = targetCol - firstVisibleCol; - - if (targetCol > lastTotallyVisibleCol && lastTotallyVisibleCol != -1) - { - dCols = targetCol - lastTotallyVisibleCol; - } - - // if only part of the currentCol is visible - // then we should still scroll - if (dCols != 0 || negOffset != 0) - { - ScrollRight(dCols); - } - } - - /// - /// Selects a given row - /// - public void Select(int row) - { - // - Debug.WriteLineIf(CompModSwitches.DataGridSelection.TraceVerbose, "Selecting row " + row.ToString(CultureInfo.InvariantCulture)); - DataGridRow[] localGridRows = DataGridRows; - if (!localGridRows[row].Selected) - { - localGridRows[row].Selected = true; - numSelectedRows++; - } - - // when selecting a row, hide the edit box - // - EndEdit(); - } - - // this function will pair the listManager w/ a table from the TableStylesCollection. - // and for each column in the TableStylesCollection will pair them w/ a propertyDescriptor - // from the listManager - // - // prerequisite: the current table is either the default table, or has the same name as the - // list in the listManager. - // - private void PairTableStylesAndGridColumns(CurrencyManager lm, DataGridTableStyle gridTable, bool forceColumnCreation) - { - PropertyDescriptorCollection props = lm.GetItemProperties(); - GridColumnStylesCollection gridCols = gridTable.GridColumnStyles; - - // ]it is possible to have a dataTable w/ an empty string for a name. - if (!gridTable.IsDefault && string.Compare(lm.GetListName(), gridTable.MappingName, true, CultureInfo.InvariantCulture) == 0) - { - // we will force column creation only at runtime - if (gridTable.GridColumnStyles.Count == 0 && !DesignMode) - { - // we have to create some default columns for each of the propertyDescriptors - // - if (forceColumnCreation) - { - gridTable.SetGridColumnStylesCollection(lm); - } - else - { - gridTable.SetRelationsList(lm); - } - } - else - { - // it may the case that the user will have two lists w/ the same name. - // When switching binding between those different lists, we need to invalidate - // the propertyDescriptors from the current gridColumns - // - for (int i = 0; i < gridCols.Count; i++) - { - gridCols[i].PropertyDescriptor = null; - } - - // pair the propertyDescriptor from each column to the actual property descriptor - // from the listManager - // - for (int i = 0; i < props.Count; i++) - { - DataGridColumnStyle col = gridCols.MapColumnStyleToPropertyName(props[i].Name); - if (col != null) - { - col.PropertyDescriptor = props[i]; - } - } - // TableStyle::SetGridColumnStylesCollection will also set the - // relations list in the tableStyle. - gridTable.SetRelationsList(lm); - } - } - else - { - // we should put an assert, that this is the default Table Style -#if DEBUG - Debug.Assert(gridTable.IsDefault, "if we don't have a match, then the dataGRid should have the default table"); -#endif // DEBUG - gridTable.SetGridColumnStylesCollection(lm); - if (gridTable.GridColumnStyles.Count > 0 && gridTable.GridColumnStyles[0].Width == -1) - { -#if DEBUG - GridColumnStylesCollection cols = gridTable.GridColumnStyles; - for (int i = 0; i < cols.Count; i++) - { - Debug.Assert(cols[i].Width == -1, "if one column's width is not initialized, the same should be happening for the rest of the columns"); - } -#endif // DEBUG - InitializeColumnWidths(); - } - } - } - - /// - /// Sets the current GridTable for the DataGrid. - /// This GridTable is the table which is currently - /// being displayed on the grid. - /// - internal void SetDataGridTable(DataGridTableStyle newTable, bool forceColumnCreation) - { - // we have to listen to the dataGridTable for the propertyChangedEvent - if (myGridTable != null) - { - // unwire the propertyChanged event - UnWireTableStylePropChanged(myGridTable); - - if (myGridTable.IsDefault) - { - // reset the propertyDescriptors on the default table. - myGridTable.GridColumnStyles.ResetPropertyDescriptors(); - - // reset the relationship list from the default table - myGridTable.ResetRelationsList(); - } - } - - myGridTable = newTable; - - WireTableStylePropChanged(myGridTable); - - layout.RowHeadersVisible = newTable.IsDefault ? RowHeadersVisible : newTable.RowHeadersVisible; - - // we need to force the grid into the dataGridTableStyle - // this way the controls in the columns will be parented - // consider this scenario: when the user finished InitializeComponent, it added - // a bunch of tables. all of those tables will have the DataGrid property set to this - // grid. however, in InitializeComponent the tables will not have parented the - // edit controls w/ the grid. - // - // the code in DataGridTextBoxColumn already checks to see if the edits are parented - // before parenting them. - // - if (newTable != null) - { - newTable.DataGrid = this; - } - - // pair the tableStyles and GridColumns - // - if (listManager != null) - { - PairTableStylesAndGridColumns(listManager, myGridTable, forceColumnCreation); - } - - // reset the relations UI on the newTable - if (newTable != null) - { - newTable.ResetRelationsUI(); - } - - // set the isNavigating to false - gridState[GRIDSTATE_isNavigating] = false; - - horizScrollBar.Value = 0; - firstVisibleRow = 0; - currentCol = 0; - // if we add a tableStyle that mapps to the - // current listName, then we should set the currentRow to the - // position in the listManager - if (listManager == null) - { - currentRow = 0; - } - else - { - currentRow = listManager.Position == -1 ? 0 : listManager.Position; - } - - ResetHorizontalOffset(); - negOffset = 0; - ResetUIState(); - - // check the hierarchy - checkHierarchy = true; - } - - /// - /// Scrolls the data area down to make room for the parent rows - /// and lays out the different regions of the DataGrid. - /// - internal void SetParentRowsVisibility(bool visible) - { - Rectangle parentRowsRect = layout.ParentRows; - Rectangle underParentRows = layout.Data; - - if (layout.RowHeadersVisible) - { - underParentRows.X -= isRightToLeft() ? 0 : layout.RowHeaders.Width; - underParentRows.Width += layout.RowHeaders.Width; - } - if (layout.ColumnHeadersVisible) - { - underParentRows.Y -= layout.ColumnHeaders.Height; - underParentRows.Height += layout.ColumnHeaders.Height; - } - - // hide the Edit Box - EndEdit(); - - if (visible) - { - layout.ParentRowsVisible = true; - PerformLayout(); - Invalidate(); - } - else - { - RECT scrollRECT = new Rectangle(underParentRows.X, underParentRows.Y - layout.ParentRows.Height, underParentRows.Width, underParentRows.Height + layout.ParentRows.Height); - - SafeNativeMethods.ScrollWindow(new HandleRef(this, Handle), 0, -parentRowsRect.Height, ref scrollRECT, ref scrollRECT); - - // If the vertical scrollbar was visible before and not after - // the ScrollWindow call, then we will not get invalidated - // completely. We need to translate the visual bounds of - // the scrollbar's old location up and invalidate. - // - if (vertScrollBar.Visible) - { - Rectangle fixupRect = vertScrollBar.Bounds; - fixupRect.Y -= parentRowsRect.Height; - fixupRect.Height += parentRowsRect.Height; - Invalidate(fixupRect); - } - - Debug.WriteLineIf(CompModSwitches.DataGridParents.TraceVerbose, "DataGridParents: Making parent rows invisible."); - layout.ParentRowsVisible = false; - PerformLayout(); - } - } - - /// - /// Sets whether a row is expanded or not. - /// - private void SetRowExpansionState(int row, bool expanded) - { - if (row < -1 || row > DataGridRowsLength - (policy.AllowAdd ? 2 : 1)) - { - throw new ArgumentOutOfRangeException(nameof(row)); - } - - DataGridRow[] localGridRows = DataGridRows; - if (row == -1) - { - DataGridRelationshipRow[] expandableRows = GetExpandableRows(); - bool repositionEditControl = false; - - for (int r = 0; r < expandableRows.Length; ++r) - { - if (expandableRows[r].Expanded != expanded) - { - expandableRows[r].Expanded = expanded; - repositionEditControl = true; - } - } - if (repositionEditControl) - { - // we need to reposition the edit control - if (gridState[GRIDSTATE_isNavigating] || gridState[GRIDSTATE_isEditing]) - { - ResetSelection(); - Edit(); - } - } - } - else if (localGridRows[row] is DataGridRelationshipRow expandableRow) - { - if (expandableRow.Expanded != expanded) - { - // we need to reposition the edit control - if (gridState[GRIDSTATE_isNavigating] || gridState[GRIDSTATE_isEditing]) - { - ResetSelection(); - Edit(); - } - - expandableRow.Expanded = expanded; - } - } - } - - private void ObjectSiteChange(IContainer container, IComponent component, bool site) - { - if (site) - { - if (component.Site == null) - { - container.Add(component); - } - } - else - { - if (component.Site != null && component.Site.Container == container) - { - container.Remove(component); - } - } - } - - public void SubObjectsSiteChange(bool site) - { - DataGrid dgrid = this; - if (dgrid.DesignMode && dgrid.Site != null) - { - IDesignerHost host = (IDesignerHost)dgrid.Site.GetService(typeof(IDesignerHost)); - if (host != null) - { - DesignerTransaction trans = host.CreateTransaction(); - try - { - IContainer container = dgrid.Site.Container; - - DataGridTableStyle[] tables = new DataGridTableStyle[dgrid.TableStyles.Count]; - dgrid.TableStyles.CopyTo(tables, 0); - - for (int i = 0; i < tables.Length; i++) - { - DataGridTableStyle table = tables[i]; - ObjectSiteChange(container, table, site); - - DataGridColumnStyle[] columns = new DataGridColumnStyle[table.GridColumnStyles.Count]; - table.GridColumnStyles.CopyTo(columns, 0); - - for (int j = 0; j < columns.Length; j++) - { - DataGridColumnStyle column = columns[j]; - ObjectSiteChange(container, column, site); - } - } - } - finally - { - trans.Commit(); - } - } - } - } - - /// - /// Unselects a given row - /// - public void UnSelect(int row) - { - // - Debug.WriteLineIf(CompModSwitches.DataGridSelection.TraceVerbose, "DataGridSelection: Unselecting row " + row.ToString(CultureInfo.InvariantCulture)); - DataGridRow[] localGridRows = DataGridRows; - if (localGridRows[row].Selected) - { - localGridRows[row].Selected = false; - numSelectedRows--; - } - } - - /// - /// Asks the cursor to update. - /// - private void UpdateListManager() - { - Debug.WriteLineIf(CompModSwitches.DataGridCursor.TraceVerbose, "DataGridCursor: Requesting EndEdit()"); - try - { - if (listManager != null) - { - EndEdit(); - listManager.EndCurrentEdit(); - } - } - catch - { - } - } - - /// - /// Will return the string that will be used as a delimiter between columns - /// when copying rows contents to the Clipboard. - /// At the moment, return "\t" - /// - protected virtual string GetOutputTextDelimiter() - { - return "\t"; - } - - /// - /// The accessible object class for a DataGrid. The child accessible objects - /// are accessible objects corresponding to the propertygrid entries. - /// - [ComVisible(true)] - internal class DataGridAccessibleObject : ControlAccessibleObject - { - /// - /// Construct a PropertyGridViewAccessibleObject - /// - public DataGridAccessibleObject(DataGrid owner) : base(owner) - { - } - - internal DataGrid DataGrid - { - get - { - return (DataGrid)Owner; - } - } - - private int ColumnCountPrivate - { - get - { - return ((DataGrid)Owner).myGridTable.GridColumnStyles.Count; - } - } - - private int RowCountPrivate - { - get - { - return ((DataGrid)Owner).dataGridRows.Length; - } - } - - public override string Name - { - get - { - // Special case: If an explicit name has been set in the AccessibleName property, use that. - // Note: Any non-null value in AccessibleName overrides the default accessible name logic, - // even an empty string (this is the only way to *force* the accessible name to be blank). - string name = Owner.AccessibleName; - if (name != null) - { - return name; - } - - // Otherwise just return the default label string, minus any mnemonics - return "DataGrid"; - } - - set - { - // If anyone tries to set the accessible name, just cache the value in the control's - // AccessibleName property. This value will then end up overriding the normal accessible - // name logic, until such time as AccessibleName is set back to null. - Owner.AccessibleName = value; - } - } - - public override AccessibleRole Role - { - get - { - AccessibleRole role = Owner.AccessibleRole; - if (role != AccessibleRole.Default) - { - return role; - } - return AccessibleRole.Table; - } - } - public override AccessibleObject GetChild(int index) - { - DataGrid dataGrid = (DataGrid)Owner; - - int cols = ColumnCountPrivate; - int rows = RowCountPrivate; - - if (dataGrid.dataGridRows == null) - { - dataGrid.CreateDataGridRows(); - } - - if (index < 1) - { - return dataGrid.ParentRowsAccessibleObject; - } - else - { - index -= 1; - if (index < cols) - { - return dataGrid.myGridTable.GridColumnStyles[index].HeaderAccessibleObject; - } - else - { - index -= cols; - - if (index < rows) - { - Debug.Assert(dataGrid.dataGridRows[index].RowNumber == index, "Row number is wrong!"); - return dataGrid.dataGridRows[index].AccessibleObject; - } - else - { - index -= rows; - - if (dataGrid.horizScrollBar.Visible) - { - if (index == 0) - { - return dataGrid.horizScrollBar.AccessibilityObject; - } - index--; - } - - if (dataGrid.vertScrollBar.Visible) - { - if (index == 0) - { - return dataGrid.vertScrollBar.AccessibilityObject; - } - index--; - } - - int colCount = dataGrid.myGridTable.GridColumnStyles.Count; - int rowCount = dataGrid.dataGridRows.Length; - int currentRow = index / colCount; - int currentCol = index % colCount; - - if (currentRow < dataGrid.dataGridRows.Length && currentCol < dataGrid.myGridTable.GridColumnStyles.Count) - { - return dataGrid.dataGridRows[currentRow].AccessibleObject.GetChild(currentCol); - } - } - } - } - - return null; - } - - public override int GetChildCount() - { - int n = 1 + ColumnCountPrivate + ((DataGrid)Owner).DataGridRowsLength; - if (DataGrid.horizScrollBar.Visible) - { - n++; - } - if (DataGrid.vertScrollBar.Visible) - { - n++; - } - n += DataGrid.DataGridRows.Length * DataGrid.myGridTable.GridColumnStyles.Count; - return n; - } - - public override AccessibleObject GetFocused() - { - if (DataGrid.Focused) - { - return GetSelected(); - } - - return null; - } - - public override AccessibleObject GetSelected() - { - if (DataGrid.DataGridRows.Length == 0 || DataGrid.myGridTable.GridColumnStyles.Count == 0) - { - return null; - } - - DataGridCell cell = DataGrid.CurrentCell; - return GetChild(1 + ColumnCountPrivate + cell.RowNumber).GetChild(cell.ColumnNumber); - } - - public override AccessibleObject HitTest(int x, int y) - { - Point client = DataGrid.PointToClient(new Point(x, y)); - HitTestInfo hti = DataGrid.HitTest(client.X, client.Y); - - switch (hti.Type) - { - case HitTestType.RowHeader: - return GetChild(1 + ColumnCountPrivate + hti.Row); - case HitTestType.Cell: - return GetChild(1 + ColumnCountPrivate + hti.Row).GetChild(hti.Column); - case HitTestType.ColumnHeader: - return GetChild(1 + hti.Column); - case HitTestType.ParentRows: - return DataGrid.ParentRowsAccessibleObject; - case HitTestType.None: - case HitTestType.ColumnResize: - case HitTestType.RowResize: - case HitTestType.Caption: - break; - } - - return null; - } - - public override AccessibleObject Navigate(AccessibleNavigation navdir) - { - // We're only handling FirstChild and LastChild here - if (GetChildCount() > 0) - { - switch (navdir) - { - case AccessibleNavigation.FirstChild: - return GetChild(0); - case AccessibleNavigation.LastChild: - return GetChild(GetChildCount() - 1); - } - } - - return null; // Perform default behavior - } - } - - // - // This simple data structure holds all of the layout information - // for the DataGrid. - // - internal class LayoutData - { - internal bool dirty = true; - // region inside the Control's borders. - public Rectangle Inside = Rectangle.Empty; - - public Rectangle RowHeaders = Rectangle.Empty; - - public Rectangle TopLeftHeader = Rectangle.Empty; - public Rectangle ColumnHeaders = Rectangle.Empty; - public Rectangle Data = Rectangle.Empty; - - public Rectangle Caption = Rectangle.Empty; - public Rectangle ParentRows = Rectangle.Empty; - - public Rectangle ResizeBoxRect = Rectangle.Empty; - - public bool ColumnHeadersVisible; - public bool RowHeadersVisible; - public bool CaptionVisible; - public bool ParentRowsVisible; - - // used for resizing. - public Rectangle ClientRectangle = Rectangle.Empty; - - public LayoutData() - { - } - - public LayoutData(LayoutData src) - { - GrabLayout(src); - } - - private void GrabLayout(LayoutData src) - { - Inside = src.Inside; - TopLeftHeader = src.TopLeftHeader; - ColumnHeaders = src.ColumnHeaders; - RowHeaders = src.RowHeaders; - Data = src.Data; - Caption = src.Caption; - ParentRows = src.ParentRows; - ResizeBoxRect = src.ResizeBoxRect; - ColumnHeadersVisible = src.ColumnHeadersVisible; - RowHeadersVisible = src.RowHeadersVisible; - CaptionVisible = src.CaptionVisible; - ParentRowsVisible = src.ParentRowsVisible; - ClientRectangle = src.ClientRectangle; - } - - public override string ToString() - { - StringBuilder sb = new StringBuilder(200); - sb.Append(base.ToString()); - sb.Append(" { \n"); - sb.Append("Inside = "); - sb.Append(Inside.ToString()); - sb.Append('\n'); - sb.Append("TopLeftHeader = "); - sb.Append(TopLeftHeader.ToString()); - sb.Append('\n'); - sb.Append("ColumnHeaders = "); - sb.Append(ColumnHeaders.ToString()); - sb.Append('\n'); - sb.Append("RowHeaders = "); - sb.Append(RowHeaders.ToString()); - sb.Append('\n'); - sb.Append("Data = "); - sb.Append(Data.ToString()); - sb.Append('\n'); - sb.Append("Caption = "); - sb.Append(Caption.ToString()); - sb.Append('\n'); - sb.Append("ParentRows = "); - sb.Append(ParentRows.ToString()); - sb.Append('\n'); - sb.Append("ResizeBoxRect = "); - sb.Append(ResizeBoxRect.ToString()); - sb.Append('\n'); - sb.Append("ColumnHeadersVisible = "); - sb.Append(ColumnHeadersVisible.ToString()); - sb.Append('\n'); - sb.Append("RowHeadersVisible = "); - sb.Append(RowHeadersVisible.ToString()); - sb.Append('\n'); - sb.Append("CaptionVisible = "); - sb.Append(CaptionVisible.ToString()); - sb.Append('\n'); - sb.Append("ParentRowsVisible = "); - sb.Append(ParentRowsVisible.ToString()); - sb.Append('\n'); - sb.Append("ClientRectangle = "); - sb.Append(ClientRectangle.ToString()); - sb.Append(" } "); - return sb.ToString(); - } - } - - /// - /// Contains information - /// about the part of the control the user - /// has clicked. This class cannot be inherited. - /// - public sealed class HitTestInfo - { - internal HitTestType type = HitTestType.None; - - internal int row; - internal int col; - - /// - /// Allows the object to inform you the - /// extent of the grid. - /// - public static readonly HitTestInfo Nowhere = new HitTestInfo(); - - internal HitTestInfo() - { - type = (HitTestType)0; - row = col = -1; - } - - internal HitTestInfo(HitTestType type) - { - this.type = type; - row = col = -1; - } - - /// - /// Gets the number of the clicked column. - /// - public int Column - { - get - { - return col; - } - } - - /// - /// Gets the - /// number of the clicked row. - /// - public int Row - { - get - { - return row; - } - } - - /// - /// Gets the part of the control, other than the row or column, that was - /// clicked. - /// - public HitTestType Type - { - get - { - return type; - } - } - - /// - /// Indicates whether two objects are identical. - /// - public override bool Equals(object value) - { - if (value is HitTestInfo ci) - { - return (type == ci.type && - row == ci.row && - col == ci.col); - } - return false; - } - - /// - /// Gets the hash code for the instance. - /// - public override int GetHashCode() => HashCode.Combine(type, row, col); - - /// - /// Gets the type, row number, and column number. - /// - public override string ToString() - { - return "{ " + ((type).ToString()) + "," + row.ToString(CultureInfo.InvariantCulture) + "," + col.ToString(CultureInfo.InvariantCulture) + "}"; - } - } - - /// - /// Specifies the part of the - /// control the user has clicked.< - /// - [Flags] - public enum HitTestType - { - None = 0x00000000, - Cell = 0x00000001, - ColumnHeader = 0x00000002, - RowHeader = 0x00000004, - ColumnResize = 0x00000008, - RowResize = 0x00000010, - Caption = 0x00000020, - ParentRows = 0x00000040 - } - - /// - /// Holds policy information for what the grid can and cannot do. - /// - private class Policy - { - private bool allowAdd = true; - private bool allowEdit = true; - private bool allowRemove = true; - - public Policy() - { - } - - public bool AllowAdd - { - get - { - return allowAdd; - } - set - { - if (allowAdd != value) - { - allowAdd = value; - } - } - } - - public bool AllowEdit - { - get - { - return allowEdit; - } - set - { - if (allowEdit != value) - { - allowEdit = value; - } - } - } - - public bool AllowRemove - { - get - { - return allowRemove; - } - set - { - if (allowRemove != value) - { - allowRemove = value; - } - } - } - - // returns true if the UI needs to be updated (here because addnew has changed) - public bool UpdatePolicy(CurrencyManager listManager, bool gridReadOnly) - { - bool change = false; - // only IBindingList can have an AddNewRow - IBindingList bl = listManager == null ? null : listManager.List as IBindingList; - if (listManager == null) - { - if (!allowAdd) - { - change = true; - } - - allowAdd = allowEdit = allowRemove = true; - } - else - { - if (AllowAdd != listManager.AllowAdd && !gridReadOnly) - { - change = true; - } - - AllowAdd = listManager.AllowAdd && !gridReadOnly && bl != null && bl.SupportsChangeNotification; - AllowEdit = listManager.AllowEdit && !gridReadOnly; - AllowRemove = listManager.AllowRemove && !gridReadOnly && bl != null && bl.SupportsChangeNotification; // - } - return change; - } - } - - // - // Given the x coordinate and the Width of rectangle R1 inside rectangle rect, - // this function returns the x coordinate of the rectangle that - // corresponds to the Bi-Di transformation - // - private int MirrorRectangle(Rectangle R1, Rectangle rect, bool rightToLeft) - { - if (rightToLeft) - { - return rect.Right + rect.X - R1.Right; - } - else - { - return R1.X; - } - } - - // - // Given the x coordinate of a point inside rectangle rect, - // this function returns the x coordinate of the point that - // corresponds to the Bi-Di transformation - // - private int MirrorPoint(int x, Rectangle rect, bool rightToLeft) - { - if (rightToLeft) - { - return rect.Right + rect.X - x; - } - else - { - return x; - } - } - - // This function will return true if the RightToLeft property of the dataGrid is - // set to YES - private bool isRightToLeft() - { - return (RightToLeft == RightToLeft.Yes); - } - } -} - diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridAddNewRow.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridAddNewRow.cs deleted file mode 100644 index 00c9cd19051..00000000000 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridAddNewRow.cs +++ /dev/null @@ -1,126 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Drawing; - -namespace System.Windows.Forms -{ - /// - /// This class fully encapsulates the painting logic for an addnew row - /// appearing in a DataGrid. - /// - internal class DataGridAddNewRow : DataGridRow - { - private bool dataBound = false; - - public DataGridAddNewRow(DataGrid dGrid, DataGridTableStyle gridTable, int rowNum) - : base(dGrid, gridTable, rowNum) - { - } - - // =------------------------------------------------------------------ - // = Methods - // =------------------------------------------------------------------ - - /// - /// Since the DataView does not return a valid DataRow for - /// a newly added row, the DataGrid sets this property to - /// true to signal that the AddNewRow can safely render - /// row contents and permit editing, etc because a DataRecord - /// exists in the cursor that created this row. - /// - public bool DataBound - { - get - { - return dataBound; - } - set - { - dataBound = value; - } - } - - public override void OnEdit() - { - if (!DataBound) - { - DataGrid.AddNewRow(); - } - } - - public override void OnRowLeave() - { - if (DataBound) - { - DataBound = false; - } - } - - // the addNewRow has nothing to do with losing focus - // - internal override void LoseChildFocus(Rectangle rowHeader, bool alignToRight) - { - } - - // the newDataRow has nothing to do with TAB keys - // - internal override bool ProcessTabKey(Keys keyData, Rectangle rowHeaders, bool alignToRight) - { - return false; - } - - /// - /// Paints the row. - /// - public override int Paint(Graphics g, Rectangle bounds, Rectangle trueRowBounds, int firstVisibleColumn, int columnCount) - { - return Paint(g, bounds, trueRowBounds, firstVisibleColumn, columnCount, false); - } - - public override int Paint(Graphics g, - Rectangle bounds, - Rectangle trueRowBounds, - int firstVisibleColumn, - int columnCount, - bool alignToRight) - { - Rectangle dataBounds = bounds; - DataGridLineStyle gridStyle; - if (dgTable.IsDefault) - { - gridStyle = DataGrid.GridLineStyle; - } - else - { - gridStyle = dgTable.GridLineStyle; - } - - int bWidth = DataGrid == null ? 0 : gridStyle == DataGridLineStyle.Solid ? 1 : 0; - dataBounds.Height -= bWidth; - int cx = base.PaintData(g, dataBounds, firstVisibleColumn, columnCount, alignToRight); - - if (bWidth > 0) - { - PaintBottomBorder(g, bounds, cx, bWidth, alignToRight); - } - - return cx; - } - - protected override void PaintCellContents(Graphics g, Rectangle cellBounds, DataGridColumnStyle column, - Brush backBr, Brush foreBrush, bool alignToRight) - { - if (DataBound) - { - CurrencyManager listManager = DataGrid.ListManager; - column.Paint(g, cellBounds, listManager, RowNumber, alignToRight); - } - else - { - base.PaintCellContents(g, cellBounds, column, backBr, foreBrush, alignToRight); - } - } - } -} diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridBoolColumn.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridBoolColumn.cs deleted file mode 100644 index 546335eb109..00000000000 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridBoolColumn.cs +++ /dev/null @@ -1,528 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.ComponentModel; -using System.Drawing; - -namespace System.Windows.Forms -{ - /// - /// Specifies a column in - /// which each cell contains a check box for representing - /// a boolean value. - /// - public class DataGridBoolColumn : DataGridColumnStyle - { - private static readonly int idealCheckSize = 14; - - private bool isEditing = false; - private bool isSelected = false; - private bool allowNull = true; - private int editingRow = -1; - private object currentValue = Convert.DBNull; - - private object trueValue = true; - private object falseValue = false; - private object nullValue = Convert.DBNull; - - private static readonly object EventTrueValue = new object(); - private static readonly object EventFalseValue = new object(); - private static readonly object EventAllowNull = new object(); - - /// - /// Initializes a new instance of the class. - /// - public DataGridBoolColumn() : base() { } - - /// - /// Initializes a new instance of a with the specified . - /// - public DataGridBoolColumn(PropertyDescriptor prop) - : base(prop) { } - - public DataGridBoolColumn(PropertyDescriptor prop, bool isDefault) - : base(prop, isDefault) { } - - /// - /// Gets or sets the actual value used when setting the - /// value of the column to . - /// - [TypeConverter(typeof(StringConverter)), - DefaultValue(true)] - public object TrueValue - { - get - { - return trueValue; - } - set - { - if (!trueValue.Equals(value)) - { - trueValue = value; - OnTrueValueChanged(EventArgs.Empty); - Invalidate(); - } - } - } - - public event EventHandler TrueValueChanged - { - add => Events.AddHandler(EventTrueValue, value); - remove => Events.RemoveHandler(EventTrueValue, value); - } - - /// - /// Gets or sets the actual value used when setting the value of the column to - /// . - /// - [TypeConverter(typeof(StringConverter)), DefaultValue(false)] - public object FalseValue - { - get - { - return falseValue; - } - set - { - if (!falseValue.Equals(value)) - { - falseValue = value; - OnFalseValueChanged(EventArgs.Empty); - Invalidate(); - } - } - } - - public event EventHandler FalseValueChanged - { - add => Events.AddHandler(EventFalseValue, value); - remove => Events.RemoveHandler(EventFalseValue, value); - } - - /// - /// Gets or sets the actual value used when setting the value of the column to - /// . - /// - [TypeConverter(typeof(StringConverter))] - public object NullValue - { - get - { - return nullValue; - } - set - { - if (!nullValue.Equals(value)) - { - nullValue = value; - OnFalseValueChanged(EventArgs.Empty); - Invalidate(); - } - } - } - - // =------------------------------------------------------------------ - // = Methods - // =------------------------------------------------------------------ - - // when the grid is in addNewRow it means that the user did not start typing - // so there is no data to be pushed back into the backEnd. - // make isEditing false so that in the Commit call we do not do any work. - // - protected internal override void ConcedeFocus() - { - base.ConcedeFocus(); - isSelected = false; - isEditing = false; - } - - private Rectangle GetCheckBoxBounds(Rectangle bounds, bool alignToRight) - { - if (alignToRight) - { - return new Rectangle(bounds.X + ((bounds.Width - idealCheckSize) / 2), - bounds.Y + ((bounds.Height - idealCheckSize) / 2), - bounds.Width < idealCheckSize ? bounds.Width : idealCheckSize, - idealCheckSize); - } - else - { - return new Rectangle(Math.Max(0, bounds.X + ((bounds.Width - idealCheckSize) / 2)), - Math.Max(0, bounds.Y + ((bounds.Height - idealCheckSize) / 2)), - bounds.Width < idealCheckSize ? bounds.Width : idealCheckSize, - idealCheckSize); - } - } - - /// - /// Gets the value at the specified row. - /// - protected internal override object GetColumnValueAtRow(CurrencyManager lm, int row) - { - object baseValue = base.GetColumnValueAtRow(lm, row); - object value = Convert.DBNull; - if (baseValue.Equals(trueValue)) - { - value = true; - } - else if (baseValue.Equals(falseValue)) - { - value = false; - } - return value; - } - - private bool IsReadOnly() - { - bool ret = ReadOnly; - if (DataGridTableStyle != null) - { - ret = ret || DataGridTableStyle.ReadOnly; - if (DataGridTableStyle.DataGrid != null) - { - ret = ret || DataGridTableStyle.DataGrid.ReadOnly; - } - } - return ret; - } - - /// - /// Sets the value a a specified row. - /// - protected internal override void SetColumnValueAtRow(CurrencyManager lm, int row, object value) - { - object baseValue = null; - if (true.Equals(value)) - { - baseValue = TrueValue; - } - else if (false.Equals(value)) - { - baseValue = FalseValue; - } - else if (Convert.IsDBNull(value)) - { - baseValue = NullValue; - } - currentValue = baseValue; - base.SetColumnValueAtRow(lm, row, baseValue); - } - - /// - /// Gets the optimum width and height of a cell given - /// a specific value to contain. - /// - protected internal override Size GetPreferredSize(Graphics g, object value) - { - return new Size(idealCheckSize + 2, idealCheckSize + 2); - } - - /// - /// Gets - /// the height of a cell in a column. - /// - protected internal override int GetMinimumHeight() - { - return idealCheckSize + 2; - } - - /// - /// Gets the height used when resizing columns. - /// - protected internal override int GetPreferredHeight(Graphics g, object value) - { - return idealCheckSize + 2; - } - - /// - /// Initiates a request to interrupt an edit procedure. - /// - protected internal override void Abort(int rowNum) - { - isSelected = false; - isEditing = false; - Invalidate(); - return; - } - - /// - /// Initiates a request to complete an editing procedure. - /// - protected internal override bool Commit(CurrencyManager dataSource, int rowNum) - { - isSelected = false; - // always invalidate - Invalidate(); - if (!isEditing) - { - return true; - } - - SetColumnValueAtRow(dataSource, rowNum, currentValue); - isEditing = false; - return true; - } - - /// - /// Prepares the cell for editing a value. - /// - protected internal override void Edit(CurrencyManager source, - int rowNum, - Rectangle bounds, - bool readOnly, - string displayText, - bool cellIsVisible) - { - // toggle state right now... - isSelected = true; - - // move the focus away from the previous column and give it to the grid - // - DataGrid grid = DataGridTableStyle.DataGrid; - if (!grid.Focused) - { - grid.Focus(); - } - - if (!readOnly && !IsReadOnly()) - { - editingRow = rowNum; - currentValue = GetColumnValueAtRow(source, rowNum); - } - - base.Invalidate(); - } - - /// - /// Provides a handler for determining which key was pressed, and whether to - /// process it. - /// - internal override bool KeyPress(int rowNum, Keys keyData) - { - if (isSelected && editingRow == rowNum && !IsReadOnly()) - { - if ((keyData & Keys.KeyCode) == Keys.Space) - { - ToggleValue(); - Invalidate(); - return true; - } - } - return base.KeyPress(rowNum, keyData); - } - - /// - /// Indicates whether the a mouse down event occurred at the specified row, at - /// the specified x and y coordinates. - /// - internal override bool MouseDown(int rowNum, int x, int y) - { - base.MouseDown(rowNum, x, y); - if (isSelected && editingRow == rowNum && !IsReadOnly()) - { - ToggleValue(); - Invalidate(); - return true; - } - return false; - } - - private void OnTrueValueChanged(EventArgs e) - { - if (Events[EventTrueValue] is EventHandler eh) - { - eh(this, e); - } - } - private void OnFalseValueChanged(EventArgs e) - { - if (Events[EventFalseValue] is EventHandler eh) - { - eh(this, e); - } - } - private void OnAllowNullChanged(EventArgs e) - { - if (Events[EventAllowNull] is EventHandler eh) - { - eh(this, e); - } - } - - /// - /// Draws the - /// with the given , - /// and row number. - /// - protected internal override void Paint(Graphics g, Rectangle bounds, CurrencyManager source, int rowNum) - { - Paint(g, bounds, source, rowNum, false); - } - - /// - /// Draws the - /// with the given , , - /// row number, and alignment settings. - /// - protected internal override void Paint(Graphics g, Rectangle bounds, CurrencyManager source, int rowNum, bool alignToRight) - { - Paint(g, bounds, source, rowNum, DataGridTableStyle.BackBrush, DataGridTableStyle.ForeBrush, alignToRight); - } - - /// - /// Draws the with the given , , - /// row number, , and . - /// - protected internal override void Paint(Graphics g, Rectangle bounds, CurrencyManager source, int rowNum, - Brush backBrush, Brush foreBrush, - bool alignToRight) - { - object value = (isEditing && editingRow == rowNum) ? currentValue : GetColumnValueAtRow(source, rowNum); - ButtonState checkedState = ButtonState.Inactive; - if (!Convert.IsDBNull(value)) - { - checkedState = ((bool)value ? ButtonState.Checked : ButtonState.Normal); - } - - Rectangle box = GetCheckBoxBounds(bounds, alignToRight); - - Region r = g.Clip; - g.ExcludeClip(box); - - Brush selectionBrush = DataGridTableStyle.IsDefault ? DataGridTableStyle.DataGrid.SelectionBackBrush : DataGridTableStyle.SelectionBackBrush; - if (isSelected && editingRow == rowNum && !IsReadOnly()) - { - g.FillRectangle(selectionBrush, bounds); - } - else - { - g.FillRectangle(backBrush, bounds); - } - - g.Clip = r; - - if (checkedState == ButtonState.Inactive) - { - ControlPaint.DrawMixedCheckBox(g, box, ButtonState.Checked); - } - else - { - ControlPaint.DrawCheckBox(g, box, checkedState); - } - - // if the column is read only we should still show selection - if (IsReadOnly() && isSelected && source.Position == rowNum) - { - bounds.Inflate(-1, -1); - Pen pen = new Pen(selectionBrush) - { - DashStyle = System.Drawing.Drawing2D.DashStyle.Dash - }; - g.DrawRectangle(pen, bounds); - pen.Dispose(); - // restore the bounds rectangle - bounds.Inflate(1, 1); - } - } - - /// - /// Gets or sets a value indicating whether null values are allowed. - /// - [ - SRCategory(nameof(SR.CatBehavior)), - DefaultValue(true), - SRDescription(nameof(SR.DataGridBoolColumnAllowNullValue)) - ] - public bool AllowNull - { - get - { - return allowNull; - } - set - { - if (allowNull != value) - { - allowNull = value; - // if we do not allow null, and the gridColumn had - // a null in it, discard it - if (!value && Convert.IsDBNull(currentValue)) - { - currentValue = false; - Invalidate(); - } - OnAllowNullChanged(EventArgs.Empty); - } - } - } - - public event EventHandler AllowNullChanged - { - add => Events.AddHandler(EventAllowNull, value); - remove => Events.RemoveHandler(EventAllowNull, value); - } - - /// - /// Enters a into the column. - /// - protected internal override void EnterNullValue() - { - // do not throw an exception when the column is marked as readOnly or - // does not allowNull - if (!AllowNull || IsReadOnly()) - { - return; - } - - if (currentValue != Convert.DBNull) - { - currentValue = Convert.DBNull; - Invalidate(); - } - } - - private void ResetNullValue() - { - NullValue = Convert.DBNull; - } - - private bool ShouldSerializeNullValue() - { - return nullValue != Convert.DBNull; - } - - private void ToggleValue() - { - if (currentValue is bool && ((bool)currentValue) == false) - { - currentValue = true; - } - else - { - if (AllowNull) - { - if (Convert.IsDBNull(currentValue)) - { - currentValue = false; - } - else - { - currentValue = Convert.DBNull; - } - } - else - { - currentValue = false; - } - } - // we started editing - isEditing = true; - // tell the dataGrid that things are changing - // we put Rectangle.Empty cause toggle will invalidate the row anyhow - DataGridTableStyle.DataGrid.ColumnStartedEditing(Rectangle.Empty); - } - } -} diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridCaption.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridCaption.cs deleted file mode 100644 index 6d53f7492c5..00000000000 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridCaption.cs +++ /dev/null @@ -1,909 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.ComponentModel; -using System.Diagnostics; -using System.Drawing; -using System.Drawing.Imaging; -using System.Globalization; - -namespace System.Windows.Forms -{ - /// - /// Represents a caption in the DataGrid control. - /// - internal class DataGridCaption - { - internal EventHandlerList events; - - private const int xOffset = 3; - private const int yOffset = 1; - private const int textPadding = 2; - private const int buttonToText = 4; - private static readonly ColorMap[] colorMap = new ColorMap[] { new ColorMap() }; - - private static readonly Point minimumBounds = new Point(50, 30); - - private readonly DataGrid dataGrid = null; - private bool backButtonVisible = false; - private bool downButtonVisible = false; - - private SolidBrush backBrush = DefaultBackBrush; - private SolidBrush foreBrush = DefaultForeBrush; - private readonly Pen textBorderPen = DefaultTextBorderPen; - - private string text = string.Empty; - private bool textBorderVisible = false; - private Font textFont = null; - - // use the datagridFont when the textFont is not set - // we cache this font ( cause we have to make it bold every time we paint the caption ) - // - private Font dataGridFont = null; - - private bool backActive = false; - private bool downActive = false; - private bool backPressed = false; - private bool downPressed = false; - - // if the downButton should point down or not - private bool downButtonDown = false; - - private static Bitmap leftButtonBitmap; - private static Bitmap leftButtonBitmap_bidi; - private static Bitmap magnifyingGlassBitmap; - - private Rectangle backButtonRect = new Rectangle(); - private Rectangle downButtonRect = new Rectangle(); - private Rectangle textRect = new Rectangle(); - - private CaptionLocation lastMouseLocation = CaptionLocation.Nowhere; - - private EventEntry eventList; - private static readonly object EVENT_BACKWARDCLICKED = new object(); - private static readonly object EVENT_DOWNCLICKED = new object(); - private static readonly object EVENT_CAPTIONCLICKED = new object(); - - internal DataGridCaption(DataGrid dataGrid) - { - this.dataGrid = dataGrid; - downButtonVisible = dataGrid.ParentRowsVisible; - colorMap[0].OldColor = Color.White; - colorMap[0].NewColor = ForeColor; - OnGridFontChanged(); - } - - internal void OnGridFontChanged() - { - if (dataGridFont == null || !dataGridFont.Equals(dataGrid.Font)) - { - try - { - dataGridFont = new Font(dataGrid.Font, FontStyle.Bold); - } - catch - { - } - } - } - - // =------------------------------------------------------------------ - // = Properties - // =------------------------------------------------------------------ - - internal bool BackButtonActive - { - get - { - return backActive; - } - set - { - if (backActive != value) - { - backActive = value; - InvalidateCaptionRect(backButtonRect); - } - } - } - - internal bool DownButtonActive - { - get - { - return downActive; - } - set - { - if (downActive != value) - { - downActive = value; - InvalidateCaptionRect(downButtonRect); - } - } - } - - internal static SolidBrush DefaultBackBrush - { - get - { - return (SolidBrush)SystemBrushes.ActiveCaption; - } - } - - internal static Pen DefaultTextBorderPen - { - get - { - return new Pen(SystemColors.ActiveCaptionText); - } - } - - internal static SolidBrush DefaultForeBrush - { - get - { - return (SolidBrush)SystemBrushes.ActiveCaptionText; - } - } - - internal Color BackColor - { - get - { - return backBrush.Color; - } - set - { - if (!backBrush.Color.Equals(value)) - { - if (value.IsEmpty) - { - throw new ArgumentException(string.Format(SR.DataGridEmptyColor, "Caption BackColor")); - } - - backBrush = new SolidBrush(value); - Invalidate(); - } - } - } - - internal EventHandlerList Events - { - get - { - if (events == null) - { - events = new EventHandlerList(); - } - return events; - } - } - - internal Font Font - { - get - { - // use the dataGridFont only if the user - // did not set the CaptionFont - // - if (textFont == null) - { - return dataGridFont; - } - else - { - return textFont; - } - } - set - { - if (textFont == null || !textFont.Equals(value)) - { - textFont = value; - // this property gets called in the constructor before dataGrid has a caption - // and we don't need this special-handling then... - if (dataGrid.Caption != null) - { - dataGrid.RecalculateFonts(); - dataGrid.PerformLayout(); - dataGrid.Invalidate(); // smaller invalidate rect? - } - } - } - } - - internal bool ShouldSerializeFont() - { - return textFont != null && !textFont.Equals(dataGridFont); - } - - internal bool ShouldSerializeBackColor() - { - return !backBrush.Equals(DefaultBackBrush); - } - - internal void ResetBackColor() - { - if (ShouldSerializeBackColor()) - { - backBrush = DefaultBackBrush; - Invalidate(); - } - } - - internal void ResetForeColor() - { - if (ShouldSerializeForeColor()) - { - foreBrush = DefaultForeBrush; - Invalidate(); - } - } - - internal bool ShouldSerializeForeColor() - { - return !foreBrush.Equals(DefaultForeBrush); - } - - internal void ResetFont() - { - textFont = null; - Invalidate(); - } - - internal string Text - { - get - { - return text; - } - set - { - if (value == null) - { - text = string.Empty; - } - else - { - text = value; - } - - Invalidate(); - } - } - - internal bool TextBorderVisible - { - get - { - return textBorderVisible; - } - set - { - textBorderVisible = value; - Invalidate(); - } - } - - internal Color ForeColor - { - get - { - return foreBrush.Color; - } - set - { - if (value.IsEmpty) - { - throw new ArgumentException(string.Format(SR.DataGridEmptyColor, "Caption ForeColor")); - } - - foreBrush = new SolidBrush(value); - colorMap[0].NewColor = ForeColor; - Invalidate(); - } - } - - internal Point MinimumBounds - { - get - { - return minimumBounds; - } - } - - internal bool BackButtonVisible - { - get - { - return backButtonVisible; - } - set - { - if (backButtonVisible != value) - { - backButtonVisible = value; - Invalidate(); - } - } - } - - internal bool DownButtonVisible - { - get - { - return downButtonVisible; - } - set - { - if (downButtonVisible != value) - { - downButtonVisible = value; - Invalidate(); - } - } - } - - // =------------------------------------------------------------------ - // = Methods - // =------------------------------------------------------------------ - - protected virtual void AddEventHandler(object key, Delegate handler) - { - // Locking 'this' here is ok since this is an internal class. - lock (this) - { - if (handler == null) - { - return; - } - - for (EventEntry e = eventList; e != null; e = e.next) - { - if (e.key == key) - { - e.handler = Delegate.Combine(e.handler, handler); - return; - } - } - eventList = new EventEntry(eventList, key, handler); - } - } - - /// - /// Adds a listener for the BackwardClicked event. - /// - internal event EventHandler BackwardClicked - { - add => Events.AddHandler(EVENT_BACKWARDCLICKED, value); - remove => Events.RemoveHandler(EVENT_BACKWARDCLICKED, value); - } - - /// - /// Adds a listener for the CaptionClicked event. - /// - internal event EventHandler CaptionClicked - { - add => Events.AddHandler(EVENT_CAPTIONCLICKED, value); - remove => Events.RemoveHandler(EVENT_CAPTIONCLICKED, value); - } - - internal event EventHandler DownClicked - { - add => Events.AddHandler(EVENT_DOWNCLICKED, value); - remove => Events.RemoveHandler(EVENT_DOWNCLICKED, value); - } - - private void Invalidate() - { - if (dataGrid != null) - { - dataGrid.InvalidateCaption(); - } - } - - private void InvalidateCaptionRect(Rectangle r) - { - if (dataGrid != null) - { - dataGrid.InvalidateCaptionRect(r); - } - } - - private void InvalidateLocation(CaptionLocation loc) - { - Rectangle r; - switch (loc) - { - case CaptionLocation.BackButton: - r = backButtonRect; - r.Inflate(1, 1); - InvalidateCaptionRect(r); - break; - case CaptionLocation.DownButton: - r = downButtonRect; - r.Inflate(1, 1); - InvalidateCaptionRect(r); - break; - } - } - - protected void OnBackwardClicked(EventArgs e) - { - if (backActive) - { - ((EventHandler)Events[EVENT_BACKWARDCLICKED])?.Invoke(this, e); - } - } - - protected void OnCaptionClicked(EventArgs e) - { - ((EventHandler)Events[EVENT_CAPTIONCLICKED])?.Invoke(this, e); - } - - protected void OnDownClicked(EventArgs e) - { - if (downActive && downButtonVisible) - { - ((EventHandler)Events[EVENT_DOWNCLICKED])?.Invoke(this, e); - } - } - - private Bitmap GetBitmap(string bitmapName) - { - try - { - return DpiHelper.GetBitmapFromIcon(typeof(DataGridCaption), bitmapName); - } - catch (Exception e) - { - Debug.Fail("Failed to load bitmap: " + bitmapName, e.ToString()); - return null; - } - } - - private Bitmap GetBackButtonBmp(bool alignRight) - { - if (alignRight) - { - if (leftButtonBitmap_bidi == null) - { - leftButtonBitmap_bidi = GetBitmap("DataGridCaption.backarrow_bidi"); - } - - return leftButtonBitmap_bidi; - } - else - { - if (leftButtonBitmap == null) - { - leftButtonBitmap = GetBitmap("DataGridCaption.backarrow"); - } - - return leftButtonBitmap; - } - } - - private Bitmap GetDetailsBmp() - { - if (magnifyingGlassBitmap == null) - { - magnifyingGlassBitmap = GetBitmap("DataGridCaption.Details"); - } - - return magnifyingGlassBitmap; - } - - protected virtual Delegate GetEventHandler(object key) - { - // Locking 'this' here is ok since this is an internal class. - lock (this) - { - for (EventEntry e = eventList; e != null; e = e.next) - { - if (e.key == key) - { - return e.handler; - } - } - return null; - } - } - - internal Rectangle GetBackButtonRect(Rectangle bounds, bool alignRight, int downButtonWidth) - { - Bitmap backButtonBmp = GetBackButtonBmp(false); - Size backButtonSize; - lock (backButtonBmp) - { - backButtonSize = backButtonBmp.Size; - } - return new Rectangle(bounds.Right - xOffset * 4 - downButtonWidth - backButtonSize.Width, - bounds.Y + yOffset + textPadding, - backButtonSize.Width, - backButtonSize.Height); - } - - internal int GetDetailsButtonWidth() - { - int width = 0; - Bitmap detailsBmp = GetDetailsBmp(); - lock (detailsBmp) - { - width = detailsBmp.Size.Width; - } - return width; - } - - internal Rectangle GetDetailsButtonRect(Rectangle bounds, bool alignRight) - { - Size downButtonSize; - Bitmap detailsBmp = GetDetailsBmp(); - lock (detailsBmp) - { - downButtonSize = detailsBmp.Size; - } - int downButtonWidth = downButtonSize.Width; - return new Rectangle(bounds.Right - xOffset * 2 - downButtonWidth, - bounds.Y + yOffset + textPadding, - downButtonWidth, - downButtonSize.Height); - } - - /// - /// Called by the dataGrid when it needs the caption - /// to repaint. - /// - internal void Paint(Graphics g, Rectangle bounds, bool alignRight) - { - Size textSize = new Size((int)g.MeasureString(text, Font).Width + 2, Font.Height + 2); - - downButtonRect = GetDetailsButtonRect(bounds, alignRight); - int downButtonWidth = GetDetailsButtonWidth(); - backButtonRect = GetBackButtonRect(bounds, alignRight, downButtonWidth); - - int backButtonArea = backButtonVisible ? backButtonRect.Width + xOffset + buttonToText : 0; - int downButtonArea = downButtonVisible && !dataGrid.ParentRowsIsEmpty() ? downButtonWidth + xOffset + buttonToText : 0; - - int textWidthLeft = bounds.Width - xOffset - backButtonArea - downButtonArea; - - textRect = new Rectangle( - bounds.X, - bounds.Y + yOffset, - Math.Min(textWidthLeft, 2 * textPadding + textSize.Width), - 2 * textPadding + textSize.Height); - - // align the caption text box, downButton, and backButton - // if the RigthToLeft property is set to true - if (alignRight) - { - textRect.X = bounds.Right - textRect.Width; - backButtonRect.X = bounds.X + xOffset * 4 + downButtonWidth; - downButtonRect.X = bounds.X + xOffset * 2; - } - - Debug.WriteLineIf(CompModSwitches.DGCaptionPaint.TraceVerbose, "text size = " + textSize.ToString()); - Debug.WriteLineIf(CompModSwitches.DGCaptionPaint.TraceVerbose, "downButtonWidth = " + downButtonWidth.ToString(CultureInfo.InvariantCulture)); - Debug.WriteLineIf(CompModSwitches.DGCaptionPaint.TraceVerbose, "textWidthLeft = " + textWidthLeft.ToString(CultureInfo.InvariantCulture)); - Debug.WriteLineIf(CompModSwitches.DGCaptionPaint.TraceVerbose, "backButtonRect " + backButtonRect.ToString()); - Debug.WriteLineIf(CompModSwitches.DGCaptionPaint.TraceVerbose, "textRect " + textRect.ToString()); - Debug.WriteLineIf(CompModSwitches.DGCaptionPaint.TraceVerbose, "downButtonRect " + downButtonRect.ToString()); - - // we should use the code that is commented out - // with today's code, there are pixels on the backButtonRect and the downButtonRect - // that are getting painted twice - // - g.FillRectangle(backBrush, bounds); - - if (backButtonVisible) - { - PaintBackButton(g, backButtonRect, alignRight); - if (backActive) - { - if (lastMouseLocation == CaptionLocation.BackButton) - { - backButtonRect.Inflate(1, 1); - ControlPaint.DrawBorder3D(g, backButtonRect, - backPressed ? Border3DStyle.SunkenInner : Border3DStyle.RaisedInner); - } - } - } - PaintText(g, textRect, alignRight); - - if (downButtonVisible && !dataGrid.ParentRowsIsEmpty()) - { - PaintDownButton(g, downButtonRect); - // the rules have changed, yet again. - // now: if we show the parent rows and the mouse is - // not on top of this icon, then let the icon be depressed. - // if the mouse is pressed over the icon, then show the icon pressed - // if the mouse is over the icon and not pressed, then show the icon SunkenInner; - // - if (lastMouseLocation == CaptionLocation.DownButton) - { - downButtonRect.Inflate(1, 1); - ControlPaint.DrawBorder3D(g, downButtonRect, - downPressed ? Border3DStyle.SunkenInner : Border3DStyle.RaisedInner); - } - } - } - - private void PaintIcon(Graphics g, Rectangle bounds, Bitmap b) - { - ImageAttributes attr = new ImageAttributes(); - attr.SetRemapTable(colorMap, ColorAdjustType.Bitmap); - g.DrawImage(b, bounds, 0, 0, bounds.Width, bounds.Height, GraphicsUnit.Pixel, attr); - attr.Dispose(); - } - - private void PaintBackButton(Graphics g, Rectangle bounds, bool alignRight) - { - Bitmap backButtonBmp = GetBackButtonBmp(alignRight); - lock (backButtonBmp) - { - PaintIcon(g, bounds, backButtonBmp); - } - } - - private void PaintDownButton(Graphics g, Rectangle bounds) - { - Bitmap detailsBmp = GetDetailsBmp(); - lock (detailsBmp) - { - PaintIcon(g, bounds, detailsBmp); - } - } - - private void PaintText(Graphics g, Rectangle bounds, bool alignToRight) - { - Rectangle textBounds = bounds; - - if (textBounds.Width <= 0 || textBounds.Height <= 0) - { - return; - } - - if (textBorderVisible) - { - g.DrawRectangle(textBorderPen, textBounds.X, textBounds.Y, textBounds.Width - 1, textBounds.Height - 1); - textBounds.Inflate(-1, -1); - } - - if (textPadding > 0) - { - Rectangle border = textBounds; - border.Height = textPadding; - g.FillRectangle(backBrush, border); - - border.Y = textBounds.Bottom - textPadding; - g.FillRectangle(backBrush, border); - - border = new Rectangle(textBounds.X, textBounds.Y + textPadding, - textPadding, textBounds.Height - 2 * textPadding); - g.FillRectangle(backBrush, border); - - border.X = textBounds.Right - textPadding; - g.FillRectangle(backBrush, border); - textBounds.Inflate(-textPadding, -textPadding); - } - - g.FillRectangle(backBrush, textBounds); - - // Brush foreBrush = new SolidBrush(dataGrid.CaptionForeColor); - StringFormat format = new StringFormat(); - if (alignToRight) - { - format.FormatFlags |= StringFormatFlags.DirectionRightToLeft; - format.Alignment = StringAlignment.Far; - } - g.DrawString(text, Font, foreBrush, textBounds, format); - format.Dispose(); - // foreBrush.Dispose(); - } - - private CaptionLocation FindLocation(int x, int y) - { - if (!backButtonRect.IsEmpty) - { - if (backButtonRect.Contains(x, y)) - { - return CaptionLocation.BackButton; - } - } - if (!downButtonRect.IsEmpty) - { - if (downButtonRect.Contains(x, y)) - { - return CaptionLocation.DownButton; - } - } - if (!textRect.IsEmpty) - { - if (textRect.Contains(x, y)) - { - return CaptionLocation.Text; - } - } - return CaptionLocation.Nowhere; - } - - private bool DownButtonDown - { - get - { - return downButtonDown; - } - set - { - if (downButtonDown != value) - { - downButtonDown = value; - InvalidateLocation(CaptionLocation.DownButton); - } - } - } - - internal bool GetDownButtonDirection() - { - return DownButtonDown; - } - - /// - /// Called by the dataGrid when the mouse is pressed - /// inside the caption. - /// - internal void MouseDown(int x, int y) - { - CaptionLocation loc = FindLocation(x, y); - switch (loc) - { - case CaptionLocation.BackButton: - backPressed = true; - InvalidateLocation(loc); - break; - case CaptionLocation.DownButton: - downPressed = true; - InvalidateLocation(loc); - break; - case CaptionLocation.Text: - OnCaptionClicked(EventArgs.Empty); - break; - } - } - - /// - /// Called by the dataGrid when the mouse is released - /// inside the caption. - /// - internal void MouseUp(int x, int y) - { - CaptionLocation loc = FindLocation(x, y); - switch (loc) - { - case CaptionLocation.DownButton: - if (downPressed == true) - { - downPressed = false; - OnDownClicked(EventArgs.Empty); - } - break; - case CaptionLocation.BackButton: - if (backPressed == true) - { - backPressed = false; - OnBackwardClicked(EventArgs.Empty); - } - break; - } - } - - /// - /// Called by the dataGrid when the mouse leaves - /// the caption area. - /// - internal void MouseLeft() - { - CaptionLocation oldLoc = lastMouseLocation; - lastMouseLocation = CaptionLocation.Nowhere; - InvalidateLocation(oldLoc); - } - - /// - /// Called by the dataGrid when the mouse is - /// inside the caption. - /// - internal void MouseOver(int x, int y) - { - CaptionLocation newLoc = FindLocation(x, y); - - InvalidateLocation(lastMouseLocation); - InvalidateLocation(newLoc); - lastMouseLocation = newLoc; - } - - protected virtual void RaiseEvent(object key, EventArgs e) - { - Delegate handler = GetEventHandler(key); - if (handler != null) - { - ((EventHandler)handler)(this, e); - } - } - - protected virtual void RemoveEventHandler(object key, Delegate handler) - { - // Locking 'this' here is ok since this is an internal class. - lock (this) - { - if (handler == null) - { - return; - } - - for (EventEntry e = eventList, prev = null; e != null; prev = e, e = e.next) - { - if (e.key == key) - { - e.handler = Delegate.Remove(e.handler, handler); - if (e.handler == null) - { - if (prev == null) - { - eventList = e.next; - } - else - { - prev.next = e.next; - } - } - return; - } - } - } - } - - protected virtual void RemoveEventHandlers() - { - eventList = null; - } - - internal void SetDownButtonDirection(bool pointDown) - { - DownButtonDown = pointDown; - } - - /// - /// Toggles the direction the "Down Button" is pointing. - /// - internal bool ToggleDownButtonDirection() - { - DownButtonDown = !DownButtonDown; - return DownButtonDown; - } - internal enum CaptionLocation - { - Nowhere, - BackButton, - DownButton, - Text - } - - private sealed class EventEntry - { - internal EventEntry next; - internal object key; - internal Delegate handler; - - internal EventEntry(EventEntry next, object key, Delegate handler) - { - this.next = next; - this.key = key; - this.handler = handler; - } - } - - } -} - diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridCell.cs deleted file mode 100644 index 448f34fd09a..00000000000 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridCell.cs +++ /dev/null @@ -1,58 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System.Windows.Forms -{ - /// - /// Identifies a cell in the grid. - /// - public struct DataGridCell - { - /// - /// Gets or sets the number of a column in the control. - /// - public int ColumnNumber { get; set; } - - /// - /// Gets or sets the number of a row in the control. - /// - public int RowNumber { get; set; } - - /// - /// Initializes a new instance of the class. - /// - public DataGridCell(int r, int c) - { - RowNumber = r; - ColumnNumber = c; - } - - /// - /// Gets a value indicating whether the is - /// identical to a second . - /// - public override bool Equals(object o) - { - if (!(o is DataGridCell rhs)) - { - return false; - } - - return rhs.RowNumber == RowNumber && rhs.ColumnNumber == ColumnNumber; - } - - /// - /// Gets a hash value that uniquely identifies the cell. - /// - public override int GetHashCode() => HashCode.Combine(RowNumber, ColumnNumber); - - /// - /// Gets the row number and column number of the cell. - /// - public override string ToString() - { - return "DataGridCell {RowNumber = " + RowNumber + ", ColumnNumber = " + ColumnNumber + "}"; - } - } -} diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridColumnCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridColumnCollection.cs deleted file mode 100644 index 139a6273713..00000000000 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridColumnCollection.cs +++ /dev/null @@ -1,558 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Collections; -using System.ComponentModel; -using System.Diagnostics; -using System.Drawing.Design; -using System.Globalization; - -namespace System.Windows.Forms -{ - /// - /// Represents a collection of System.Windows.Forms.DataGridColumnStyle objects in the - /// control. - /// - [ - Editor("System.Windows.Forms.Design.DataGridColumnCollectionEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)), - ListBindable(false) - ] - public class GridColumnStylesCollection : BaseCollection, IList - { - CollectionChangeEventHandler onCollectionChanged; - readonly ArrayList items = new ArrayList(); - readonly DataGridTableStyle owner = null; - private readonly bool isDefault = false; - - // we have to implement IList for the Collection editor to work - // - int IList.Add(object value) - { - return Add((DataGridColumnStyle)value); - } - - void IList.Clear() - { - Clear(); - } - - bool IList.Contains(object value) - { - return items.Contains(value); - } - - int IList.IndexOf(object value) - { - return items.IndexOf(value); - } - - void IList.Insert(int index, object value) - { - throw new NotSupportedException(); - } - - void IList.Remove(object value) - { - Remove((DataGridColumnStyle)value); - } - - void IList.RemoveAt(int index) - { - RemoveAt(index); - } - - bool IList.IsFixedSize - { - get { return false; } - } - - bool IList.IsReadOnly - { - get { return false; } - } - - object IList.this[int index] - { - get { return items[index]; } - set { throw new NotSupportedException(); } - } - - void ICollection.CopyTo(Array array, int index) - { - items.CopyTo(array, index); - } - - int ICollection.Count - { - get { return items.Count; } - } - - bool ICollection.IsSynchronized - { - get { return false; } - } - - object ICollection.SyncRoot - { - get { return this; } - } - - IEnumerator IEnumerable.GetEnumerator() - { - return items.GetEnumerator(); - } - - internal GridColumnStylesCollection(DataGridTableStyle table) - { - owner = table; - } - - internal GridColumnStylesCollection(DataGridTableStyle table, bool isDefault) : this(table) - { - this.isDefault = isDefault; - } - - /// - /// Gets the list of items in the collection. - /// - protected override ArrayList List - { - get - { - return items; - } - } - - /* implemented in BaseCollection - /// - /// Gets the number of System.Windows.Forms.DataGridColumnStyle objects in the collection. - /// - /// - /// The number of System.Windows.Forms.DataGridColumnStyle objects in the System.Windows.Forms.GridColumnsStyleCollection . - /// - /// - /// The following example uses the - /// property to determine how many System.Windows.Forms.DataGridColumnStyle objects are in a System.Windows.Forms.GridColumnsStyleCollection, and uses that number to iterate through the - /// collection. - /// - /// Private Sub PrintGridColumns() - /// Dim colsCount As Integer - /// colsCount = DataGrid1.GridColumns.Count - /// Dim i As Integer - /// For i = 0 to colsCount - 1 - /// Debug.Print DataGrid1.GridColumns(i).GetType.ToString - /// Next i - /// End Sub - /// - /// - /// - /// - public override int Count { - get { - return items.Count; - } - } - */ - - /// - /// Gets the System.Windows.Forms.DataGridColumnStyle at a specified index. - /// - public DataGridColumnStyle this[int index] - { - get - { - return (DataGridColumnStyle)items[index]; - } - } - - /// - /// Gets the System.Windows.Forms.DataGridColumnStyle - /// with the specified name. - /// - public DataGridColumnStyle this[string columnName] - { - get - { - int itemCount = items.Count; - for (int i = 0; i < itemCount; ++i) - { - DataGridColumnStyle column = (DataGridColumnStyle)items[i]; - // NOTE: case-insensitive - if (string.Equals(column.MappingName, columnName, StringComparison.OrdinalIgnoreCase)) - { - return column; - } - } - return null; - } - } - - internal DataGridColumnStyle MapColumnStyleToPropertyName(string mappingName) - { - int itemCount = items.Count; - for (int i = 0; i < itemCount; ++i) - { - DataGridColumnStyle column = (DataGridColumnStyle)items[i]; - // NOTE: case-insensitive - if (string.Equals(column.MappingName, mappingName, StringComparison.OrdinalIgnoreCase)) - { - return column; - } - } - return null; - } - - /// - /// Gets the System.Windows.Forms.DataGridColumnStyle associated with the - /// specified . - /// - public DataGridColumnStyle this[PropertyDescriptor propertyDesciptor] - { - get - { - int itemCount = items.Count; - for (int i = 0; i < itemCount; ++i) - { - DataGridColumnStyle column = (DataGridColumnStyle)items[i]; - if (propertyDesciptor.Equals(column.PropertyDescriptor)) - { - return column; - } - } - return null; - } - } - - internal DataGridTableStyle DataGridTableStyle - { - get - { - return owner; - } - } - - /// - /// Adds a System.Windows.Forms.DataGridColumnStyle to the System.Windows.Forms.GridColumnStylesCollection - /// - internal void CheckForMappingNameDuplicates(DataGridColumnStyle column) - { - if (string.IsNullOrEmpty(column.MappingName)) - { - return; - } - - for (int i = 0; i < items.Count; i++) - { - if (((DataGridColumnStyle)items[i]).MappingName.Equals(column.MappingName) && column != items[i]) - { - throw new ArgumentException(SR.DataGridColumnStyleDuplicateMappingName, "column"); - } - } - } - - private void ColumnStyleMappingNameChanged(object sender, EventArgs pcea) - { - OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Refresh, null)); - } - - private void ColumnStylePropDescChanged(object sender, EventArgs pcea) - { - OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Refresh, (DataGridColumnStyle)sender)); - } - - public virtual int Add(DataGridColumnStyle column) - { - if (isDefault) - { - throw new ArgumentException(SR.DataGridDefaultColumnCollectionChanged); - } - - CheckForMappingNameDuplicates(column); - - column.SetDataGridTableInColumn(owner, true); - column.MappingNameChanged += new EventHandler(ColumnStyleMappingNameChanged); - column.PropertyDescriptorChanged += new EventHandler(ColumnStylePropDescChanged); - - // columns which are not the default should have a default - // width of DataGrid.PreferredColumnWidth - if (DataGridTableStyle != null && column.Width == -1) - { - column._width = DataGridTableStyle.PreferredColumnWidth; - } -#if false - column.AddOnPropertyChanged(owner.OnColumnChanged); -#endif - int index = items.Add(column); - OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Add, column)); - return index; - } - - public void AddRange(DataGridColumnStyle[] columns) - { - if (columns == null) - { - throw new ArgumentNullException(nameof(columns)); - } - for (int i = 0; i < columns.Length; i++) - { - Add(columns[i]); - } - } - - // the dataGrid will need to add default columns to a default - // table when there is no match for the listName in the tableStyle - internal void AddDefaultColumn(DataGridColumnStyle column) - { -#if DEBUG - Debug.Assert(isDefault, "we should be calling this function only for default tables"); - Debug.Assert(column.IsDefault, "we should be a default column"); -#endif // DEBUG - column.SetDataGridTableInColumn(owner, true); - items.Add(column); - } - - internal void ResetDefaultColumnCollection() - { - Debug.Assert(isDefault, "we should be calling this function only for default tables"); - // unparent the edit controls - for (int i = 0; i < Count; i++) - { - this[i].ReleaseHostedControl(); - } - - // get rid of the old list and get a new empty list - items.Clear(); - } - - /// - /// Occurs when a change is made to the System.Windows.Forms.GridColumnStylesCollection. - /// - public event CollectionChangeEventHandler CollectionChanged - { - add => onCollectionChanged += value; - remove => onCollectionChanged -= value; - } - - public void Clear() - { - for (int i = 0; i < Count; i++) - { - this[i].ReleaseHostedControl(); - } - items.Clear(); - OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Refresh, null)); - } - - /// - /// Gets a value indicating whether the System.Windows.Forms.GridColumnStylesCollection contains a System.Windows.Forms.DataGridColumnStyle associated with the - /// specified . - /// - public bool Contains(PropertyDescriptor propertyDescriptor) - { - return this[propertyDescriptor] != null; - } - - /// - /// Gets a value indicating whether the System.Windows.Forms.GridColumnsStyleCollection contains the specified System.Windows.Forms.DataGridColumnStyle. - /// - public bool Contains(DataGridColumnStyle column) - { - int index = items.IndexOf(column); - return index != -1; - } - - /// - /// Gets a value indicating whether the System.Windows.Forms.GridColumnsStyleCollection contains the System.Windows.Forms.DataGridColumnStyle with the specified name. - /// - public bool Contains(string name) - { - IEnumerator e = items.GetEnumerator(); - while (e.MoveNext()) - { - DataGridColumnStyle column = (DataGridColumnStyle)e.Current; - // NOTE: case-insensitive - if (string.Compare(column.MappingName, name, true, CultureInfo.InvariantCulture) == 0) - { - return true; - } - } - return false; - } - - /* implemented at BaseCollection - /// - /// Gets an enumerator for the System.Windows.Forms.GridColumnsStyleCollection. - /// - /// - /// Gets an enumerator for the System.Windows.Forms.GridColumnsStyleCollection. - /// - /// - /// An - /// that can be used to iterate through the collection. - /// - /// - /// The following example gets an that iterates through the System.Windows.Forms.GridColumnsStyleCollection. and prints the - /// of each - /// associated with the object. - /// - /// Private Sub EnumerateThroughGridColumns() - /// Dim ie As System.Collections.IEnumerator - /// Dim dgCol As DataGridColumn - /// Set ie = DataGrid1.GridColumns.GetEnumerator - /// Do While ie.GetNext = True - /// Set dgCol = ie.GetObject - /// Debug.Print dgCol.DataColumn.Caption - /// Loop - /// End Sub - /// - /// - /// - /// - /// - /// - public override IEnumerator GetEnumerator() { - return items.GetEnumerator(); - } - - /// - /// Gets an enumerator for the System.Windows.Forms.GridColumnsStyleCollection - /// . - /// - /// - /// A value that indicates if the enumerator can remove elements. , if removals are allowed; otherwise, . The default is . - /// - /// - /// An that can be used to iterate through the - /// collection. - /// - /// - /// An attempt was made to remove the System.Windows.Forms.DataGridColumnStyle through the object's method. Use the System.Windows.Forms.GridColumnsStyleCollection object's method instead. - /// - /// - /// Because this implementation doesn't support the removal - /// of System.Windows.Forms.DataGridColumnStyle objects through the - /// class's method, you must use the class's - /// method instead. - /// - /// - /// The following example gets an for that iterates through the System.Windows.Forms.GridColumnsStyleCollection. If a column in the collection is of type , it is deleted. - /// - /// Private Sub RemoveBoolColumns() - /// Dim ie As System.Collections.IEnumerator - /// Dim dgCol As DataGridColumn - /// Set ie = DataGrid1.GridColumns.GetEnumerator(true) - /// Do While ie.GetNext - /// Set dgCol = ie.GetObject - /// - /// If dgCol.ToString = "DataGridBoolColumn" Then - /// DataGrid1.GridColumns.Remove dgCol - /// End If - /// Loop - /// End If - /// - /// - /// - /// - /// - /// - public override IEnumerator GetEnumerator(bool allowRemove) { - if (!allowRemove) - return GetEnumerator(); - else - throw new NotSupportedException(SR.DataGridColumnCollectionGetEnumerator); - } - */ - - /// - /// Gets the index of a specified System.Windows.Forms.DataGridColumnStyle. - /// - public int IndexOf(DataGridColumnStyle element) - { - int itemCount = items.Count; - for (int i = 0; i < itemCount; ++i) - { - DataGridColumnStyle column = (DataGridColumnStyle)items[i]; - if (element == column) - { - return i; - } - } - return -1; - } - - /// - /// Raises the System.Windows.Forms.GridColumnsCollection.CollectionChanged event. - /// - protected void OnCollectionChanged(CollectionChangeEventArgs e) - { - onCollectionChanged?.Invoke(this, e); - - DataGrid grid = owner.DataGrid; - if (grid != null) - { - grid.checkHierarchy = true; - } - } - - /// - /// Removes the specified System.Windows.Forms.DataGridColumnStyle from the System.Windows.Forms.GridColumnsStyleCollection. - /// - public void Remove(DataGridColumnStyle column) - { - if (isDefault) - { - throw new ArgumentException(SR.DataGridDefaultColumnCollectionChanged); - } - - int columnIndex = -1; - int itemsCount = items.Count; - for (int i = 0; i < itemsCount; ++i) - { - if (items[i] == column) - { - columnIndex = i; - break; - } - } - - if (columnIndex == -1) - { - throw new InvalidOperationException(SR.DataGridColumnCollectionMissing); - } - else - { - RemoveAt(columnIndex); - } - } - - /// - /// Removes the System.Windows.Forms.DataGridColumnStyle with the specified index from the System.Windows.Forms.GridColumnsStyleCollection. - /// - public void RemoveAt(int index) - { - if (isDefault) - { - throw new ArgumentException(SR.DataGridDefaultColumnCollectionChanged); - } - - DataGridColumnStyle toRemove = (DataGridColumnStyle)items[index]; - toRemove.SetDataGridTableInColumn(null, true); - toRemove.MappingNameChanged -= new EventHandler(ColumnStyleMappingNameChanged); - toRemove.PropertyDescriptorChanged -= new EventHandler(ColumnStylePropDescChanged); -#if false - toRemove.RemoveOnPropertyChange(owner.OnColumnChanged); -#endif - items.RemoveAt(index); - OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Remove, toRemove)); - } - - public void ResetPropertyDescriptors() - { - for (int i = 0; i < Count; i++) - { - this[i].PropertyDescriptor = null; - } - } - } -} diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridColumnStyle.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridColumnStyle.cs deleted file mode 100644 index c562ba8d7ef..00000000000 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridColumnStyle.cs +++ /dev/null @@ -1,791 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Collections; -using System.ComponentModel; -using System.Diagnostics; -using System.Drawing; -using System.Runtime.InteropServices; - -namespace System.Windows.Forms -{ - /// - /// Specifies the appearance and text formatting and behavior of a control column. - /// - [ToolboxItem(false)] - [DesignTimeVisible(false)] - [DefaultProperty(nameof(HeaderText))] - public abstract class DataGridColumnStyle : Component, IDataGridColumnStyleEditingNotificationService - { - private HorizontalAlignment _alignment = HorizontalAlignment.Left; - private PropertyDescriptor _propertyDescriptor = null; - private DataGridTableStyle _dataGridTableStyle = null; - private readonly Font _font = null; - private string _mappingName = string.Empty; - private string _headerName = string.Empty; - private bool _invalid = false; - private string _nullText = SR.DataGridNullText; - private bool _readOnly = false; - private bool _updating = false; - internal int _width = -1; - private AccessibleObject _headerAccessibleObject = null; - - private static readonly object s_alignmentEvent = new object(); - private static readonly object s_propertyDescriptorEvent = new object(); - private static readonly object s_headerTextEvent = new object(); - private static readonly object s_mappingNameEvent = new object(); - private static readonly object s_nullTextEvent = new object(); - private static readonly object s_readOnlyEvent = new object(); - private static readonly object s_widthEvent = new object(); - - /// - /// In a derived class, initializes a new instance of the - /// class. - /// - public DataGridColumnStyle() - { - } - - /// - /// Initializes a new instance of the - /// class with the specified . - /// - public DataGridColumnStyle(PropertyDescriptor prop) : this() - { - PropertyDescriptor = prop; - if (prop != null) - { - _readOnly = prop.IsReadOnly; - } - } - - private protected DataGridColumnStyle(PropertyDescriptor prop, bool isDefault) : this(prop) - { -#if DEBUG - IsDefault = isDefault; -#endif - if (isDefault && prop != null) - { - // take the header name from the property name - _headerName = prop.Name; - _mappingName = prop.Name; - } - } - -#if DEBUG - internal bool IsDefault { get; } -#endif - - /// - /// Gets or sets the alignment of text in a column. - /// - [SRCategory(nameof(SR.CatDisplay))] - [Localizable(true)] - [DefaultValue(HorizontalAlignment.Left)] - public virtual HorizontalAlignment Alignment - { - get => _alignment; - set - { - if (!ClientUtils.IsEnumValid(value, (int)value, (int)HorizontalAlignment.Left, (int)HorizontalAlignment.Center)) - { - throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridLineStyle)); - } - - if (_alignment != value) - { - _alignment = value; - OnAlignmentChanged(EventArgs.Empty); - Invalidate(); - } - } - } - - public event EventHandler AlignmentChanged - { - add => Events.AddHandler(s_alignmentEvent, value); - remove => Events.RemoveHandler(s_alignmentEvent, value); - } - - /// - /// When overridden in a derived class, updates the value of a specified row with - /// the given text. - /// - protected internal virtual void UpdateUI(CurrencyManager source, int rowNum, string displayText) - { - } - - /// - /// Gets or sets the background color of the column. - /// - [Browsable(false)] - public AccessibleObject HeaderAccessibleObject - { - get => _headerAccessibleObject ?? (_headerAccessibleObject = CreateHeaderAccessibleObject()); - } - - /// - /// Gets or sets the that determines the - /// attributes of data displayed by the . - /// - [DefaultValue(null)] - [Browsable(false)] - [EditorBrowsable(EditorBrowsableState.Advanced)] - public virtual PropertyDescriptor PropertyDescriptor - { - get => _propertyDescriptor; - set - { - if (_propertyDescriptor != value) - { - _propertyDescriptor = value; - OnPropertyDescriptorChanged(EventArgs.Empty); - } - } - } - - [Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced)] - public event EventHandler PropertyDescriptorChanged - { - add => Events.AddHandler(s_propertyDescriptorEvent, value); - remove => Events.RemoveHandler(s_propertyDescriptorEvent, value); - } - - protected virtual AccessibleObject CreateHeaderAccessibleObject() - { - return new DataGridColumnHeaderAccessibleObject(this); - } - - /// - /// When overridden in a derived class, sets the - /// control that this column belongs to. - /// - protected virtual void SetDataGrid(DataGrid value) - { - SetDataGridInColumn(value); - } - - /// - /// When overridden in a derived class, sets the - /// for the column. - /// - protected virtual void SetDataGridInColumn(DataGrid value) - { - // we need to set up the PropertyDescriptor - if (PropertyDescriptor == null && value != null) - { - CurrencyManager lm = value.ListManager; - if (lm == null) - { - return; - } - - PropertyDescriptorCollection propCollection = lm.GetItemProperties(); - int propCount = propCollection.Count; - for (int i = 0; i < propCollection.Count; i++) - { - PropertyDescriptor prop = propCollection[i]; - if (!typeof(IList).IsAssignableFrom(prop.PropertyType) && prop.Name.Equals(HeaderText)) - { - PropertyDescriptor = prop; - return; - } - } - } - } - - internal void SetDataGridInternalInColumn(DataGrid value) - { - if (value == null || value.Initializing) - { - return; - } - - SetDataGridInColumn(value); - } - - /// - /// Gets the System.Windows.Forms.DataGridTableStyle for the column. - /// - [Browsable(false)] - public virtual DataGridTableStyle DataGridTableStyle => _dataGridTableStyle; - - internal void SetDataGridTableInColumn(DataGridTableStyle value, bool force) - { - if (_dataGridTableStyle != null && _dataGridTableStyle.Equals(value) && !force) - { - return; - } - - if (value != null && value.DataGrid != null && !value.DataGrid.Initializing) - { - SetDataGridInColumn(value.DataGrid); - } - - _dataGridTableStyle = value; - } - - /// - /// Gets the height of the column's font. - /// - protected int FontHeight - { - get => DataGridTableStyle?.DataGrid?.FontHeight ?? DataGridTableStyle.defaultFontHeight; - } - - /// - /// Indicates whether the Font property should be persisted. - /// - private bool ShouldSerializeFont() => _font != null; - - public event EventHandler FontChanged - { - add { } - remove { } - } - - /// - /// Gets or sets the text of the column header. - /// - [Localizable(true)] - [SRCategory(nameof(SR.CatDisplay))] - public virtual string HeaderText - { - get => _headerName; - set - { - if (value == null) - { - value = string.Empty; - } - - if (!_headerName.Equals(value)) - { - _headerName = value; - OnHeaderTextChanged(EventArgs.Empty); - // we only invalidate columns that are visible ( ie, their propertyDescriptor is not null) - if (PropertyDescriptor != null) - { - Invalidate(); - } - } - } - } - - public event EventHandler HeaderTextChanged - { - add => Events.AddHandler(s_headerTextEvent, value); - remove => Events.RemoveHandler(s_headerTextEvent, value); - } - - [Editor("System.Windows.Forms.Design.DataGridColumnStyleMappingNameEditor, " + AssemblyRef.SystemDesign, typeof(Drawing.Design.UITypeEditor))] - [Localizable(true)] - [DefaultValue("")] - public string MappingName - { - get => _mappingName; - set - { - if (value == null) - { - value = string.Empty; - } - - if (!_mappingName.Equals(value)) - { - string originalMappingName = _mappingName; - _mappingName = value; - try - { - _dataGridTableStyle?.GridColumnStyles.CheckForMappingNameDuplicates(this); - } - catch - { - _mappingName = originalMappingName; - throw; - } - - OnMappingNameChanged(EventArgs.Empty); - } - } - } - - public event EventHandler MappingNameChanged - { - add => Events.AddHandler(s_mappingNameEvent, value); - remove => Events.RemoveHandler(s_mappingNameEvent, value); - } - - /// - /// Indicates whether the System.Windows.Forms.DataGridColumnStyle.HeaderText property - /// should be persisted. - /// - private bool ShouldSerializeHeaderText() - { - return (_headerName.Length != 0); - } - - /// - /// Resets the System.Windows.Forms.DataGridColumnStyle.HeaderText to its default value. - /// - public void ResetHeaderText() => HeaderText = string.Empty; - - /// - /// Gets or sets the text that is displayed when the column contains a null - /// value. - /// - [Localizable(true)] - [SRCategory(nameof(SR.CatDisplay))] - public virtual string NullText - { - get => _nullText; - set - { - if (_nullText != value) - { - _nullText = value; - OnNullTextChanged(EventArgs.Empty); - Invalidate(); - } - } - } - - public event EventHandler NullTextChanged - { - add => Events.AddHandler(s_nullTextEvent, value); - remove => Events.RemoveHandler(s_nullTextEvent, value); - } - - /// - /// Gets or sets a value indicating whether the data in the column cannot be edited. - /// - [DefaultValue(false)] - public virtual bool ReadOnly - { - get => _readOnly; - set - { - if (_readOnly != value) - { - _readOnly = value; - OnReadOnlyChanged(EventArgs.Empty); - } - } - } - - public event EventHandler ReadOnlyChanged - { - add => Events.AddHandler(s_readOnlyEvent, value); - remove => Events.RemoveHandler(s_readOnlyEvent, value); - } - - /// - /// Gets or sets the width of the column. - /// - [SRCategory(nameof(SR.CatLayout))] - [Localizable(true)] - [DefaultValue(100)] - public virtual int Width - { - get => _width; - set - { - if (_width != value) - { - _width = value; - DataGrid grid = DataGridTableStyle?.DataGrid; - if (grid != null) - { - // rearrange the scroll bars - grid.PerformLayout(); - - // force the grid to repaint - grid.InvalidateInside(); - } - - OnWidthChanged(EventArgs.Empty); - } - } - } - - public event EventHandler WidthChanged - { - add => Events.AddHandler(s_widthEvent, value); - remove => Events.RemoveHandler(s_widthEvent, value); - } - - /// - /// Suspends the painting of the column until the - /// method is called. - /// - protected void BeginUpdate() => _updating = true; - - /// - /// Resumes the painting of columns suspended by calling the - /// method. - /// - protected void EndUpdate() - { - _updating = false; - if (_invalid) - { - _invalid = false; - Invalidate(); - } - } - - internal virtual string GetDisplayText(object value) => value.ToString(); - - private void ResetNullText() => NullText = SR.DataGridNullText; - - private bool ShouldSerializeNullText() => !SR.DataGridNullText.Equals(_nullText); - - /// - /// When overridden in a derived class, gets the optimum width and height of the - /// specified value. - /// - protected internal abstract Size GetPreferredSize(Graphics g, object value); - - /// - /// Gets the minimum height of a row. - /// - protected internal abstract int GetMinimumHeight(); - - /// - /// When overridden in a derived class, gets the height to be used in for - /// automatically resizing columns. - /// - protected internal abstract int GetPreferredHeight(Graphics g, object value); - - /// - /// Gets the value in the specified row from the specified System.Windows.Forms.ListManager. - /// - protected internal virtual object GetColumnValueAtRow(CurrencyManager source, int rowNum) - { - CheckValidDataSource(source); - PropertyDescriptor descriptor = PropertyDescriptor; - if (descriptor == null) - { - throw new InvalidOperationException(SR.DataGridColumnNoPropertyDescriptor); - } - - return descriptor.GetValue(source[rowNum]); - } - - /// - /// Redraws the column and causes a paint message to be sent to the control. - /// - protected virtual void Invalidate() - { - if (_updating) - { - _invalid = true; - return; - } - - DataGridTableStyle?.InvalidateColumn(this); - } - - /// - /// Checks if the specified DataView is valid. - /// - protected void CheckValidDataSource(CurrencyManager value) - { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - - // The code may delete a gridColumn that was editing. - // In that case, we still have to push the value into the backend - // and we only need the propertyDescriptor to push the value. - // (take a look at gridEditAndDeleteEditColumn) - if (PropertyDescriptor == null) - { - throw new InvalidOperationException(string.Format(SR.DataGridColumnUnbound, HeaderText)); - } - } - - /// - /// When overridden in a derived class, initiates a request to interrrupt an edit - /// procedure. - /// - protected internal abstract void Abort(int rowNum); - - /// - /// When overridden in a derived class, inititates a request to complete an - /// editing procedure. - /// - protected internal abstract bool Commit(CurrencyManager dataSource, int rowNum); - - /// - /// When overridden in a deriving class, prepares a cell for editing. - /// - protected internal virtual void Edit(CurrencyManager source, int rowNum, Rectangle bounds, bool readOnly) - { - Edit(source, rowNum, bounds, readOnly, null, true); - } - - /// - /// Prepares the cell for editing, passing the specified , - /// row number, , argument indicating whether - /// the column is read-only, and the text to display in the new control. - /// - protected internal virtual void Edit(CurrencyManager source, int rowNum, Rectangle bounds, bool readOnly, string displayText) - { - Edit(source, rowNum, bounds, readOnly, displayText, true); - } - - /// - /// When overridden in a deriving class, prepares a cell for editing. - /// - protected internal abstract void Edit(CurrencyManager source, int rowNum, Rectangle bounds, bool readOnly, string displayText, bool cellIsVisible); - - /// - /// Indicates whether the a mouse down event occurred at the specified row, at - /// the specified x and y coordinates. - /// - internal virtual bool MouseDown(int rowNum, int x, int y) - { - return false; - } - - /// - /// When overriden in a derived class, enters a - /// into the column. - /// - protected internal virtual void EnterNullValue() - { - } - - /// - /// Provides a handler for determining which key was pressed, and whether to - /// process it. - /// - internal virtual bool KeyPress(int rowNum, Keys keyData) - { - // if this is read only then do not do anything - if (ReadOnly || (DataGridTableStyle != null && DataGridTableStyle.DataGrid != null && DataGridTableStyle.DataGrid.ReadOnly)) - { - return false; - } - if (keyData == (Keys.Control | Keys.NumPad0) || keyData == (Keys.Control | Keys.D0)) - { - EnterNullValue(); - return true; - } - - return false; - } - - /// - /// When overridden in a derived class, directs the column to concede focus with - /// an appropriate action. - /// - protected internal virtual void ConcedeFocus() - { - } - - /// - /// Paints the a with the specified - /// , , - /// System.Windows.Forms.CurrencyManager, and row number. - /// - protected internal abstract void Paint(Graphics g, Rectangle bounds, CurrencyManager source, int rowNum); - - /// - /// When overridden in a derived class, paints a - /// with the specified , , - /// see Rectangle, row number, and alignment. - /// - protected internal abstract void Paint(Graphics g, Rectangle bounds, CurrencyManager source, int rowNum, bool alignToRight); - - /// - /// Paints a with the specified , , see System.Data.DataView, row number, background color, foreground color, and alignment. - /// - protected internal virtual void Paint(Graphics g, Rectangle bounds, CurrencyManager source, int rowNum, - Brush backBrush, Brush foreBrush, bool alignToRight) - { - Paint(g, bounds, source, rowNum, alignToRight); - } - - private void OnPropertyDescriptorChanged(EventArgs e) - { - EventHandler eh = Events[s_propertyDescriptorEvent] as EventHandler; - eh?.Invoke(this, e); - } - - private void OnAlignmentChanged(EventArgs e) - { - EventHandler eh = Events[s_alignmentEvent] as EventHandler; - eh?.Invoke(this, e); - } - - private void OnHeaderTextChanged(EventArgs e) - { - EventHandler eh = Events[s_headerTextEvent] as EventHandler; - eh?.Invoke(this, e); - } - - private void OnMappingNameChanged(EventArgs e) - { - EventHandler eh = Events[s_mappingNameEvent] as EventHandler; - eh?.Invoke(this, e); - } - - private void OnReadOnlyChanged(EventArgs e) - { - EventHandler eh = Events[s_readOnlyEvent] as EventHandler; - eh?.Invoke(this, e); - } - - private void OnNullTextChanged(EventArgs e) - { - EventHandler eh = Events[s_nullTextEvent] as EventHandler; - eh?.Invoke(this, e); - } - - private void OnWidthChanged(EventArgs e) - { - EventHandler eh = Events[s_widthEvent] as EventHandler; - eh?.Invoke(this, e); - } - - /// - /// Sets the value in a specified row with the value from a specified see DataView. - /// - protected internal virtual void SetColumnValueAtRow(CurrencyManager source, int rowNum, object value) - { - CheckValidDataSource(source); - PropertyDescriptor descriptor = PropertyDescriptor; - if (descriptor == null) - { - throw new InvalidOperationException(SR.DataGridColumnNoPropertyDescriptor); - } - - if (source.Position != rowNum) - { - throw new ArgumentException(SR.DataGridColumnListManagerPosition, nameof(rowNum)); - } - if (source[rowNum] is IEditableObject editableObject) - { - editableObject.BeginEdit(); - } - - descriptor.SetValue(source[rowNum], value); - } - - protected internal virtual void ColumnStartedEditing(Control editingControl) - { - DataGridTableStyle?.DataGrid?.ColumnStartedEditing(editingControl); - } - - void IDataGridColumnStyleEditingNotificationService.ColumnStartedEditing(Control editingControl) - { - ColumnStartedEditing(editingControl); - } - - protected internal virtual void ReleaseHostedControl() - { - } - - protected class CompModSwitches - { - private static TraceSwitch dgEditColumnEditing; - - public static TraceSwitch DGEditColumnEditing - { - get - { - if (dgEditColumnEditing == null) - { - dgEditColumnEditing = new TraceSwitch("DGEditColumnEditing", "Editing related tracing"); - } - - return dgEditColumnEditing; - } - } - } - - [ComVisible(true)] - protected class DataGridColumnHeaderAccessibleObject : AccessibleObject - { - public DataGridColumnHeaderAccessibleObject(DataGridColumnStyle owner) : this() - { - Debug.Assert(owner != null, "DataGridColumnHeaderAccessibleObject must have a valid owner DataGridColumn"); - Owner = owner; - } - - public DataGridColumnHeaderAccessibleObject() : base() - { - } - - public override Rectangle Bounds - { - get - { - // we need to get the width and the X coordinate of this column on the screen - // we can't just cache this, cause the column may be moved in the collection - if (Owner.PropertyDescriptor == null) - { - return Rectangle.Empty; - } - - DataGrid dg = DataGrid; - if (dg.DataGridRowsLength == 0) - { - return Rectangle.Empty; - } - - // We need to find this column's offset in the gridColumnCollection. - GridColumnStylesCollection cols = Owner._dataGridTableStyle.GridColumnStyles; - int offset = -1; - for (int i = 0; i < cols.Count; i++) - { - if (cols[i] == Owner) - { - offset = i; - break; - } - } - - Debug.Assert(offset >= 0, "this column must be in a collection, otherwise its bounds are useless"); - Rectangle rect = dg.GetCellBounds(0, offset); - // Now add the Y coordinate of the datagrid.Layout.Data. - // It should be the same as dataGrid.Layout.ColumnHeaders - rect.Y = dg.GetColumnHeadersRect().Y; - return dg.RectangleToScreen(rect); - } - } - - public override string Name => Owner._headerName; - - protected DataGridColumnStyle Owner { get; } - - public override AccessibleObject Parent => DataGrid.AccessibilityObject; - - private DataGrid DataGrid => Owner._dataGridTableStyle.dataGrid; - - public override AccessibleRole Role => AccessibleRole.ColumnHeader; - - public override AccessibleObject Navigate(AccessibleNavigation navdir) - { - switch (navdir) - { - case AccessibleNavigation.Right: - case AccessibleNavigation.Next: - case AccessibleNavigation.Down: - return Parent.GetChild(1 + Owner._dataGridTableStyle.GridColumnStyles.IndexOf(Owner) + 1); - case AccessibleNavigation.Up: - case AccessibleNavigation.Left: - case AccessibleNavigation.Previous: - return Parent.GetChild(1 + Owner._dataGridTableStyle.GridColumnStyles.IndexOf(Owner) - 1); - - } - - return null; - } - } - } -} diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridDefaultColumnWidthTypeConverter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridDefaultColumnWidthTypeConverter.cs deleted file mode 100644 index f23c6edaa6c..00000000000 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridDefaultColumnWidthTypeConverter.cs +++ /dev/null @@ -1,75 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.ComponentModel; -using System.Globalization; - -namespace System.Windows.Forms -{ - public class DataGridPreferredColumnWidthTypeConverter : TypeConverter - { - public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) - { - if (sourceType == typeof(string) || sourceType == typeof(int)) - { - return true; - } - else - { - return false; - } - } - - public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) - { - if (destinationType == typeof(string)) - { - if (value.GetType() == typeof(int)) - { - int pulica = (int)value; - if (pulica == -1) - { - return "AutoColumnResize (-1)"; - } - else - { - return pulica.ToString(CultureInfo.CurrentCulture); - } - } - else - { - return base.ConvertTo(context, culture, value, destinationType); - } - } - else - { - return base.ConvertTo(context, culture, value, destinationType); - } - } - - public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) - { - if (value.GetType() == typeof(string)) - { - string text = value.ToString(); - if (text.Equals("AutoColumnResize (-1)")) - { - return -1; - } - else - { - return int.Parse(text, CultureInfo.CurrentCulture); - } - } - else if (value.GetType() == typeof(int)) - { - return (int)value; - } - else - { - throw GetConvertFromException(value); - } - } - } -} diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridLineStyle.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridLineStyle.cs deleted file mode 100644 index 84d9184fa47..00000000000 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridLineStyle.cs +++ /dev/null @@ -1,22 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System.Windows.Forms -{ - /// - /// Specifies the style of gridlines in a . - /// - public enum DataGridLineStyle - { - /// - /// No gridlines between cells. - /// - None, - - /// - /// Solid gridlines between cells. - /// - Solid - } -} diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridParentRows.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridParentRows.cs deleted file mode 100644 index c9a91726b07..00000000000 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridParentRows.cs +++ /dev/null @@ -1,1389 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Collections; -using System.Diagnostics; -using System.Drawing; -using System.Drawing.Imaging; -using System.Runtime.InteropServices; -using System.Text; - -namespace System.Windows.Forms -{ - internal class DataGridParentRows - { - // siting - // - private readonly DataGrid dataGrid; - - // ui - // - // private Color backColor = DataGrid.defaultParentRowsBackColor; - // private Color foreColor = DataGrid.defaultParentRowsForeColor; - - private SolidBrush backBrush = DataGrid.DefaultParentRowsBackBrush; - private SolidBrush foreBrush = DataGrid.DefaultParentRowsForeBrush; - - private readonly int borderWidth = 1; - // private Color borderColor = SystemColors.WindowFrame; - private Brush borderBrush = new SolidBrush(SystemColors.WindowFrame); - - private static Bitmap rightArrow = null; - private static Bitmap leftArrow = null; - - private readonly ColorMap[] colorMap = new ColorMap[] { new ColorMap() }; - - // private bool gridLineDots = false; - // private Color gridLineColor = SystemColors.Control; - // private Brush gridLineBrush = SystemBrushes.Control; - private readonly Pen gridLinePen = SystemPens.Control; - - private int totalHeight = 0; - private int textRegionHeight = 0; - - // now that we have left and right arrows, we also have layout - private readonly Layout layout = new Layout(); - - // mouse info - // - // private bool overLeftArrow = false; - // private bool overRightArrow = false; - private bool downLeftArrow = false; - private bool downRightArrow = false; - - // a horizOffset of 0 means that the layout for the parent - // rows is left aligned. - // a horizOffset of 1 means that the leftmost unit of information ( let it be a - // table name, a column name or a column value ) is not visible. - // a horizOffset of 2 means that the leftmost 2 units of information are not visible, and so on - // - private int horizOffset = 0; - - // storage for parent row states - // - private readonly ArrayList parents = new ArrayList(); - private int parentsCount = 0; - private readonly ArrayList rowHeights = new ArrayList(); - AccessibleObject accessibleObject; - - internal DataGridParentRows(DataGrid dataGrid) - { - colorMap[0].OldColor = Color.Black; - this.dataGrid = dataGrid; - // UpdateGridLinePen(); - } - - // =------------------------------------------------------------------ - // = Properties - // =------------------------------------------------------------------ - - public AccessibleObject AccessibleObject - { - get - { - if (accessibleObject == null) - { - accessibleObject = new DataGridParentRowsAccessibleObject(this); - } - return accessibleObject; - } - } - - internal Color BackColor - { - get - { - return backBrush.Color; - } - set - { - if (value.IsEmpty) - { - throw new ArgumentException(string.Format(SR.DataGridEmptyColor, "Parent Rows BackColor")); - } - - if (value != backBrush.Color) - { - backBrush = new SolidBrush(value); - Invalidate(); - } - } - } - - internal SolidBrush BackBrush - { - get - { - return backBrush; - } - set - { - if (value != backBrush) - { - CheckNull(value, "BackBrush"); - backBrush = value; - Invalidate(); - } - } - } - - internal SolidBrush ForeBrush - { - get - { - return foreBrush; - } - set - { - if (value != foreBrush) - { - CheckNull(value, "BackBrush"); - foreBrush = value; - Invalidate(); - } - } - } - - // since the layout of the parentRows is computed on every paint message, - // we can actually return true ClientRectangle coordinates - internal Rectangle GetBoundsForDataGridStateAccesibility(DataGridState dgs) - { - Rectangle ret = Rectangle.Empty; - int rectY = 0; - for (int i = 0; i < parentsCount; i++) - { - int height = (int)rowHeights[i]; - if (parents[i] == dgs) - { - ret.X = layout.leftArrow.IsEmpty ? layout.data.X : layout.leftArrow.Right; - ret.Height = height; - ret.Y = rectY; - ret.Width = layout.data.Width; - return ret; - } - rectY += height; - } - return ret; - } - - /* - internal Color BorderColor { - get { - return borderColor; - } - set { - if (value != borderColor) { - borderColor = value; - Invalidate(); - } - } - } - */ - - internal Brush BorderBrush - { - get - { - return borderBrush; - } - set - { - if (value != borderBrush) - { - borderBrush = value; - Invalidate(); - } - } - } - - /* - internal Brush GridLineBrush { - get { - return gridLineBrush; - } - set { - if (value != gridLineBrush) { - gridLineBrush = value; - UpdateGridLinePen(); - Invalidate(); - } - } - } - - internal bool GridLineDots { - get { - return gridLineDots; - } - set { - if (gridLineDots != value) { - gridLineDots = value; - UpdateGridLinePen(); - Invalidate(); - } - } - } - */ - - internal int Height - { - get - { - return totalHeight; - } - } - - internal Color ForeColor - { - get - { - return foreBrush.Color; - } - set - { - if (value.IsEmpty) - { - throw new ArgumentException(string.Format(SR.DataGridEmptyColor, "Parent Rows ForeColor")); - } - - if (value != foreBrush.Color) - { - foreBrush = new SolidBrush(value); - Invalidate(); - } - } - } - - internal bool Visible - { - get - { - return dataGrid.ParentRowsVisible; - } - set - { - dataGrid.ParentRowsVisible = value; - } - } - - // =------------------------------------------------------------------ - // = Methods - // =------------------------------------------------------------------ - - /// - /// Adds a DataGridState object to the top of the list of parents. - /// - internal void AddParent(DataGridState dgs) - { - CurrencyManager childDataSource = (CurrencyManager)dataGrid.BindingContext[dgs.DataSource, dgs.DataMember]; - parents.Add(dgs); - SetParentCount(parentsCount + 1); - Debug.Assert(GetTopParent() != null, "we should have a parent at least"); - } - - internal void Clear() - { - for (int i = 0; i < parents.Count; i++) - { - DataGridState dgs = parents[i] as DataGridState; - dgs.RemoveChangeNotification(); - } - parents.Clear(); - rowHeights.Clear(); - totalHeight = 0; - SetParentCount(0); - } - - internal void SetParentCount(int count) - { - parentsCount = count; - dataGrid.Caption.BackButtonVisible = (parentsCount > 0) && (dataGrid.AllowNavigation); - } - - internal void CheckNull(object value, string propName) - { - if (value == null) - { - throw new ArgumentNullException(nameof(propName)); - } - } - - internal void Dispose() - { - gridLinePen.Dispose(); - } - - /// - /// Retrieves the top most parent in the list of parents. - /// - internal DataGridState GetTopParent() - { - if (parentsCount < 1) - { - return null; - } - return (DataGridState)(((ICloneable)(parents[parentsCount - 1])).Clone()); - } - - /// - /// Determines if there are any parent rows contained in this object. - /// - internal bool IsEmpty() - { - return parentsCount == 0; - } - - /// - /// Similar to GetTopParent() but also removes it. - /// - internal DataGridState PopTop() - { - if (parentsCount < 1) - { - return null; - } - - SetParentCount(parentsCount - 1); - DataGridState ret = (DataGridState)parents[parentsCount]; - ret.RemoveChangeNotification(); - parents.RemoveAt(parentsCount); - return ret; - } - - internal void Invalidate() - { - if (dataGrid != null) - { - dataGrid.InvalidateParentRows(); - } - } - - internal void InvalidateRect(Rectangle rect) - { - if (dataGrid != null) - { - Rectangle r = new Rectangle(rect.X, rect.Y, rect.Width + borderWidth, rect.Height + borderWidth); - dataGrid.InvalidateParentRowsRect(r); - } - } - - // called from DataGrid::OnLayout - internal void OnLayout() - { - if (parentsCount == rowHeights.Count) - { - return; - } - - int height = 0; - if (totalHeight == 0) - { - totalHeight += 2 * borderWidth; - } - - // figure out how tall each row's text will be - // - textRegionHeight = (int)dataGrid.Font.Height + 2; - - // make the height of the Column.Font count for the height - // of the parentRows; - // - // if the user wants to programatically - // navigate to a relation in the constructor of the form - // ( ie, when the form does not process PerformLayout ) - // the grid will receive an OnLayout message when there is more - // than one parent in the grid - if (parentsCount > rowHeights.Count) - { - Debug.Assert(parentsCount == rowHeights.Count + 1 || rowHeights.Count == 0, "see comment above for more info"); - int rowHeightsCount = rowHeights.Count; - for (int i = rowHeightsCount; i < parentsCount; i++) - { - DataGridState dgs = (DataGridState)parents[i]; - GridColumnStylesCollection cols = dgs.GridColumnStyles; - - int colsHeight = 0; - - for (int j = 0; j < cols.Count; j++) - { - colsHeight = Math.Max(colsHeight, cols[j].GetMinimumHeight()); - } - height = Math.Max(colsHeight, textRegionHeight); - - // the height of the bottom border - height++; - rowHeights.Add(height); - - totalHeight += height; - } - } - else - { - Debug.Assert(parentsCount == rowHeights.Count - 1, "we do layout only for push/popTop"); - if (parentsCount == 0) - { - totalHeight = 0; - } - else - { - totalHeight -= (int)rowHeights[rowHeights.Count - 1]; - } - - rowHeights.RemoveAt(rowHeights.Count - 1); - } - } - - private int CellCount() - { - int cellCount = 0; - cellCount = ColsCount(); - - if (dataGrid.ParentRowsLabelStyle == DataGridParentRowsLabelStyle.TableName || - dataGrid.ParentRowsLabelStyle == DataGridParentRowsLabelStyle.Both) - { - cellCount++; - } - - return cellCount; - } - - private void ResetMouseInfo() - { - // overLeftArrow = false; - // overRightArrow = false; - downLeftArrow = false; - downRightArrow = false; - } - - private void LeftArrowClick(int cellCount) - { - if (horizOffset > 0) - { - ResetMouseInfo(); - horizOffset -= 1; - Invalidate(); - } - else - { - ResetMouseInfo(); - InvalidateRect(layout.leftArrow); - } - } - - private void RightArrowClick(int cellCount) - { - if (horizOffset < cellCount - 1) - { - ResetMouseInfo(); - horizOffset += 1; - Invalidate(); - } - else - { - ResetMouseInfo(); - InvalidateRect(layout.rightArrow); - } - } - - // the only mouse clicks that are handled are - // the mouse clicks on the LeftArrow and RightArrow - // - internal void OnMouseDown(int x, int y, bool alignToRight) - { - if (layout.rightArrow.IsEmpty) - { - Debug.Assert(layout.leftArrow.IsEmpty, "we can't have the leftArrow w/o the rightArrow"); - return; - } - - int cellCount = CellCount(); - - if (layout.rightArrow.Contains(x, y)) - { - // draw a nice sunken border around the right arrow area - // we want to keep a cell on the screen - - downRightArrow = true; - - if (alignToRight) - { - LeftArrowClick(cellCount); - } - else - { - RightArrowClick(cellCount); - } - } - else if (layout.leftArrow.Contains(x, y)) - { - downLeftArrow = true; - - if (alignToRight) - { - RightArrowClick(cellCount); - } - else - { - LeftArrowClick(cellCount); - } - } - else - { - if (downLeftArrow) - { - downLeftArrow = false; - InvalidateRect(layout.leftArrow); - } - if (downRightArrow) - { - downRightArrow = false; - InvalidateRect(layout.rightArrow); - } - } - } - - internal void OnMouseLeave() - { - if (downLeftArrow) - { - downLeftArrow = false; - InvalidateRect(layout.leftArrow); - } - if (downRightArrow) - { - downRightArrow = false; - InvalidateRect(layout.rightArrow); - } - } - - internal void OnMouseMove(int x, int y) - { - /* - if (!layout.leftArrow.IsEmpty && layout.leftArrow.Contains(x,y)) - { - ResetMouseInfo(); - overLeftArrow = true; - InvalidateRect(layout.leftArrow); - return; - } - if (!layout.rightArrow.IsEmpty && layout.rightArrow.Contains(x,y)) - { - ResetMouseInfo(); - overRightArrow = true; - InvalidateRect(layout.rightArrow); - return; - } - */ - - if (downLeftArrow) - { - downLeftArrow = false; - InvalidateRect(layout.leftArrow); - } - if (downRightArrow) - { - downRightArrow = false; - InvalidateRect(layout.rightArrow); - } - } - - internal void OnMouseUp(int x, int y) - { - ResetMouseInfo(); - if (!layout.rightArrow.IsEmpty && layout.rightArrow.Contains(x, y)) - { - InvalidateRect(layout.rightArrow); - return; - } - if (!layout.leftArrow.IsEmpty && layout.leftArrow.Contains(x, y)) - { - InvalidateRect(layout.leftArrow); - return; - } - } - - internal void OnResize(Rectangle oldBounds) - { - Invalidate(); - } - - /// - /// Paints the parent rows - /// - internal void Paint(Graphics g, Rectangle visualbounds, bool alignRight) - { - Rectangle bounds = visualbounds; - // Paint the border around our bounds - if (borderWidth > 0) - { - PaintBorder(g, bounds); - bounds.Inflate(-borderWidth, -borderWidth); - } - - PaintParentRows(g, bounds, alignRight); - } - - private void PaintBorder(Graphics g, Rectangle bounds) - { - Rectangle border = bounds; - - // top - border.Height = borderWidth; - g.FillRectangle(borderBrush, border); - - // bottom - border.Y = bounds.Bottom - borderWidth; - g.FillRectangle(borderBrush, border); - - // left - border = new Rectangle(bounds.X, bounds.Y + borderWidth, - borderWidth, bounds.Height - 2 * borderWidth); - g.FillRectangle(borderBrush, border); - - // right - border.X = bounds.Right - borderWidth; - g.FillRectangle(borderBrush, border); - } - - // will return the width of the text box that will fit all the - // tables names - private int GetTableBoxWidth(Graphics g, Font font) - { - // try to make the font BOLD - Font textFont = font; - try - { - textFont = new Font(font, FontStyle.Bold); - } - catch - { - } - int width = 0; - for (int row = 0; row < parentsCount; row++) - { - DataGridState dgs = (DataGridState)parents[row]; - // Graphics.MeasureString(...) returns different results for ": " than for " :" - // - string displayTableName = dgs.ListManager.GetListName() + " :"; - int size = (int)g.MeasureString(displayTableName, textFont).Width; - width = Math.Max(size, width); - } - - return width; - } - - // will return the width of the text box that will - // fit all the column names - private int GetColBoxWidth(Graphics g, Font font, int colNum) - { - int width = 0; - - for (int row = 0; row < parentsCount; row++) - { - DataGridState dgs = (DataGridState)parents[row]; - GridColumnStylesCollection columns = dgs.GridColumnStyles; - if (colNum < columns.Count) - { - // Graphics.MeasureString(...) returns different results for ": " than for " :" - // - string colName = columns[colNum].HeaderText + " :"; - int size = (int)g.MeasureString(colName, font).Width; - width = Math.Max(size, width); - } - } - - return width; - } - - // will return the width of the best fit for the column - // - private int GetColDataBoxWidth(Graphics g, int colNum) - { - int width = 0; - for (int row = 0; row < parentsCount; row++) - { - DataGridState dgs = (DataGridState)parents[row]; - GridColumnStylesCollection columns = dgs.GridColumnStyles; - if (colNum < columns.Count) - { - object value = columns[colNum].GetColumnValueAtRow((CurrencyManager)dataGrid.BindingContext[dgs.DataSource, dgs.DataMember], - dgs.LinkingRow.RowNumber); - int size = columns[colNum].GetPreferredSize(g, value).Width; - width = Math.Max(size, width); - } - } - return width; - } - - // will return the count of the table with the largest number of columns - private int ColsCount() - { - int colNum = 0; - for (int row = 0; row < parentsCount; row++) - { - DataGridState dgs = (DataGridState)parents[row]; - colNum = Math.Max(colNum, dgs.GridColumnStyles.Count); - } - return colNum; - } - - // will return the total width required to paint the parentRows - private int TotalWidth(int tableNameBoxWidth, int[] colsNameWidths, int[] colsDataWidths) - { - int totalWidth = 0; - totalWidth += tableNameBoxWidth; - Debug.Assert(colsNameWidths.Length == colsDataWidths.Length, "both arrays are as long as the largest column count in dgs"); - for (int i = 0; i < colsNameWidths.Length; i++) - { - totalWidth += colsNameWidths[i]; - totalWidth += colsDataWidths[i]; - } - - // let 3 pixels in between datacolumns - // see DonnaWa - totalWidth += 3 * (colsNameWidths.Length - 1); - return totalWidth; - } - - // computes the layout for the parent rows - // - private void ComputeLayout(Rectangle bounds, int tableNameBoxWidth, int[] colsNameWidths, int[] colsDataWidths) - { - int totalWidth = TotalWidth(tableNameBoxWidth, colsNameWidths, colsDataWidths); - if (totalWidth > bounds.Width) - { - layout.leftArrow = new Rectangle(bounds.X, bounds.Y, 15, bounds.Height); - layout.data = new Rectangle(layout.leftArrow.Right, bounds.Y, bounds.Width - 30, bounds.Height); - layout.rightArrow = new Rectangle(layout.data.Right, bounds.Y, 15, bounds.Height); - } - else - { - layout.data = bounds; - layout.leftArrow = Rectangle.Empty; - layout.rightArrow = Rectangle.Empty; - } - } - - private void PaintParentRows(Graphics g, Rectangle bounds, bool alignToRight) - { - // variables needed for aligning the table and column names - int tableNameBoxWidth = 0; - int numCols = ColsCount(); - int[] colsNameWidths = new int[numCols]; - int[] colsDataWidths = new int[numCols]; - - // compute the size of the box that will contain the tableName - // - if (dataGrid.ParentRowsLabelStyle == DataGridParentRowsLabelStyle.TableName || - dataGrid.ParentRowsLabelStyle == DataGridParentRowsLabelStyle.Both) - { - tableNameBoxWidth = GetTableBoxWidth(g, dataGrid.Font); - } - - // initialiaze the arrays that contain the column names and the column size - // - for (int i = 0; i < numCols; i++) - { - if (dataGrid.ParentRowsLabelStyle == DataGridParentRowsLabelStyle.ColumnName || - dataGrid.ParentRowsLabelStyle == DataGridParentRowsLabelStyle.Both) - { - colsNameWidths[i] = GetColBoxWidth(g, dataGrid.Font, i); - } - else - { - colsNameWidths[i] = 0; - } - colsDataWidths[i] = GetColDataBoxWidth(g, i); - } - - // compute the layout - // - ComputeLayout(bounds, tableNameBoxWidth, colsNameWidths, colsDataWidths); - - // paint the navigation arrows, if necessary - // - if (!layout.leftArrow.IsEmpty) - { - g.FillRectangle(BackBrush, layout.leftArrow); - PaintLeftArrow(g, layout.leftArrow, alignToRight); - } - - // paint the parent rows: - // - Rectangle rowBounds = layout.data; - for (int row = 0; row < parentsCount; ++row) - { - rowBounds.Height = (int)rowHeights[row]; - if (rowBounds.Y > bounds.Bottom) - { - break; - } - - int paintedWidth = PaintRow(g, rowBounds, row, dataGrid.Font, alignToRight, tableNameBoxWidth, colsNameWidths, colsDataWidths); - if (row == parentsCount - 1) - { - break; - } - - // draw the grid line below - g.DrawLine(gridLinePen, rowBounds.X, rowBounds.Bottom, - rowBounds.X + paintedWidth, - rowBounds.Bottom); - rowBounds.Y += rowBounds.Height; - } - - if (!layout.rightArrow.IsEmpty) - { - g.FillRectangle(BackBrush, layout.rightArrow); - PaintRightArrow(g, layout.rightArrow, alignToRight); - } - } - - private Bitmap GetBitmap(string bitmapName) - { - try - { - return DpiHelper.GetBitmapFromIcon(typeof(DataGridParentRows), bitmapName); - } - catch (Exception e) - { - Debug.Fail("Failed to load bitmap: " + bitmapName, e.ToString()); - return null; - } - } - - private Bitmap GetRightArrowBitmap() - { - if (rightArrow == null) - { - rightArrow = GetBitmap("DataGridParentRows.RightArrow"); - } - - return rightArrow; - } - - private Bitmap GetLeftArrowBitmap() - { - if (leftArrow == null) - { - leftArrow = GetBitmap("DataGridParentRows.LeftArrow"); - } - - return leftArrow; - } - - private void PaintBitmap(Graphics g, Bitmap b, Rectangle bounds) - { - // center the bitmap in the bounds: - int bmpX = bounds.X + (bounds.Width - b.Width) / 2; - int bmpY = bounds.Y + (bounds.Height - b.Height) / 2; - Rectangle bmpRect = new Rectangle(bmpX, bmpY, b.Width, b.Height); - - g.FillRectangle(BackBrush, bmpRect); - - // now draw the bitmap - ImageAttributes attr = new ImageAttributes(); - colorMap[0].NewColor = ForeColor; - attr.SetRemapTable(colorMap, ColorAdjustType.Bitmap); - g.DrawImage(b, bmpRect, 0, 0, bmpRect.Width, bmpRect.Height, GraphicsUnit.Pixel, attr); - attr.Dispose(); - } - - /* - private void PaintOverButton(Graphics g, Rectangle bounds) - { - } - */ - - private void PaintDownButton(Graphics g, Rectangle bounds) - { - g.DrawLine(Pens.Black, bounds.X, bounds.Y, bounds.X + bounds.Width, bounds.Y); // the top - g.DrawLine(Pens.White, bounds.X + bounds.Width, bounds.Y, bounds.X + bounds.Width, bounds.Y + bounds.Height); // the right side - g.DrawLine(Pens.White, bounds.X + bounds.Width, bounds.Y + bounds.Height, bounds.X, bounds.Y + bounds.Height); // the right side - g.DrawLine(Pens.Black, bounds.X, bounds.Y + bounds.Height, bounds.X, bounds.Y); // the left side - } - - private void PaintLeftArrow(Graphics g, Rectangle bounds, bool alignToRight) - { - Bitmap bmp = GetLeftArrowBitmap(); - // paint the border around this bitmap if this is the case - // - /* - if (overLeftArrow) - { - Debug.Assert(!downLeftArrow, "can both of those happen?"); - PaintOverButton(g, bounds); - layout.leftArrow.Inflate(-1,-1); - } - */ - if (downLeftArrow) - { - PaintDownButton(g, bounds); - layout.leftArrow.Inflate(-1, -1); - lock (bmp) - { - PaintBitmap(g, bmp, bounds); - } - layout.leftArrow.Inflate(1, 1); - } - else - { - lock (bmp) - { - PaintBitmap(g, bmp, bounds); - } - } - } - - private void PaintRightArrow(Graphics g, Rectangle bounds, bool alignToRight) - { - Bitmap bmp = GetRightArrowBitmap(); - // paint the border around this bitmap if this is the case - // - /* - if (overRightArrow) - { - Debug.Assert(!downRightArrow, "can both of those happen?"); - PaintOverButton(g, bounds); - layout.rightArrow.Inflate(-1,-1); - } - */ - if (downRightArrow) - { - PaintDownButton(g, bounds); - layout.rightArrow.Inflate(-1, -1); - lock (bmp) - { - PaintBitmap(g, bmp, bounds); - } - layout.rightArrow.Inflate(1, 1); - } - else - { - lock (bmp) - { - PaintBitmap(g, bmp, bounds); - } - } - } - - private int PaintRow(Graphics g, Rectangle bounds, int row, Font font, bool alignToRight, - int tableNameBoxWidth, int[] colsNameWidths, int[] colsDataWidths) - { - DataGridState dgs = (DataGridState)parents[row]; - Rectangle paintBounds = bounds; - Rectangle rowBounds = bounds; - paintBounds.Height = (int)rowHeights[row]; - rowBounds.Height = (int)rowHeights[row]; - - int paintedWidth = 0; - // used for scrolling: when paiting, we will skip horizOffset cells in the dataGrid ParentRows - int skippedCells = 0; - - // paint the table name - if (dataGrid.ParentRowsLabelStyle == DataGridParentRowsLabelStyle.TableName || - dataGrid.ParentRowsLabelStyle == DataGridParentRowsLabelStyle.Both) - { - if (skippedCells < horizOffset) - { - // skip this - skippedCells++; - } - else - { - paintBounds.Width = Math.Min(paintBounds.Width, tableNameBoxWidth); - paintBounds.X = MirrorRect(bounds, paintBounds, alignToRight); - string displayTableName = dgs.ListManager.GetListName() + ": "; - PaintText(g, paintBounds, displayTableName, font, true, alignToRight); // true is for painting bold - paintedWidth += paintBounds.Width; - } - } - - if (paintedWidth >= bounds.Width) - { - return bounds.Width; // we painted everything - } - - rowBounds.Width -= paintedWidth; - rowBounds.X += alignToRight ? 0 : paintedWidth; - paintedWidth += PaintColumns(g, rowBounds, dgs, font, alignToRight, colsNameWidths, colsDataWidths, skippedCells); - - // paint the possible space left after columns - if (paintedWidth < bounds.Width) - { - paintBounds.X = bounds.X + paintedWidth; - paintBounds.Width = bounds.Width - paintedWidth; - paintBounds.X = MirrorRect(bounds, paintBounds, alignToRight); - g.FillRectangle(BackBrush, paintBounds); - } - return paintedWidth; - } - - private int PaintColumns(Graphics g, Rectangle bounds, DataGridState dgs, Font font, bool alignToRight, - int[] colsNameWidths, int[] colsDataWidths, int skippedCells) - { - Rectangle paintBounds = bounds; - Rectangle rowBounds = bounds; - GridColumnStylesCollection cols = dgs.GridColumnStyles; - int cx = 0; - - for (int i = 0; i < cols.Count; i++) - { - if (cx >= bounds.Width) - { - break; - } - - // paint the column name, if we have to - if (dataGrid.ParentRowsLabelStyle == DataGridParentRowsLabelStyle.ColumnName || - dataGrid.ParentRowsLabelStyle == DataGridParentRowsLabelStyle.Both) - { - if (skippedCells < horizOffset) - { - // skip this column - } - else - { - paintBounds.X = bounds.X + cx; - paintBounds.Width = Math.Min(bounds.Width - cx, colsNameWidths[i]); - paintBounds.X = MirrorRect(bounds, paintBounds, alignToRight); - - string colName = cols[i].HeaderText + ": "; - PaintText(g, paintBounds, colName, font, false, alignToRight); // false is for not painting bold - - cx += paintBounds.Width; - } - } - - if (cx >= bounds.Width) - { - break; - } - - if (skippedCells < horizOffset) - { - // skip this cell - skippedCells++; - } - else - { - // paint the cell contents - paintBounds.X = bounds.X + cx; - paintBounds.Width = Math.Min(bounds.Width - cx, colsDataWidths[i]); - paintBounds.X = MirrorRect(bounds, paintBounds, alignToRight); - - // when we paint the data grid parent rows, we want to paint the data at the position - // stored in the currency manager. - cols[i].Paint(g, paintBounds, (CurrencyManager)dataGrid.BindingContext[dgs.DataSource, dgs.DataMember], - dataGrid.BindingContext[dgs.DataSource, dgs.DataMember].Position, BackBrush, ForeBrush, alignToRight); - - cx += paintBounds.Width; - - // draw the line to the right (or left, according to alignRight) - // - g.DrawLine(new Pen(SystemColors.ControlDark), - alignToRight ? paintBounds.X : paintBounds.Right, - paintBounds.Y, - alignToRight ? paintBounds.X : paintBounds.Right, - paintBounds.Bottom); - - // this is how wide the line is.... - cx++; - - // put 3 pixels in between columns - // see DonnaWa - // - if (i < cols.Count - 1) - { - paintBounds.X = bounds.X + cx; - paintBounds.Width = Math.Min(bounds.Width - cx, 3); - paintBounds.X = MirrorRect(bounds, paintBounds, alignToRight); - - g.FillRectangle(BackBrush, paintBounds); - cx += 3; - } - } - } - - return cx; - } - - /// - /// Draws on the screen the text. It is used only to paint the Table Name and the column Names - /// Returns the width of bounding rectangle that was passed in - /// - private int PaintText(Graphics g, Rectangle textBounds, string text, Font font, bool bold, bool alignToRight) - { - Font textFont = font; - if (bold) - { - try - { - textFont = new Font(font, FontStyle.Bold); - } - catch { } - } - else - { - textFont = font; - } - - // right now, we paint the entire box, cause it will be used anyway - g.FillRectangle(BackBrush, textBounds); - StringFormat format = new StringFormat(); - if (alignToRight) - { - format.FormatFlags |= StringFormatFlags.DirectionRightToLeft; - format.Alignment = StringAlignment.Far; - } - format.FormatFlags |= StringFormatFlags.NoWrap; - // part 1, section 3: put the table and the column name in the - // parent rows at the same height as the dataGridTextBoxColumn draws the string - // - textBounds.Offset(0, 2); - textBounds.Height -= 2; - g.DrawString(text, textFont, ForeBrush, textBounds, format); - format.Dispose(); - return textBounds.Width; - - } - - // will return the X coordinate of the containedRect mirrored within the surroundingRect - // according to the value of alignToRight - private int MirrorRect(Rectangle surroundingRect, Rectangle containedRect, bool alignToRight) - { - Debug.Assert(containedRect.X >= surroundingRect.X && containedRect.Right <= surroundingRect.Right, "containedRect is not contained in surroundingRect"); - if (alignToRight) - { - return surroundingRect.Right - containedRect.Right + surroundingRect.X; - } - else - { - return containedRect.X; - } - } - - private class Layout - { - public Rectangle data; - public Rectangle leftArrow; - public Rectangle rightArrow; - - public Layout() - { - data = Rectangle.Empty; - leftArrow = Rectangle.Empty; - rightArrow = Rectangle.Empty; - } - - public override string ToString() - { - StringBuilder sb = new StringBuilder(200); - sb.Append("ParentRows Layout: \n"); - sb.Append("data = "); - sb.Append(data.ToString()); - sb.Append("\n leftArrow = "); - sb.Append(leftArrow.ToString()); - sb.Append("\n rightArrow = "); - sb.Append(rightArrow.ToString()); - sb.Append("\n"); - - return sb.ToString(); - } - } - - [ComVisible(true)] - protected internal class DataGridParentRowsAccessibleObject : AccessibleObject - { - readonly DataGridParentRows owner = null; - - public DataGridParentRowsAccessibleObject(DataGridParentRows owner) : base() - { - Debug.Assert(owner != null, "DataGridParentRowsAccessibleObject must have a valid owner"); - this.owner = owner; - } - - internal DataGridParentRows Owner - { - get - { - return owner; - } - } - - public override Rectangle Bounds - { - get - { - return owner.dataGrid.RectangleToScreen(owner.dataGrid.ParentRowsBounds); - } - } - - public override string DefaultAction - { - get - { - return SR.AccDGNavigateBack; - } - } - - public override string Name - { - get - { - return SR.AccDGParentRows; - } - } - - public override AccessibleObject Parent - { - get - { - return owner.dataGrid.AccessibilityObject; - } - } - - public override AccessibleRole Role - { - get - { - return AccessibleRole.List; - } - } - - public override AccessibleStates State - { - get - { - AccessibleStates state = AccessibleStates.ReadOnly; - - if (owner.parentsCount == 0) - { - state |= AccessibleStates.Invisible; - } - if (owner.dataGrid.ParentRowsVisible) - { - state |= AccessibleStates.Expanded; - } - else - { - state |= AccessibleStates.Collapsed; - } - - return state; - } - } - - public override string Value - { - get - { - return null; - } - } - - public override void DoDefaultAction() - { - owner.dataGrid.NavigateBack(); - } - - public override AccessibleObject GetChild(int index) - { - return ((DataGridState)owner.parents[index]).ParentRowAccessibleObject; - } - - public override int GetChildCount() - { - return owner.parentsCount; - } - - /// - /// Returns the currently focused child, if any. - /// Returns this if the object itself is focused. - /// - public override AccessibleObject GetFocused() - { - return null; - } - - internal AccessibleObject GetNext(AccessibleObject child) - { - int children = GetChildCount(); - bool hit = false; - - for (int i = 0; i < children; i++) - { - if (hit) - { - return GetChild(i); - } - if (GetChild(i) == child) - { - hit = true; - } - } - - return null; - } - - internal AccessibleObject GetPrev(AccessibleObject child) - { - int children = GetChildCount(); - bool hit = false; - - for (int i = children - 1; i >= 0; i--) - { - if (hit) - { - return GetChild(i); - } - if (GetChild(i) == child) - { - hit = true; - } - } - - return null; - } - - /// - /// Navigate to the next or previous grid entry. - /// - public override AccessibleObject Navigate(AccessibleNavigation navdir) - { - switch (navdir) - { - case AccessibleNavigation.Right: - case AccessibleNavigation.Next: - case AccessibleNavigation.Down: - return Parent.GetChild(1); - case AccessibleNavigation.Up: - case AccessibleNavigation.Left: - case AccessibleNavigation.Previous: - return Parent.GetChild(GetChildCount() - 1); - case AccessibleNavigation.FirstChild: - if (GetChildCount() > 0) - { - return GetChild(0); - } - break; - case AccessibleNavigation.LastChild: - if (GetChildCount() > 0) - { - return GetChild(GetChildCount() - 1); - } - break; - - } - - return null; - - } - - public override void Select(AccessibleSelection flags) - { - } - } - } -} - diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridParentRowsLabel.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridParentRowsLabel.cs deleted file mode 100644 index 210192dc28d..00000000000 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridParentRowsLabel.cs +++ /dev/null @@ -1,34 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System.Windows.Forms -{ - /// - /// Specifies how parent row labels of a DataGrid - /// control are displayed. - /// - public enum DataGridParentRowsLabelStyle - { - /// - /// Display no parent row labels. - /// - None = 0, - - /// - /// Displaya the parent table name. - /// - TableName = 1, - - /// - /// Displaya the parent column name. - /// - ColumnName = 2, - - /// - /// Displays - /// both the parent table and column names. - /// - Both = 3, - } -} diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridRelationshipRow.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridRelationshipRow.cs deleted file mode 100644 index a6ec4af7fb9..00000000000 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridRelationshipRow.cs +++ /dev/null @@ -1,1273 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Collections; -using System.ComponentModel; -using System.Diagnostics; -using System.Drawing; -using System.Globalization; -using System.Runtime.InteropServices; - -namespace System.Windows.Forms -{ - /// - /// This class fully encapsulates the painting logic for a row - /// appearing in a DataGrid. - /// - internal class DataGridRelationshipRow : DataGridRow - { - private const bool defaultOpen = false; - private const int expandoBoxWidth = 14; - private const int indentWidth = 20; - // private const int relationshipSpacing = 1; - private const int triangleSize = 5; - - private bool expanded = defaultOpen; - // private bool hasRelationships = false; - // private Font linkFont = null; - // private new DataGrid dataGrid; // Currently used only to obtain a Graphics object for measuring text - - // private Rectangle relationshipRect = Rectangle.Empty; - // private int relationshipHeight = 0; - - // relationships - // we should get this directly from the dgTable. - // private ArrayList relationships; - // private int focusedRelation = -1; - // private int focusedTextWidth; - - public DataGridRelationshipRow(DataGrid dataGrid, DataGridTableStyle dgTable, int rowNumber) - : base(dataGrid, dgTable, rowNumber) - { - // this.dataGrid = dataGrid; - // linkFont = dataGrid.LinkFont; - // relationshipHeight = dataGrid.LinkFontHeight + this.dgTable.relationshipSpacing; - - // if (DataGrid.AllowNavigation) { - // hasRelationships = dgTable.RelationsList.Count > 0; - // } - } - - internal protected override int MinimumRowHeight(GridColumnStylesCollection cols) - { - /* - if (DataGrid != null && DataGrid.LinkFontHeight + this.dgTable.relationshipSpacing != relationshipHeight) { - relationshipRect = Rectangle.Empty; - relationshipHeight = DataGrid.LinkFontHeight + this.dgTable.relationshipSpacing; - } - */ - - return base.MinimumRowHeight(cols) + (expanded ? GetRelationshipRect().Height : 0); - } - - internal protected override int MinimumRowHeight(DataGridTableStyle dgTable) - { - /* - if (DataGrid != null && DataGrid.LinkFontHeight + this.dgTable.relationshipSpacing != relationshipHeight) { - relationshipRect = Rectangle.Empty; - relationshipHeight = DataGrid.LinkFontHeight + this.dgTable.relationshipSpacing; - } - */ - - return base.MinimumRowHeight(dgTable) + (expanded ? GetRelationshipRect().Height : 0); - } - - // =------------------------------------------------------------------ - // = Properties - // =------------------------------------------------------------------ - - public virtual bool Expanded - { - get - { - return expanded; - } - set - { - if (expanded == value) - { - return; - } - - if (expanded) - { - Collapse(); - } - else - { - Expand(); - } - } - } - - /* - private Color BorderColor { - get { - if (DataGrid == null) - return Color.Empty; - return DataGrid.GridLineColor; - } - } - */ - -#if FALSE - private int BorderWidth { - get { - DataGrid dataGrid = this.DataGrid; - if (dataGrid == null) - return 0; - // if the user set the GridLineStyle property on the dataGrid. - // then use the value of that property - DataGridLineStyle gridStyle; - int gridLineWidth; - if (this.dgTable.IsDefault) { - gridStyle = this.DataGrid.GridLineStyle; - gridLineWidth = this.DataGrid.GridLineWidth; - } else { - gridStyle = this.dgTable.GridLineStyle; - gridLineWidth = this.dgTable.GridLineWidth; - } - - if (gridStyle == DataGridLineStyle.None) - return 0; - - return gridLineWidth; - } - } -#endif //FALSE - - private int FocusedRelation - { - get - { - return dgTable.FocusedRelation; - } - set - { - dgTable.FocusedRelation = value; - } - } - - // =------------------------------------------------------------------ - // = Methods - // =------------------------------------------------------------------ - - private void Collapse() - { - Debug.Assert(dgTable.DataGrid.AllowNavigation, "how can the user collapse the relations if the grid does not allow navigation?"); - if (expanded) - { - expanded = false; - // relationshipRect = Rectangle.Empty; - FocusedRelation = -1; - DataGrid.OnRowHeightChanged(this); - } - } - - protected override AccessibleObject CreateAccessibleObject() - { - return new DataGridRelationshipRowAccessibleObject(this); - } - - private void Expand() - { - Debug.Assert(dgTable.DataGrid.AllowNavigation, "how can the user expand the relations if the grid does not allow navigation?"); - if (expanded == false - && DataGrid != null - && dgTable != null - && dgTable.RelationsList.Count > 0) - { - expanded = true; - FocusedRelation = -1; - - // relationshipRect = Rectangle.Empty; - DataGrid.OnRowHeightChanged(this); - } - } - - public override int Height - { - get - { - int height = base.Height; - if (expanded) - { - return height + GetRelationshipRect().Height; - } - else - { - return height; - } - } - set - { - // we should use the RelationshipRect only when the row is expanded - if (expanded) - { - base.Height = value - GetRelationshipRect().Height; - } - else - { - base.Height = value; - } - } - } - - // so the edit box will not paint under the - // grid line of the row - public override Rectangle GetCellBounds(int col) - { - Rectangle cellBounds = base.GetCellBounds(col); - // decrement base.Height by 1, so the edit box will not - // paint over the bottom line. - cellBounds.Height = base.Height - 1; - return cellBounds; - } - - /// - /// Given an origin, this procedure returns - /// a rectangle that describes the location of an outline box. - /// - private Rectangle GetOutlineRect(int xOrigin, int yOrigin) - { - Rectangle outline = new Rectangle(xOrigin + 2, - yOrigin + 2, - 9, - 9); - return outline; - } - - public override Rectangle GetNonScrollableArea() - { - if (expanded) - { - return GetRelationshipRect(); - } - else - { - return Rectangle.Empty; - } - } - - private Rectangle GetRelationshipRect() - { - Debug.Assert(expanded, "we should need this rectangle only when the row is expanded"); - Rectangle ret = dgTable.RelationshipRect; - ret.Y = base.Height - dgTable.BorderWidth; - return ret; - } - -#if FALSE - private Rectangle GetRelationshipRect() { - if (relationshipRect.IsEmpty) { - Debug.WriteLineIf(CompModSwitches.DGRelationShpRowLayout.TraceVerbose, "GetRelationshipRect grinding away"); - if (!expanded) { - return(relationshipRect = new Rectangle(0,0,0,0)); - } - Graphics g = DataGrid.CreateGraphicsInternal(); - relationshipRect = new Rectangle(); - relationshipRect.X = 0; //indentWidth; - relationshipRect.Y = base.Height - this.dgTable.BorderWidth; - - // Determine the width of the widest relationship name - int longestRelationship = 0; - for (int r = 0; r < this.dgTable.RelationsList.Count; ++r) { - int rwidth = (int) Math.Ceiling(g.MeasureString(((string) this.dgTable.RelationsList[r]), this.DataGrid.LinkFont).Width); - if (rwidth > longestRelationship) - longestRelationship = rwidth; - } - - g.Dispose(); - - relationshipRect.Width = longestRelationship + 5; - relationshipRect.Width += 2; // relationshipRect border; - relationshipRect.Height = this.dgTable.BorderWidth + relationshipHeight * this.dgTable.RelationsList.Count; - relationshipRect.Height += 2; // relationship border - if (this.dgTable.RelationsList.Count > 0) - relationshipRect.Height += 2 * System.Windows.Forms.DataGridTableStyle.relationshipSpacing; - } - return relationshipRect; - } - -#endif// FALSE - - private Rectangle GetRelationshipRectWithMirroring() - { - Rectangle relRect = GetRelationshipRect(); - bool rowHeadersVisible = dgTable.IsDefault ? DataGrid.RowHeadersVisible : dgTable.RowHeadersVisible; - if (rowHeadersVisible) - { - int rowHeaderWidth = dgTable.IsDefault ? DataGrid.RowHeaderWidth : dgTable.RowHeaderWidth; - relRect.X += DataGrid.GetRowHeaderRect().X + rowHeaderWidth; - } - relRect.X = MirrorRelationshipRectangle(relRect, DataGrid.GetRowHeaderRect(), DataGrid.RightToLeft == RightToLeft.Yes); - return relRect; - } - - /// - /// Called by the DataGrid when a click occurs in the row's client - /// area. The coordinates are normalized to the rectangle's top - /// left point. - /// - private bool PointOverPlusMinusGlyph(int x, int y, Rectangle rowHeaders, bool alignToRight) - { - if (dgTable == null || dgTable.DataGrid == null || !dgTable.DataGrid.AllowNavigation) - { - return false; - } - - Rectangle insideRowHeaders = rowHeaders; - if (!DataGrid.FlatMode) - { - insideRowHeaders.Inflate(-1, -1); - } - - Rectangle outline = GetOutlineRect(insideRowHeaders.Right - expandoBoxWidth, 0); - - outline.X = MirrorRectangle(outline.X, outline.Width, insideRowHeaders, alignToRight); - - return outline.Contains(x, y); - } - - public override bool OnMouseDown(int x, int y, Rectangle rowHeaders, bool alignToRight) - { - bool rowHeadersVisible = dgTable.IsDefault ? DataGrid.RowHeadersVisible : dgTable.RowHeadersVisible; - if (rowHeadersVisible) - { - if (PointOverPlusMinusGlyph(x, y, rowHeaders, alignToRight)) - { - if (dgTable.RelationsList.Count == 0) - { - return false; - } - else if (expanded) - { - Collapse(); - } - else - { - Expand(); - } - DataGrid.OnNodeClick(EventArgs.Empty); - return true; - } - } - - if (!expanded) - { - return base.OnMouseDown(x, y, rowHeaders, alignToRight); - } - - // hit test for relationships - Rectangle relRect = GetRelationshipRectWithMirroring(); - - if (relRect.Contains(x, y)) - { - int r = RelationFromY(y); - if (r != -1) - { - // first, reset the FocusedRelation - FocusedRelation = -1; - DataGrid.NavigateTo(((string)dgTable.RelationsList[r]), this, true); - } - // DataGrid.OnLinkClick(EventArgs.Empty); - return true; - } - - return base.OnMouseDown(x, y, rowHeaders, alignToRight); - } - - public override bool OnMouseMove(int x, int y, Rectangle rowHeaders, bool alignToRight) - { - if (!expanded) - { - return false; - } - - Rectangle relRect = GetRelationshipRectWithMirroring(); - - if (relRect.Contains(x, y)) - { - DataGrid.Cursor = Cursors.Hand; - return true; - } - - DataGrid.Cursor = Cursors.Default; - return base.OnMouseMove(x, y, rowHeaders, alignToRight); - } - - // this function will not invalidate all of the - // row - public override void OnMouseLeft(Rectangle rowHeaders, bool alignToRight) - { - if (!expanded) - { - return; - } - - Rectangle relRect = GetRelationshipRect(); - relRect.X += rowHeaders.X + dgTable.RowHeaderWidth; - relRect.X = MirrorRelationshipRectangle(relRect, rowHeaders, alignToRight); - - if (FocusedRelation != -1) - { - InvalidateRowRect(relRect); - FocusedRelation = -1; - } - } - - public override void OnMouseLeft() - { - if (!expanded) - { - return; - } - - if (FocusedRelation != -1) - { - InvalidateRow(); - FocusedRelation = -1; - } - base.OnMouseLeft(); - } - - /// - /// Called by the DataGrid when a keypress occurs on a row with "focus." - /// - public override bool OnKeyPress(Keys keyData) - { - // ignore the shift key if it is not paired w/ the TAB key - if ((keyData & Keys.Modifiers) == Keys.Shift && (keyData & Keys.KeyCode) != Keys.Tab) - { - return false; - } - - switch (keyData & Keys.KeyCode) - { - case Keys.F5: - if (dgTable == null || dgTable.DataGrid == null || !dgTable.DataGrid.AllowNavigation) - { - return false; - } - - if (expanded) - { - Collapse(); - } - else - { - Expand(); - } - - FocusedRelation = -1; - return true; - - // to make the gridTest run w/ the numLock key on - // - case Keys.NumLock: - if (FocusedRelation != -1) - { - return false; - } - else - { - return base.OnKeyPress(keyData); - } - - case Keys.Enter: - if (FocusedRelation != -1) - { - // somebody set the relation number up already - // navigate to the relation - DataGrid.NavigateTo(((string)dgTable.RelationsList[FocusedRelation]), this, true); - - // now reset the FocusedRelation - FocusedRelation = -1; - return true; - } - else - { - return false; - } - - case Keys.Tab: - return false; - - default: - FocusedRelation = -1; - return base.OnKeyPress(keyData); - } - } - - // will reset the FocusedRelation and will invalidate the - // rectangle so that the linkFont is no longer shown - internal override void LoseChildFocus(Rectangle rowHeaders, bool alignToRight) - { - // we only invalidate stuff if the row is expanded. - if (FocusedRelation == -1 || !expanded) - { - return; - } - - FocusedRelation = -1; - Rectangle relRect = GetRelationshipRect(); - relRect.X += rowHeaders.X + dgTable.RowHeaderWidth; - relRect.X = MirrorRelationshipRectangle(relRect, rowHeaders, alignToRight); - InvalidateRowRect(relRect); - } - - // here is the logic for FOCUSED: - // - // first the dataGrid gets the KeyPress. - // the dataGrid passes it to the currentRow. if it is anything other - // than Enter or TAB, the currentRow resets the FocusedRelation variable. - // - // Then the dataGrid takes another look at the TAB key and if it is the case - // it passes it to the row. If the dataRelationshipRow can become focused, - // then it eats the TAB key, otherwise it will give it back to the dataGrid. - // - internal override bool ProcessTabKey(Keys keyData, Rectangle rowHeaders, bool alignToRight) - { - Debug.Assert((keyData & Keys.Control) != Keys.Control, "the DataGridRelationshipRow only handles TAB and TAB-SHIFT"); - Debug.Assert((keyData & Keys.Alt) != Keys.Alt, "the DataGridRelationshipRow only handles TAB and TAB-SHIFT"); - - // if there are no relationships, this row can't do anything with the - // key - if (dgTable.RelationsList.Count == 0 || dgTable.DataGrid == null || !dgTable.DataGrid.AllowNavigation) - { - return false; - } - - // expand the relationship box - if (!expanded) - { - Expand(); - } - - if ((keyData & Keys.Shift) == Keys.Shift) - { - if (FocusedRelation == 0) - { - // if user hits TAB-SHIFT and the focus was on the first relationship then - // reset FocusedRelation and let the dataGrid use the key - // - // consider: Microsoft: if the relationships box is expanded, should we collapse it on leave? - FocusedRelation = -1; - return false; - } - - // we need to invalidate the relationshipRectangle, and cause the linkFont to move - // to the next relation - Rectangle relRect = GetRelationshipRect(); - relRect.X += rowHeaders.X + dgTable.RowHeaderWidth; - relRect.X = MirrorRelationshipRectangle(relRect, rowHeaders, alignToRight); - InvalidateRowRect(relRect); - - if (FocusedRelation == -1) - { - // is the first time that the user focuses on this - // set of relationships - FocusedRelation = dgTable.RelationsList.Count - 1; - } - else - { - FocusedRelation--; - } - - return true; - } - else - { - if (FocusedRelation == dgTable.RelationsList.Count - 1) - { - // if the user hits TAB and the focus was on the last relationship then - // reset FocusedRelation and let the dataGrid use the key - // - // consider: Microsoft: if the relationships box is expanded, should we collapse it on leave? - FocusedRelation = -1; - return false; - } - - // we need to invalidate the relationshipRectangle, and cause the linkFont to move - // to the next relation - Rectangle relRect = GetRelationshipRect(); - relRect.X += rowHeaders.X + dgTable.RowHeaderWidth; - relRect.X = MirrorRelationshipRectangle(relRect, rowHeaders, alignToRight); - InvalidateRowRect(relRect); - - FocusedRelation++; - return true; - } - } - - /// - /// Paints the row. - /// - public override int Paint(Graphics g, Rectangle bounds, Rectangle trueRowBounds, int firstVisibleColumn, int numVisibleColumns) - { - return Paint(g, bounds, trueRowBounds, firstVisibleColumn, numVisibleColumns, false); - } - - public override int Paint(Graphics g, - Rectangle bounds, // negative offsetted row bounds - Rectangle trueRowBounds, // real row bounds. - int firstVisibleColumn, - int numVisibleColumns, - bool alignToRight) - { - if (CompModSwitches.DGRelationShpRowPaint.TraceVerbose) - { - Debug.WriteLine("Painting row " + RowNumber.ToString(CultureInfo.InvariantCulture) + " with bounds " + bounds.ToString()); - } - - int bWidth = dgTable.BorderWidth; - - // paint the data cells - Rectangle dataBounds = bounds; - dataBounds.Height = base.Height - bWidth; - int dataWidth = PaintData(g, dataBounds, firstVisibleColumn, numVisibleColumns, alignToRight); - int dataWidthOffsetted = dataWidth + bounds.X - trueRowBounds.X; - - dataBounds.Offset(0, bWidth); // use bWidth, not 1 - if (bWidth > 0) - { - PaintBottomBorder(g, dataBounds, dataWidth, bWidth, alignToRight); - } - - if (expanded && dgTable.RelationsList.Count > 0) - { - // paint the relationships - Rectangle relationBounds = new Rectangle(trueRowBounds.X, - dataBounds.Bottom, - trueRowBounds.Width, - trueRowBounds.Height - dataBounds.Height - 2 * bWidth); - PaintRelations(g, relationBounds, trueRowBounds, dataWidthOffsetted, - firstVisibleColumn, numVisibleColumns, alignToRight); - relationBounds.Height += 1; - if (bWidth > 0) - { - PaintBottomBorder(g, relationBounds, dataWidthOffsetted, bWidth, alignToRight); - } - } - - return dataWidth; - } - - protected override void PaintCellContents(Graphics g, Rectangle cellBounds, DataGridColumnStyle column, - Brush backBr, Brush foreBrush, bool alignToRight) - { - CurrencyManager listManager = DataGrid.ListManager; - - // painting the error.. - // - string errString = string.Empty; - Rectangle bounds = cellBounds; - object errInfo = DataGrid.ListManager[number]; - if (errInfo is IDataErrorInfo) - { - errString = ((IDataErrorInfo)errInfo)[column.PropertyDescriptor.Name]; - } - - if (!string.IsNullOrEmpty(errString)) - { - Bitmap bmp = GetErrorBitmap(); - Rectangle errRect; - lock (bmp) - { - errRect = PaintIcon(g, bounds, true, alignToRight, bmp, backBr); - } - // paint the errors correctly when RTL = true - if (alignToRight) - { - bounds.Width -= errRect.Width + xOffset; - } - else - { - bounds.X += errRect.Width + xOffset; - } - - DataGrid.ToolTipProvider.AddToolTip(errString, (IntPtr)(DataGrid.ToolTipId++), errRect); - } - - column.Paint(g, bounds, listManager, RowNumber, backBr, foreBrush, alignToRight); - } - - public override void PaintHeader(Graphics g, Rectangle bounds, bool alignToRight, bool isDirty) - { - DataGrid grid = DataGrid; - - Rectangle insideBounds = bounds; - - if (!grid.FlatMode) - { - ControlPaint.DrawBorder3D(g, insideBounds, Border3DStyle.RaisedInner); - insideBounds.Inflate(-1, -1); - } - - if (dgTable.IsDefault) - { - PaintHeaderInside(g, insideBounds, DataGrid.HeaderBackBrush, alignToRight, isDirty); - } - else - { - PaintHeaderInside(g, insideBounds, dgTable.HeaderBackBrush, alignToRight, isDirty); - } - } - - public void PaintHeaderInside(Graphics g, Rectangle bounds, Brush backBr, bool alignToRight, bool isDirty) - { - // paint the row header - bool paintPlusMinus = dgTable.RelationsList.Count > 0 && dgTable.DataGrid.AllowNavigation; - int rowHeaderBoundsX = MirrorRectangle(bounds.X, - bounds.Width - (paintPlusMinus ? expandoBoxWidth : 0), - bounds, alignToRight); - - if (!alignToRight) - { - Debug.Assert(bounds.X == rowHeaderBoundsX, "what's up doc?"); - } - - Rectangle rowHeaderBounds = new Rectangle(rowHeaderBoundsX, - bounds.Y, - bounds.Width - (paintPlusMinus ? expandoBoxWidth : 0), - bounds.Height); - - base.PaintHeader(g, rowHeaderBounds, alignToRight, isDirty); - - // Paint the expando on the right - int expandoBoxX = MirrorRectangle(bounds.X + rowHeaderBounds.Width, expandoBoxWidth, bounds, alignToRight); - - if (!alignToRight) - { - Debug.Assert(rowHeaderBounds.Right == expandoBoxX, "what's up doc?"); - } - - Rectangle expandoBox = new Rectangle(expandoBoxX, - bounds.Y, - expandoBoxWidth, - bounds.Height); - if (paintPlusMinus) - { - PaintPlusMinusGlyph(g, expandoBox, backBr, alignToRight); - } - - } - - /// - /// Paints the relationships below the data area. - /// - private void PaintRelations(Graphics g, Rectangle bounds, Rectangle trueRowBounds, - int dataWidth, int firstCol, int nCols, bool alignToRight) - { - // Calculate the relationship rect. - // relationshipRect = Rectangle.Empty; - Rectangle relRect = GetRelationshipRect(); - //relRect.Offset(trueRowBounds.X, trueRowBounds.Y); - relRect.X = alignToRight ? bounds.Right - relRect.Width : bounds.X; - relRect.Y = bounds.Y; - int paintedWidth = Math.Max(dataWidth, relRect.Width); - - // Paint the stuff to the right , or left (Bi-Di) of the relationship rect. - Region r = g.Clip; - g.ExcludeClip(relRect); - - g.FillRectangle(GetBackBrush(), - alignToRight ? bounds.Right - dataWidth : bounds.X, - bounds.Y, - dataWidth, - bounds.Height); - - // Paint the relations' text - g.SetClip(bounds); - - relRect.Height -= dgTable.BorderWidth; // use bWidth not 1 - g.DrawRectangle(SystemPens.ControlText, relRect.X, relRect.Y, relRect.Width - 1, relRect.Height - 1); - relRect.Inflate(-1, -1); - - int cy = PaintRelationText(g, relRect, alignToRight); - - if (cy < relRect.Height) - { - g.FillRectangle(GetBackBrush(), relRect.X, relRect.Y + cy, relRect.Width, relRect.Height - cy); - } - - g.Clip = r; - - // paint any exposed area to the right or to the left (BI-DI) - if (paintedWidth < bounds.Width) - { - int bWidth; - if (dgTable.IsDefault) - { - bWidth = DataGrid.GridLineWidth; - } - else - { - bWidth = dgTable.GridLineWidth; - } - - g.FillRectangle(DataGrid.BackgroundBrush, - alignToRight ? bounds.X : bounds.X + paintedWidth, - bounds.Y, - bounds.Width - paintedWidth - bWidth + 1, // + 1 cause the relationship rectangle was deflated - bounds.Height); - - // Paint the border to the right of each cell - if (bWidth > 0) - { - Brush br; - // if the user changed the gridLineColor on the dataGrid - // from the defaultValue, then use that value; - if (dgTable.IsDefault) - { - br = DataGrid.GridLineBrush; - } - else - { - br = dgTable.GridLineBrush; - } - - g.FillRectangle(br, - alignToRight ? bounds.Right - bWidth - paintedWidth : bounds.X + paintedWidth - bWidth, - bounds.Y, - bWidth, - bounds.Height); - } - } - - } - - private int PaintRelationText(Graphics g, Rectangle bounds, bool alignToRight) - { - g.FillRectangle(GetBackBrush(), bounds.X, bounds.Y, bounds.Width, System.Windows.Forms.DataGridTableStyle.relationshipSpacing); - - int relationshipHeight = dgTable.RelationshipHeight; - Rectangle textBounds = new Rectangle(bounds.X, bounds.Y + System.Windows.Forms.DataGridTableStyle.relationshipSpacing, - bounds.Width, - relationshipHeight); - int cy = System.Windows.Forms.DataGridTableStyle.relationshipSpacing; - for (int r = 0; r < dgTable.RelationsList.Count; ++r) - { - if (cy > bounds.Height) - { - break; - } - - Brush textBrush = dgTable.IsDefault ? DataGrid.LinkBrush : dgTable.LinkBrush; - - Font textFont = DataGrid.Font; - textBrush = dgTable.IsDefault ? DataGrid.LinkBrush : dgTable.LinkBrush; - textFont = DataGrid.LinkFont; - - g.FillRectangle(GetBackBrush(), textBounds); - - StringFormat format = new StringFormat(); - if (alignToRight) - { - format.FormatFlags |= StringFormatFlags.DirectionRightToLeft; - format.Alignment = StringAlignment.Far; - } - g.DrawString(((string)dgTable.RelationsList[r]), textFont, textBrush, textBounds, - format); - if (r == FocusedRelation && number == DataGrid.CurrentCell.RowNumber) - { - textBounds.Width = dgTable.FocusedTextWidth; - ControlPaint.DrawFocusRectangle(g, textBounds, ((SolidBrush)textBrush).Color, ((SolidBrush)GetBackBrush()).Color); - textBounds.Width = bounds.Width; - } - format.Dispose(); - - textBounds.Y += relationshipHeight; - cy += textBounds.Height; - } - return cy; - } - - private void PaintPlusMinusGlyph(Graphics g, Rectangle bounds, Brush backBr, bool alignToRight) - { - if (CompModSwitches.DGRelationShpRowPaint.TraceVerbose) - { - Debug.WriteLine("PlusMinusGlyph painting in bounds -> " + bounds.ToString()); - } - - Rectangle outline = GetOutlineRect(bounds.X, bounds.Y); - - outline = Rectangle.Intersect(bounds, outline); - if (outline.IsEmpty) - { - return; - } - - g.FillRectangle(backBr, bounds); - - if (CompModSwitches.DGRelationShpRowPaint.TraceVerbose) - { - Debug.WriteLine("Painting PlusMinusGlyph with outline -> " + outline.ToString()); - } - // draw the +/- box - Pen drawPen = dgTable.IsDefault ? DataGrid.HeaderForePen : dgTable.HeaderForePen; - g.DrawRectangle(drawPen, outline.X, outline.Y, outline.Width - 1, outline.Height - 1); - - int indent = 2; - // draw the - - g.DrawLine(drawPen, - outline.X + indent, outline.Y + outline.Width / 2, - outline.Right - indent - 1, outline.Y + outline.Width / 2); // -1 on the y coordinate - - if (!expanded) - { - // draw the vertical line to make + - g.DrawLine(drawPen, - outline.X + outline.Height / 2, outline.Y + indent, - outline.X + outline.Height / 2, outline.Bottom - indent - 1); // -1... hinting - } - else - { - Point[] points = new Point[3]; - points[0] = new Point(outline.X + outline.Height / 2, outline.Bottom); - - points[1] = new Point(points[0].X, bounds.Y + 2 * indent + base.Height); - - points[2] = new Point(alignToRight ? bounds.X : bounds.Right, - points[1].Y); - g.DrawLines(drawPen, points); - } - } - - private int RelationFromY(int y) - { - int relation = -1; - int relationshipHeight = dgTable.RelationshipHeight; - Rectangle relRect = GetRelationshipRect(); - int cy = base.Height - dgTable.BorderWidth + System.Windows.Forms.DataGridTableStyle.relationshipSpacing; - while (cy < relRect.Bottom) - { - if (cy > y) - { - break; - } - - cy += relationshipHeight; - relation++; - } - if (relation >= dgTable.RelationsList.Count) - { - return -1; - } - - return relation; - } - - // given the relRect and the rowHeader, this function will return the - // X coordinate of the relationship rectangle as it should appear on the screen - private int MirrorRelationshipRectangle(Rectangle relRect, Rectangle rowHeader, bool alignToRight) - { - if (alignToRight) - { - return rowHeader.X - relRect.Width; - } - else - { - return relRect.X; - } - } - - // given the X and Width of a rectangle R1 contained in rect, - // this will return the X coordinate of the rectangle that corresponds to R1 in Bi-Di transformation - private int MirrorRectangle(int x, int width, Rectangle rect, bool alignToRight) - { - if (alignToRight) - { - return rect.Right + rect.X - width - x; - } - else - { - return x; - } - } - - [ComVisible(true)] - protected class DataGridRelationshipRowAccessibleObject : DataGridRowAccessibleObject - { - public DataGridRelationshipRowAccessibleObject(DataGridRow owner) : base(owner) - { - } - - protected override void AddChildAccessibleObjects(IList children) - { - base.AddChildAccessibleObjects(children); - DataGridRelationshipRow row = (DataGridRelationshipRow)Owner; - if (row.dgTable.RelationsList != null) - { - for (int i = 0; i < row.dgTable.RelationsList.Count; i++) - { - children.Add(new DataGridRelationshipAccessibleObject(row, i)); - } - } - } - - private DataGridRelationshipRow RelationshipRow - { - get - { - return (DataGridRelationshipRow)Owner; - } - } - - public override string DefaultAction - { - get - { - if (RelationshipRow.dgTable.RelationsList.Count > 0) - { - if (RelationshipRow.Expanded) - { - return SR.AccDGCollapse; - } - else - { - return SR.AccDGExpand; - } - } - return null; - } - } - - public override AccessibleStates State - { - get - { - AccessibleStates state = base.State; - if (RelationshipRow.dgTable.RelationsList.Count > 0) - { - if (((DataGridRelationshipRow)Owner).Expanded) - { - state |= AccessibleStates.Expanded; - } - else - { - state |= AccessibleStates.Collapsed; - } - } - return state; - } - } - - public override void DoDefaultAction() - { - if (RelationshipRow.dgTable.RelationsList.Count > 0) - { - ((DataGridRelationshipRow)Owner).Expanded = !((DataGridRelationshipRow)Owner).Expanded; - } - } - - public override AccessibleObject GetFocused() - { - DataGridRelationshipRow row = (DataGridRelationshipRow)Owner; - int focusRel = row.dgTable.FocusedRelation; - if (focusRel == -1) - { - return base.GetFocused(); - } - else - { - return GetChild(GetChildCount() - row.dgTable.RelationsList.Count + focusRel); - } - } - } - - [ComVisible(true)] - protected class DataGridRelationshipAccessibleObject : AccessibleObject - { - readonly DataGridRelationshipRow owner = null; - readonly int relationship; - - public DataGridRelationshipAccessibleObject(DataGridRelationshipRow owner, int relationship) : base() - { - Debug.Assert(owner != null, "DataGridRelationshipAccessibleObject must have a valid owner DataGridRow"); - this.owner = owner; - this.relationship = relationship; - } - - public override Rectangle Bounds - { - get - { - Rectangle rowBounds = DataGrid.GetRowBounds(owner); - - Rectangle bounds = owner.Expanded ? owner.GetRelationshipRectWithMirroring() : Rectangle.Empty; - bounds.Y += owner.dgTable.RelationshipHeight * relationship; - bounds.Height = owner.Expanded ? owner.dgTable.RelationshipHeight : 0; // when the row is collapsed the height of the relationship object should be 0 - // GetRelationshipRectWithMirroring will use the row headers width - if (!owner.Expanded) - { - bounds.X += rowBounds.X; - } - - bounds.Y += rowBounds.Y; - - return owner.DataGrid.RectangleToScreen(bounds); - } - } - - public override string Name - { - get - { - return (string)owner.dgTable.RelationsList[relationship]; - } - } - - protected DataGridRelationshipRow Owner - { - get - { - return owner; - } - } - - public override AccessibleObject Parent - { - get - { - return owner.AccessibleObject; - } - } - - protected DataGrid DataGrid - { - get - { - return owner.DataGrid; - } - } - - public override AccessibleRole Role - { - get - { - return AccessibleRole.Link; - } - } - - public override AccessibleStates State - { - get - { - - DataGridRow[] dgRows = DataGrid.DataGridRows; - if (Array.IndexOf(dgRows, owner) == -1) - { - return AccessibleStates.Unavailable; - } - - AccessibleStates state = AccessibleStates.Selectable - | AccessibleStates.Focusable - | AccessibleStates.Linked; - - if (!owner.Expanded) - { - state |= AccessibleStates.Invisible; - } - - if (DataGrid.Focused && Owner.dgTable.FocusedRelation == relationship) - { - state |= AccessibleStates.Focused; - } - - return state; - } - } - - public override string Value - { - get - { - DataGridRow[] dgRows = DataGrid.DataGridRows; - if (Array.IndexOf(dgRows, owner) == -1) - { - return null; - } - else - { - return (string)owner.dgTable.RelationsList[relationship]; - } - } - set - { - // not supported - } - } - - public override string DefaultAction - { - get - { - return SR.AccDGNavigate; - } - } - - public override void DoDefaultAction() - { - ((DataGridRelationshipRow)Owner).Expanded = true; - owner.FocusedRelation = -1; - DataGrid.NavigateTo((string)owner.dgTable.RelationsList[relationship], owner, true); - DataGrid.BeginInvoke(new MethodInvoker(ResetAccessibilityLayer)); - } - - private void ResetAccessibilityLayer() - { - ((DataGrid.DataGridAccessibleObject)DataGrid.AccessibilityObject).NotifyClients(AccessibleEvents.Reorder, 0); - ((DataGrid.DataGridAccessibleObject)DataGrid.AccessibilityObject).NotifyClients(AccessibleEvents.Focus, DataGrid.CurrentCellAccIndex); - ((DataGrid.DataGridAccessibleObject)DataGrid.AccessibilityObject).NotifyClients(AccessibleEvents.Selection, DataGrid.CurrentCellAccIndex); - } - - /// - /// Navigate to the next or previous grid entry. - /// - public override AccessibleObject Navigate(AccessibleNavigation navdir) - { - switch (navdir) - { - case AccessibleNavigation.Right: - case AccessibleNavigation.Next: - case AccessibleNavigation.Down: - if (relationship + 1 < owner.dgTable.RelationsList.Count) - { - return Parent.GetChild(Parent.GetChildCount() - owner.dgTable.RelationsList.Count + relationship + 1); - } - break; - case AccessibleNavigation.Up: - case AccessibleNavigation.Left: - case AccessibleNavigation.Previous: - if (relationship > 0) - { - return Parent.GetChild(Parent.GetChildCount() - owner.dgTable.RelationsList.Count + relationship - 1); - } - break; - } - - return null; - - } - - public override void Select(AccessibleSelection flags) - { - // Focus the PropertyGridView window - // - if ((flags & AccessibleSelection.TakeFocus) == AccessibleSelection.TakeFocus) - { - DataGrid.Focus(); - } - - if ((flags & AccessibleSelection.TakeSelection) == AccessibleSelection.TakeSelection) - { - Owner.FocusedRelation = relationship; - } - } - - } - - } -} diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridRow.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridRow.cs deleted file mode 100644 index d9b7ddcb25e..00000000000 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridRow.cs +++ /dev/null @@ -1,1182 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Collections; -using System.ComponentModel; -using System.Diagnostics; -using System.Drawing; -using System.Drawing.Imaging; -using System.Runtime.InteropServices; - -namespace System.Windows.Forms -{ - /// - /// Encapsulates the painting logic for a new row added to a control. - /// - internal abstract class DataGridRow : MarshalByRefObject - { - internal protected int number; // row number - private bool selected; - private int height; - // protected DataRow dataRow; - private IntPtr tooltipID = new IntPtr(-1); - private string tooltip = string.Empty; - AccessibleObject accessibleObject; - - // for accessibility... - // - // internal DataGrid dataGrid; - - // will need this for the painting information ( row header color ) - // - protected DataGridTableStyle dgTable; - - // we will be mapping only the black color to - // the HeaderForeColor - // - private static readonly ColorMap[] colorMap = new ColorMap[] { new ColorMap() }; - - // bitmaps - // - private static Bitmap rightArrow = null; - private static Bitmap leftArrow = null; - private static Bitmap errorBmp = null; - private static Bitmap pencilBmp = null; - private static Bitmap starBmp = null; - protected const int xOffset = 3; - protected const int yOffset = 2; - - /// - /// Initializes a new instance of a . - /// - public DataGridRow(DataGrid dataGrid, DataGridTableStyle dgTable, int rowNumber) - { - if (dataGrid == null || dgTable.DataGrid == null) - { - throw new ArgumentNullException(nameof(dataGrid)); - } - - if (rowNumber < 0) - { - throw new ArgumentException(SR.DataGridRowRowNumber, "rowNumber"); - } - // this.dataGrid = dataGrid; - number = rowNumber; - - // map the black color in the pictures to the DataGrid's HeaderForeColor - // - colorMap[0].OldColor = Color.Black; - colorMap[0].NewColor = dgTable.HeaderForeColor; - - this.dgTable = dgTable; - height = MinimumRowHeight(dgTable); - } - - public AccessibleObject AccessibleObject - { - get - { - if (accessibleObject == null) - { - accessibleObject = CreateAccessibleObject(); - } - return accessibleObject; - } - } - - protected virtual AccessibleObject CreateAccessibleObject() - { - return new DataGridRowAccessibleObject(this); - } - - internal protected virtual int MinimumRowHeight(DataGridTableStyle dgTable) - { - return MinimumRowHeight(dgTable.GridColumnStyles); - } - - internal protected virtual int MinimumRowHeight(GridColumnStylesCollection columns) - { - int h = dgTable.IsDefault ? DataGrid.PreferredRowHeight : dgTable.PreferredRowHeight; - - try - { - if (dgTable.DataGrid.DataSource != null) - { - int nCols = columns.Count; - for (int i = 0; i < nCols; ++i) - { - // if (columns[i].Visible && columns[i].PropertyDescriptor != null) - if (columns[i].PropertyDescriptor != null) - { - h = Math.Max(h, columns[i].GetMinimumHeight()); - } - } - } - } - catch - { - } - return h; - } - - // =------------------------------------------------------------------ - // = Properties - // =------------------------------------------------------------------ - - /// - /// Gets the control the row belongs to. - /// - public DataGrid DataGrid - { - get - { - return dgTable.DataGrid; - } - } - - internal DataGridTableStyle DataGridTableStyle - { - get - { - return dgTable; - } - set - { - dgTable = value; - } - } - - /* - public DataGridTable DataGridTable { - get { - return dgTable; - } - } - */ - - /* - public DataRow DataRow { - get { - return dataRow; - } - } - */ - - /// - /// Gets or sets the height of the row. - /// - public virtual int Height - { - get - { - return height; - } - set - { - // the height of the row should be at least 0. - // this way, if the row has a relationship list and the user resizes the row such that - // the new height does not accomodate the height of the relationship list - // the row will at least show the relationship list ( and not paint on the portion of the row above this one ) - height = Math.Max(0, value); - // when we resize the row, or when we set the PreferredRowHeigth on the - // DataGridTableStyle, we change the height of the Row, which will cause to invalidate, - // then the grid itself will do another invalidate call. - dgTable.DataGrid.OnRowHeightChanged(this); - } - } - - /// - /// Gets the row's number. - /// - public int RowNumber - { - get - { - return number; - } - } - - /// - /// Gets or sets a value indicating whether the row is selected. - /// - public virtual bool Selected - { - get - { - return selected; - } - set - { - selected = value; - InvalidateRow(); - } - } - - // =------------------------------------------------------------------ - // = Methods - // =------------------------------------------------------------------ - - /// - /// Gets the bitmap associated with the row. - /// - protected Bitmap GetBitmap(string bitmapName) - { - try - { - return DpiHelper.GetBitmapFromIcon(typeof(DataGridCaption), bitmapName); - } - catch (Exception e) - { - Debug.Fail("Failed to load bitmap: " + bitmapName, e.ToString()); - throw e; - } - } - - /// - /// When overridden in a derived class, gets the - /// where a cell's contents gets painted. - /// - public virtual Rectangle GetCellBounds(int col) - { - int firstVisibleCol = dgTable.DataGrid.FirstVisibleColumn; - int cx = 0; - Rectangle cellBounds = new Rectangle(); - GridColumnStylesCollection columns = dgTable.GridColumnStyles; - if (columns != null) - { - for (int i = firstVisibleCol; i < col; i++) - { - if (columns[i].PropertyDescriptor != null) - { - cx += columns[i].Width; - } - } - - int borderWidth = dgTable.GridLineWidth; - cellBounds = new Rectangle(cx, - 0, - columns[col].Width - borderWidth, - Height - borderWidth); - } - return cellBounds; - } - - /// - /// When overridden in a derived class, gets the of the non-scrollable area of - /// the row. - /// - public virtual Rectangle GetNonScrollableArea() - { - return Rectangle.Empty; - } - - /// - /// Gets or sets the bitmap displayed in the row header of a new row. - /// - protected Bitmap GetStarBitmap() - { - if (starBmp == null) - { - starBmp = GetBitmap("DataGridRow.star"); - } - - return starBmp; - } - - /// - /// Gets or sets the bitmap displayed in the row header that indicates a row can - /// be edited. - /// - protected Bitmap GetPencilBitmap() - { - if (pencilBmp == null) - { - pencilBmp = GetBitmap("DataGridRow.pencil"); - } - - return pencilBmp; - } - - /// - /// Gets or sets the bitmap displayed on a row with an error. - /// - protected Bitmap GetErrorBitmap() - { - if (errorBmp == null) - { - errorBmp = GetBitmap("DataGridRow.error"); - } - - return errorBmp; - } - - protected Bitmap GetLeftArrowBitmap() - { - if (leftArrow == null) - { - leftArrow = GetBitmap("DataGridRow.left"); - } - - return leftArrow; - } - - protected Bitmap GetRightArrowBitmap() - { - if (rightArrow == null) - { - rightArrow = GetBitmap("DataGridRow.right"); - } - - return rightArrow; - } - - public virtual void InvalidateRow() - { - dgTable.DataGrid.InvalidateRow(number); - } - - public virtual void InvalidateRowRect(Rectangle r) - { - dgTable.DataGrid.InvalidateRowRect(number, r); - } - - /// - /// When overridden in a derived class, notifies the grid that an edit will - /// occur. - /// - public virtual void OnEdit() - { - } - - /// - /// When overridden in a derived class, called by the control when a key press occurs on a row with focus. - /// - public virtual bool OnKeyPress(Keys keyData) - { - int currentColIndex = dgTable.DataGrid.CurrentCell.ColumnNumber; - GridColumnStylesCollection columns = dgTable.GridColumnStyles; - if (columns != null && currentColIndex >= 0 && currentColIndex < columns.Count) - { - DataGridColumnStyle currentColumn = columns[currentColIndex]; - if (currentColumn.KeyPress(RowNumber, keyData)) - { - return true; - } - } - return false; - } - - /// - /// Called by the when a click occurs in the row's client area - /// specifed by the x and y coordinates and the specified - /// . - /// - public virtual bool OnMouseDown(int x, int y, Rectangle rowHeaders) - { - return OnMouseDown(x, y, rowHeaders, false); - } - - /// - /// When overridden in a derived class, is called by the when a click occurs - /// in the row's - /// client area, specified by x and y coordinates. - /// - public virtual bool OnMouseDown(int x, int y, Rectangle rowHeaders, bool alignToRight) - { - // if we call base.OnMouseDown, then the row could not use this - // mouse click at all. in that case LoseChildFocus, so the edit control - // will become visible - LoseChildFocus(rowHeaders, alignToRight); - - // we did not use this click at all. - return false; - } - - public virtual bool OnMouseMove(int x, int y, Rectangle rowHeaders) - { - return false; - } - - /// - /// When overridden in a derived class, is called by the when - /// the mouse moves within the row's client area. - /// - public virtual bool OnMouseMove(int x, int y, Rectangle rowHeaders, bool alignToRight) - { - return false; - } - - public virtual void OnMouseLeft(Rectangle rowHeaders, bool alignToRight) - { - } - - public virtual void OnMouseLeft() - { - } - - /// - /// When overridden in a derived class, causes the RowEnter event to occur. - /// - public virtual void OnRowEnter() { } - public virtual void OnRowLeave() { } - - // processes the Tab Key - // returns TRUE if the TAB key is processed - internal abstract bool ProcessTabKey(Keys keyData, Rectangle rowHeaders, bool alignToRight); - - // tells the dataGridRow that it lost the focus - internal abstract void LoseChildFocus(Rectangle rowHeaders, bool alignToRight); - - /// - /// Paints the row. - /// - public abstract int Paint(Graphics g, - Rectangle dataBounds, - Rectangle rowBounds, - int firstVisibleColumn, - int numVisibleColumns); - - public abstract int Paint(Graphics g, - Rectangle dataBounds, - Rectangle rowBounds, - int firstVisibleColumn, - int numVisibleColumns, - bool alignToRight); - - /// - /// Draws a border on the bottom DataGrid.GridLineWidth pixels - /// of the bounding rectangle passed in. - /// - protected virtual void PaintBottomBorder(Graphics g, Rectangle bounds, int dataWidth) - { - PaintBottomBorder(g, bounds, dataWidth, dgTable.GridLineWidth, false); - } - - protected virtual void PaintBottomBorder(Graphics g, Rectangle bounds, int dataWidth, int borderWidth, bool alignToRight) - { - // paint bottom border - Rectangle bottomBorder = new Rectangle(alignToRight ? bounds.Right - dataWidth : bounds.X, - bounds.Bottom - borderWidth, - dataWidth, - borderWidth); - - g.FillRectangle(dgTable.IsDefault ? DataGrid.GridLineBrush : dgTable.GridLineBrush, bottomBorder); - - // paint any exposed region to the right - if (dataWidth < bounds.Width) - { - g.FillRectangle(dgTable.DataGrid.BackgroundBrush, - alignToRight ? bounds.X : bottomBorder.Right, - bottomBorder.Y, - bounds.Width - bottomBorder.Width, - borderWidth); - } - } - - /// - /// Paints the row. - /// - public virtual int PaintData(Graphics g, - Rectangle bounds, - int firstVisibleColumn, - int columnCount) - { - return PaintData(g, bounds, firstVisibleColumn, columnCount, false); - } - - public virtual int PaintData(Graphics g, - Rectangle bounds, - int firstVisibleColumn, - int columnCount, - bool alignToRight) - { - Debug.WriteLineIf(CompModSwitches.DGRowPaint.TraceVerbose, "Painting DataGridAddNewRow: bounds = " + bounds.ToString()); - - Rectangle cellBounds = bounds; - int bWidth = dgTable.IsDefault ? DataGrid.GridLineWidth : dgTable.GridLineWidth; - int cx = 0; - - DataGridCell current = dgTable.DataGrid.CurrentCell; - - GridColumnStylesCollection columns = dgTable.GridColumnStyles; - int nCols = columns.Count; - for (int col = firstVisibleColumn; col < nCols; ++col) - { - if (cx > bounds.Width) - { - break; - } - - // if (!columns[col].Visible || columns[col].PropertyDescriptor == null) - if (columns[col].PropertyDescriptor == null || columns[col].Width <= 0) - { - continue; - } - - cellBounds.Width = columns[col].Width - bWidth; - - if (alignToRight) - { - cellBounds.X = bounds.Right - cx - cellBounds.Width; - } - else - { - cellBounds.X = bounds.X + cx; - } - - // Paint the data with the the DataGridColumn - Brush backBr = BackBrushForDataPaint(ref current, columns[col], col); - Brush foreBrush = ForeBrushForDataPaint(ref current, columns[col], col); - - PaintCellContents(g, - cellBounds, - columns[col], - backBr, - foreBrush, - alignToRight); - - // Paint the border to the right of each cell - if (bWidth > 0) - { - g.FillRectangle(dgTable.IsDefault ? DataGrid.GridLineBrush : dgTable.GridLineBrush, - alignToRight ? cellBounds.X - bWidth : cellBounds.Right, - cellBounds.Y, - bWidth, - cellBounds.Height); - } - cx += cellBounds.Width + bWidth; - } - - // Paint any exposed area to the right ( or left ) of the data cell area - if (cx < bounds.Width) - { - g.FillRectangle(dgTable.DataGrid.BackgroundBrush, - alignToRight ? bounds.X : bounds.X + cx, - bounds.Y, - bounds.Width - cx, - bounds.Height); - } - return cx; - } - - protected virtual void PaintCellContents(Graphics g, Rectangle cellBounds, DataGridColumnStyle column, - Brush backBr, Brush foreBrush) - { - PaintCellContents(g, cellBounds, column, backBr, foreBrush, false); - } - - protected virtual void PaintCellContents(Graphics g, Rectangle cellBounds, DataGridColumnStyle column, - Brush backBr, Brush foreBrush, bool alignToRight) - { - g.FillRectangle(backBr, cellBounds); - } - - // - // This function will do the following: if paintIcon is set to true, then - // will draw the image on the RowHeader. if paintIcon is set to false, - // then this function will fill the rectangle on which otherwise will - // have been drawn the image - // - // will return the rectangle that includes the Icon - // - protected Rectangle PaintIcon(Graphics g, Rectangle visualBounds, bool paintIcon, bool alignToRight, Bitmap bmp) - { - return PaintIcon(g, visualBounds, paintIcon, alignToRight, bmp, - dgTable.IsDefault ? DataGrid.HeaderBackBrush : dgTable.HeaderBackBrush); - } - protected Rectangle PaintIcon(Graphics g, Rectangle visualBounds, bool paintIcon, bool alignToRight, Bitmap bmp, Brush backBrush) - { - Size bmpSize = bmp.Size; - Rectangle bmpRect = new Rectangle(alignToRight ? visualBounds.Right - xOffset - bmpSize.Width : visualBounds.X + xOffset, - visualBounds.Y + yOffset, - bmpSize.Width, - bmpSize.Height); - g.FillRectangle(backBrush, visualBounds); - if (paintIcon) - { - colorMap[0].NewColor = dgTable.IsDefault ? DataGrid.HeaderForeColor : dgTable.HeaderForeColor; - colorMap[0].OldColor = Color.Black; - ImageAttributes attr = new ImageAttributes(); - attr.SetRemapTable(colorMap, ColorAdjustType.Bitmap); - g.DrawImage(bmp, bmpRect, 0, 0, bmpRect.Width, bmpRect.Height, GraphicsUnit.Pixel, attr); - // g.DrawImage(bmp, bmpRect); - attr.Dispose(); - } - - return bmpRect; - } - - // assume that the row is not aligned to right, and that the row is not dirty - public virtual void PaintHeader(Graphics g, Rectangle visualBounds) - { - PaintHeader(g, visualBounds, false); - } - - // assume that the row is not dirty - public virtual void PaintHeader(Graphics g, Rectangle visualBounds, bool alignToRight) - { - PaintHeader(g, visualBounds, alignToRight, false); - } - - public virtual void PaintHeader(Graphics g, Rectangle visualBounds, bool alignToRight, bool rowIsDirty) - { - Rectangle bounds = visualBounds; - - // paint the first part of the row header: the Arror or Pencil/Star - Bitmap bmp; - if (this is DataGridAddNewRow) - { - bmp = GetStarBitmap(); - lock (bmp) - { - bounds.X += PaintIcon(g, bounds, true, alignToRight, bmp).Width + xOffset; - } - return; - } - else if (rowIsDirty) - { - bmp = GetPencilBitmap(); - lock (bmp) - { - bounds.X += PaintIcon(g, bounds, RowNumber == DataGrid.CurrentCell.RowNumber, alignToRight, bmp).Width + xOffset; - } - } - else - { - bmp = alignToRight ? GetLeftArrowBitmap() : GetRightArrowBitmap(); - lock (bmp) - { - bounds.X += PaintIcon(g, bounds, RowNumber == DataGrid.CurrentCell.RowNumber, alignToRight, bmp).Width + xOffset; - } - } - - // Paint the error icon - // - object errorInfo = DataGrid.ListManager[number]; - if (!(errorInfo is IDataErrorInfo)) - { - return; - } - - string errString = ((IDataErrorInfo)errorInfo).Error; - if (errString == null) - { - errString = string.Empty; - } - - if (tooltip != errString) - { - if (!string.IsNullOrEmpty(tooltip)) - { - DataGrid.ToolTipProvider.RemoveToolTip(tooltipID); - tooltip = string.Empty; - tooltipID = new IntPtr(-1); - } - } - - if (string.IsNullOrEmpty(errString)) - { - return; - } - - // we now have an error string: paint the errorIcon and add the tooltip - Rectangle errRect; - bmp = GetErrorBitmap(); - lock (bmp) - { - errRect = PaintIcon(g, bounds, true, alignToRight, bmp); - } - bounds.X += errRect.Width + xOffset; - - tooltip = errString; - tooltipID = (IntPtr)((int)DataGrid.ToolTipId++); - DataGrid.ToolTipProvider.AddToolTip(tooltip, tooltipID, errRect); - } - - protected Brush GetBackBrush() - { - Brush br = dgTable.IsDefault ? DataGrid.BackBrush : dgTable.BackBrush; - if (DataGrid.LedgerStyle && (RowNumber % 2 == 1)) - { - br = dgTable.IsDefault ? DataGrid.AlternatingBackBrush : dgTable.AlternatingBackBrush; - } - return br; - } - - /// - /// Returns the BackColor and TextColor that the Graphics object should use - /// for the appropriate values for a given row and column when painting the data. - /// - protected Brush BackBrushForDataPaint(ref DataGridCell current, DataGridColumnStyle gridColumn, int column) - { - Brush backBr = GetBackBrush(); - - if (Selected) - { - backBr = dgTable.IsDefault ? DataGrid.SelectionBackBrush : dgTable.SelectionBackBrush; - } - /* - if (RowNumber == current.RowNumber && column == current.ColumnNumber) { - backBr = grid.CurrentCellBackBrush; - } - */ - return backBr; - } - - protected Brush ForeBrushForDataPaint(ref DataGridCell current, DataGridColumnStyle gridColumn, int column) - { - // Brush foreBrush = gridColumn.ForeBrush; - Brush foreBrush = dgTable.IsDefault ? DataGrid.ForeBrush : dgTable.ForeBrush; - - if (Selected) - { - foreBrush = dgTable.IsDefault ? DataGrid.SelectionForeBrush : dgTable.SelectionForeBrush; - } - /* - if (RowNumber == current.RowNumber && column == current.ColumnNumber) { - foreColor = grid.CurrentCellForeColor; - } - */ - return foreBrush; - } - - [ComVisible(true)] - protected class DataGridRowAccessibleObject : AccessibleObject - { - ArrayList cells; - readonly DataGridRow owner = null; - - internal static string CellToDisplayString(DataGrid grid, int row, int column) - { - if (column < grid.myGridTable.GridColumnStyles.Count) - { - return grid.myGridTable.GridColumnStyles[column].PropertyDescriptor.Converter.ConvertToString(grid[row, column]); - } - else - { - return ""; - } - } - - internal static object DisplayStringToCell(DataGrid grid, int row, int column, string value) - { - if (column < grid.myGridTable.GridColumnStyles.Count) - { - return grid.myGridTable.GridColumnStyles[column].PropertyDescriptor.Converter.ConvertFromString(value); - } - // ignore... - // - return null; - } - - public DataGridRowAccessibleObject(DataGridRow owner) : base() - { - Debug.Assert(owner != null, "DataGridRowAccessibleObject must have a valid owner DataGridRow"); - this.owner = owner; - DataGrid grid = DataGrid; - Debug.WriteLineIf(DataGrid.DataGridAcc.TraceVerbose, "Create row accessible object"); - - EnsureChildren(); - } - - private void EnsureChildren() - { - if (cells == null) - { - // default size... little extra for relationships... - // - cells = new ArrayList(DataGrid.myGridTable.GridColumnStyles.Count + 2); - AddChildAccessibleObjects(cells); - } - } - - protected virtual void AddChildAccessibleObjects(IList children) - { - Debug.WriteLineIf(DataGrid.DataGridAcc.TraceVerbose, "Create row's accessible children"); - Debug.Indent(); - GridColumnStylesCollection cols = DataGrid.myGridTable.GridColumnStyles; - int len = cols.Count; - Debug.WriteLineIf(DataGrid.DataGridAcc.TraceVerbose, len + " columns present"); - for (int i = 0; i < len; i++) - { - children.Add(CreateCellAccessibleObject(i)); - } - Debug.Unindent(); - } - - protected virtual AccessibleObject CreateCellAccessibleObject(int column) - { - return new DataGridCellAccessibleObject(owner, column); - } - - public override Rectangle Bounds - { - get - { - return DataGrid.RectangleToScreen(DataGrid.GetRowBounds(owner)); - } - } - - public override string Name - { - get - { - if (owner is DataGridAddNewRow) - { - return SR.AccDGNewRow; - } - else - { - return DataGridRowAccessibleObject.CellToDisplayString(DataGrid, owner.RowNumber, 0); - } - } - } - - protected DataGridRow Owner - { - get - { - return owner; - } - } - - public override AccessibleObject Parent - { - get - { - return DataGrid.AccessibilityObject; - } - } - - private DataGrid DataGrid - { - get - { - return owner.DataGrid; - } - } - - public override AccessibleRole Role - { - get - { - return AccessibleRole.Row; - } - } - - public override AccessibleStates State - { - get - { - AccessibleStates state = AccessibleStates.Selectable | AccessibleStates.Focusable; - - // Determine focus - // - if (DataGrid.CurrentCell.RowNumber == owner.RowNumber) - { - state |= AccessibleStates.Focused; - } - - // Determine selected - // - if (DataGrid.CurrentRowIndex == owner.RowNumber) - { - state |= AccessibleStates.Selected; - } - - return state; - } - } - - public override string Value - { - get - { - return Name; - } - } - - public override AccessibleObject GetChild(int index) - { - if (index < cells.Count) - { - return (AccessibleObject)cells[index]; - } - - return null; - } - - public override int GetChildCount() - { - return cells.Count; - } - - /// - /// Returns the currently focused child, if any. - /// Returns this if the object itself is focused. - /// - public override AccessibleObject GetFocused() - { - if (DataGrid.Focused) - { - DataGridCell cell = DataGrid.CurrentCell; - if (cell.RowNumber == owner.RowNumber) - { - return (AccessibleObject)cells[cell.ColumnNumber]; - } - } - - return null; - } - - /// - /// Navigate to the next or previous grid entry.entry. - /// - public override AccessibleObject Navigate(AccessibleNavigation navdir) - { - switch (navdir) - { - case AccessibleNavigation.Down: - case AccessibleNavigation.Right: - case AccessibleNavigation.Next: - return DataGrid.AccessibilityObject.GetChild(1 + owner.dgTable.GridColumnStyles.Count + owner.RowNumber + 1); - - case AccessibleNavigation.Up: - case AccessibleNavigation.Left: - case AccessibleNavigation.Previous: - return DataGrid.AccessibilityObject.GetChild(1 + owner.dgTable.GridColumnStyles.Count + owner.RowNumber - 1); - - case AccessibleNavigation.FirstChild: - if (GetChildCount() > 0) - { - return GetChild(0); - } - break; - case AccessibleNavigation.LastChild: - if (GetChildCount() > 0) - { - return GetChild(GetChildCount() - 1); - } - break; - } - - return null; - - } - - public override void Select(AccessibleSelection flags) - { - // Focus the PropertyGridView window - // - if ((flags & AccessibleSelection.TakeFocus) == AccessibleSelection.TakeFocus) - { - DataGrid.Focus(); - } - - // Select the grid entry - // - if ((flags & AccessibleSelection.TakeSelection) == AccessibleSelection.TakeSelection) - { - DataGrid.CurrentRowIndex = owner.RowNumber; - } - } - - } - - [ComVisible(true)] - protected class DataGridCellAccessibleObject : AccessibleObject - { - readonly DataGridRow owner = null; - readonly int column; - - public DataGridCellAccessibleObject(DataGridRow owner, int column) : base() - { - Debug.Assert(owner != null, "DataGridColumnAccessibleObject must have a valid owner DataGridRow"); - this.owner = owner; - this.column = column; - Debug.WriteLineIf(DataGrid.DataGridAcc.TraceVerbose, "Create cell accessible object"); - } - - public override Rectangle Bounds - { - get - { - return DataGrid.RectangleToScreen(DataGrid.GetCellBounds(new DataGridCell(owner.RowNumber, column))); - } - } - - public override string Name - { - get - { - return DataGrid.myGridTable.GridColumnStyles[column].HeaderText; - } - } - - public override AccessibleObject Parent - { - get - { - return owner.AccessibleObject; - } - } - - protected DataGrid DataGrid - { - get - { - return owner.DataGrid; - } - } - - public override string DefaultAction - { - get - { - return SR.AccDGEdit; - } - } - - public override AccessibleRole Role - { - get - { - return AccessibleRole.Cell; - } - } - - public override AccessibleStates State - { - get - { - AccessibleStates state = AccessibleStates.Selectable | AccessibleStates.Focusable; - - // Determine focus - // - if (DataGrid.CurrentCell.RowNumber == owner.RowNumber - && DataGrid.CurrentCell.ColumnNumber == column) - { - if (DataGrid.Focused) - { - state |= AccessibleStates.Focused; - } - state |= AccessibleStates.Selected; - } - - return state; - } - } - - public override string Value - { - get - { - if (owner is DataGridAddNewRow) - { - return null; - } - else - { - return DataGridRowAccessibleObject.CellToDisplayString(DataGrid, owner.RowNumber, column); - } - } - - set - { - if (!(owner is DataGridAddNewRow)) - { - object realValue = DataGridRowAccessibleObject.DisplayStringToCell(DataGrid, owner.RowNumber, column, value); - DataGrid[owner.RowNumber, column] = realValue; - } - } - } - - public override void DoDefaultAction() - { - Select(AccessibleSelection.TakeFocus | AccessibleSelection.TakeSelection); - } - - /// - /// Returns the currently focused child, if any. - /// Returns this if the object itself is focused. - /// - public override AccessibleObject GetFocused() - { - // Datagrid always returns the cell as the focused thing... so do we! - // - return DataGrid.AccessibilityObject.GetFocused(); - } - - /// - /// Navigate to the next or previous grid entry. - /// - public override AccessibleObject Navigate(AccessibleNavigation navdir) - { - switch (navdir) - { - case AccessibleNavigation.Right: - case AccessibleNavigation.Next: - if (column < owner.AccessibleObject.GetChildCount() - 1) - { - return owner.AccessibleObject.GetChild(column + 1); - } - else - { - AccessibleObject o = DataGrid.AccessibilityObject.GetChild(1 + owner.dgTable.GridColumnStyles.Count + owner.RowNumber + 1); - if (o != null) - { - return o.Navigate(AccessibleNavigation.FirstChild); - } - } - break; - case AccessibleNavigation.Down: - return DataGrid.AccessibilityObject.GetChild(1 + owner.dgTable.GridColumnStyles.Count + owner.RowNumber + 1).Navigate(AccessibleNavigation.FirstChild); - case AccessibleNavigation.Up: - return DataGrid.AccessibilityObject.GetChild(1 + owner.dgTable.GridColumnStyles.Count + owner.RowNumber - 1).Navigate(AccessibleNavigation.FirstChild); - case AccessibleNavigation.Left: - case AccessibleNavigation.Previous: - if (column > 0) - { - return owner.AccessibleObject.GetChild(column - 1); - } - else - { - AccessibleObject o = DataGrid.AccessibilityObject.GetChild(1 + owner.dgTable.GridColumnStyles.Count + owner.RowNumber - 1); - if (o != null) - { - return o.Navigate(AccessibleNavigation.LastChild); - } - } - break; - - case AccessibleNavigation.FirstChild: - case AccessibleNavigation.LastChild: - - break; - } - - return null; - - } - - public override void Select(AccessibleSelection flags) - { - // Focus the PropertyGridView window - // - if ((flags & AccessibleSelection.TakeFocus) == AccessibleSelection.TakeFocus) - { - DataGrid.Focus(); - } - - // Select the grid entry - // - if ((flags & AccessibleSelection.TakeSelection) == AccessibleSelection.TakeSelection) - { - DataGrid.CurrentCell = new DataGridCell(owner.RowNumber, column); - } - } - - } - } -} diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridState.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridState.cs deleted file mode 100644 index 9cf7e27b1aa..00000000000 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridState.cs +++ /dev/null @@ -1,261 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Diagnostics; -using System.Drawing; -using System.Runtime.InteropServices; -using System.Text; - -namespace System.Windows.Forms -{ - /// - /// Encapsulates the state of a DataGrid that changes when the - /// user navigates back and forth through ADO.NET data relations. - /// - internal sealed class DataGridState : ICloneable - { - // fields - // - public object DataSource = null; - public string DataMember = null; - public CurrencyManager ListManager = null; - public DataGridRow[] DataGridRows = Array.Empty(); - public DataGrid DataGrid; - public int DataGridRowsLength = 0; - public GridColumnStylesCollection GridColumnStyles = null; - - public int FirstVisibleRow = 0; - public int FirstVisibleCol = 0; - - public int CurrentRow = 0; - public int CurrentCol = 0; - - public DataGridRow LinkingRow = null; - AccessibleObject parentRowAccessibleObject; - - public DataGridState() - { - } - - public DataGridState(DataGrid dataGrid) - { - PushState(dataGrid); - } - - internal AccessibleObject ParentRowAccessibleObject - { - get - { - if (parentRowAccessibleObject == null) - { - parentRowAccessibleObject = new DataGridStateParentRowAccessibleObject(this); - } - return parentRowAccessibleObject; - } - } - - // methods - // - - public object Clone() - { - DataGridState dgs = new DataGridState - { - DataGridRows = DataGridRows, - DataSource = DataSource, - DataMember = DataMember, - FirstVisibleRow = FirstVisibleRow, - FirstVisibleCol = FirstVisibleCol, - CurrentRow = CurrentRow, - CurrentCol = CurrentCol, - GridColumnStyles = GridColumnStyles, - ListManager = ListManager, - DataGrid = DataGrid - }; - return dgs; - } - - /// - /// Called by a DataGrid when it wishes to preserve its - /// transient state in the current DataGridState object. - /// - public void PushState(DataGrid dataGrid) - { - DataSource = dataGrid.DataSource; - DataMember = dataGrid.DataMember; - DataGrid = dataGrid; - DataGridRows = dataGrid.DataGridRows; - DataGridRowsLength = dataGrid.DataGridRowsLength; - FirstVisibleRow = dataGrid.firstVisibleRow; - FirstVisibleCol = dataGrid.firstVisibleCol; - CurrentRow = dataGrid.currentRow; - GridColumnStyles = new GridColumnStylesCollection(dataGrid.myGridTable); - - GridColumnStyles.Clear(); - foreach (DataGridColumnStyle style in dataGrid.myGridTable.GridColumnStyles) - { - GridColumnStyles.Add(style); - } - - ListManager = dataGrid.ListManager; - ListManager.ItemChanged += new ItemChangedEventHandler(DataSource_Changed); - ListManager.MetaDataChanged += new EventHandler(DataSource_MetaDataChanged); - CurrentCol = dataGrid.currentCol; - } - - // this is needed so that the parent rows will remove notification from the list - // when the datagridstate is no longer needed; - public void RemoveChangeNotification() - { - ListManager.ItemChanged -= new ItemChangedEventHandler(DataSource_Changed); - ListManager.MetaDataChanged -= new EventHandler(DataSource_MetaDataChanged); - } - - /// - /// Called by a grid when it wishes to match its transient - /// state with the current DataGridState object. - /// - public void PullState(DataGrid dataGrid, bool createColumn) - { - // dataGrid.DataSource = DataSource; - // dataGrid.DataMember = DataMember; - dataGrid.Set_ListManager(DataSource, DataMember, true, createColumn); // true for forcing new listManager, - - /* - if (DataSource.Table.ParentRelations.Count > 0) - dataGrid.PopulateColumns(); - */ - - dataGrid.firstVisibleRow = FirstVisibleRow; - dataGrid.firstVisibleCol = FirstVisibleCol; - dataGrid.currentRow = CurrentRow; - dataGrid.currentCol = CurrentCol; - dataGrid.SetDataGridRows(DataGridRows, DataGridRowsLength); - } - - private void DataSource_Changed(object sender, ItemChangedEventArgs e) - { - if (DataGrid != null && ListManager.Position == e.Index) - { - DataGrid.InvalidateParentRows(); - return; - } - - if (DataGrid != null) - { - DataGrid.ParentRowsDataChanged(); - } - } - - private void DataSource_MetaDataChanged(object sender, EventArgs e) - { - if (DataGrid != null) - { - DataGrid.ParentRowsDataChanged(); - } - } - - [ComVisible(true)] - internal class DataGridStateParentRowAccessibleObject : AccessibleObject - { - readonly DataGridState owner = null; - - public DataGridStateParentRowAccessibleObject(DataGridState owner) : base() - { - Debug.Assert(owner != null, "DataGridRowAccessibleObject must have a valid owner DataGridRow"); - this.owner = owner; - } - - public override Rectangle Bounds - { - get - { - DataGridParentRows dataGridParentRows = ((DataGridParentRows.DataGridParentRowsAccessibleObject)Parent).Owner; - DataGrid g = owner.LinkingRow.DataGrid; - Rectangle r = dataGridParentRows.GetBoundsForDataGridStateAccesibility(owner); - r.Y += g.ParentRowsBounds.Y; - return g.RectangleToScreen(r); - } - } - - public override string Name - { - get - { - return SR.AccDGParentRow; - } - } - - public override AccessibleObject Parent - { - get - { - return owner.LinkingRow.DataGrid.ParentRowsAccessibleObject; - } - } - - public override AccessibleRole Role - { - get - { - return AccessibleRole.ListItem; - } - } - - public override string Value - { - get - { - StringBuilder sb = new StringBuilder(); - - CurrencyManager source = (CurrencyManager)owner.LinkingRow.DataGrid.BindingContext[owner.DataSource, owner.DataMember]; - - sb.Append(owner.ListManager.GetListName()); - sb.Append(": "); - - bool needComma = false; - foreach (DataGridColumnStyle col in owner.GridColumnStyles) - { - if (needComma) - { - sb.Append(", "); - } - - string colName = col.HeaderText; - string cellValue = col.PropertyDescriptor.Converter.ConvertToString(col.PropertyDescriptor.GetValue(source.Current)); - sb.Append(colName); - sb.Append(": "); - sb.Append(cellValue); - needComma = true; - } - - return sb.ToString(); - } - } - - /// - /// Navigate to the next or previous grid entry. - /// - public override AccessibleObject Navigate(AccessibleNavigation navdir) - { - DataGridParentRows.DataGridParentRowsAccessibleObject parentAcc = (DataGridParentRows.DataGridParentRowsAccessibleObject)Parent; - - switch (navdir) - { - case AccessibleNavigation.Down: - case AccessibleNavigation.Right: - case AccessibleNavigation.Next: - return parentAcc.GetNext(this); - case AccessibleNavigation.Up: - case AccessibleNavigation.Left: - case AccessibleNavigation.Previous: - return parentAcc.GetPrev(this); - } - - return null; - - } - } - } -} diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTableCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTableCollection.cs deleted file mode 100644 index 403eb46a5e7..00000000000 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTableCollection.cs +++ /dev/null @@ -1,336 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Collections; -using System.ComponentModel; -using System.Globalization; - -namespace System.Windows.Forms -{ - /// - /// Represents a collection of objects in the - /// control. - /// - [ListBindable(false)] - public class GridTableStylesCollection : BaseCollection, IList - { - CollectionChangeEventHandler onCollectionChanged; - readonly ArrayList items = new ArrayList(); - readonly DataGrid owner = null; - - int IList.Add(object value) - { - return Add((DataGridTableStyle)value); - } - - void IList.Clear() - { - Clear(); - } - - bool IList.Contains(object value) - { - return items.Contains(value); - } - - int IList.IndexOf(object value) - { - return items.IndexOf(value); - } - - void IList.Insert(int index, object value) - { - throw new NotSupportedException(); - } - - void IList.Remove(object value) - { - Remove((DataGridTableStyle)value); - } - - void IList.RemoveAt(int index) - { - RemoveAt(index); - } - - bool IList.IsFixedSize - { - get { return false; } - } - - bool IList.IsReadOnly - { - get { return false; } - } - - object IList.this[int index] - { - get { return items[index]; } - set { throw new NotSupportedException(); } - } - - void ICollection.CopyTo(Array array, int index) - { - items.CopyTo(array, index); - } - - int ICollection.Count - { - get { return items.Count; } - } - - bool ICollection.IsSynchronized - { - get { return false; } - } - - object ICollection.SyncRoot - { - get { return this; } - } - - IEnumerator IEnumerable.GetEnumerator() - { - return items.GetEnumerator(); - } - - internal GridTableStylesCollection(DataGrid grid) - { - owner = grid; - } - - protected override ArrayList List - { - get - { - return items; - } - } - - /* implemented in BaseCollection - /// - /// Retrieves the number of GridTables in the collection. - /// - /// - /// The number of GridTables in the collection. - /// - public override int Count { - get { - return items.Count; - } - } - */ - - /// - /// Retrieves the DataGridTable with the specified index. - /// - public DataGridTableStyle this[int index] - { - get - { - return (DataGridTableStyle)items[index]; - } - } - - /// - /// Retrieves the DataGridTable with the name provided. - /// - public DataGridTableStyle this[string tableName] - { - get - { - if (tableName == null) - { - throw new ArgumentNullException(nameof(tableName)); - } - - int itemCount = items.Count; - for (int i = 0; i < itemCount; ++i) - { - DataGridTableStyle table = (DataGridTableStyle)items[i]; - // NOTE: case-insensitive - if (string.Equals(table.MappingName, tableName, StringComparison.OrdinalIgnoreCase)) - { - return table; - } - } - return null; - } - } - - internal void CheckForMappingNameDuplicates(DataGridTableStyle table) - { - if (string.IsNullOrEmpty(table.MappingName)) - { - return; - } - - for (int i = 0; i < items.Count; i++) - { - if (((DataGridTableStyle)items[i]).MappingName.Equals(table.MappingName) && table != items[i]) - { - throw new ArgumentException(SR.DataGridTableStyleDuplicateMappingName, "table"); - } - } - } - - /// - /// Adds a to this collection. - /// - public virtual int Add(DataGridTableStyle table) - { - // set the rowHeaderWidth on the newly added table to at least the minimum value - // on its owner - if (owner != null && owner.MinimumRowHeaderWidth() > table.RowHeaderWidth) - { - table.RowHeaderWidth = owner.MinimumRowHeaderWidth(); - } - - if (table.DataGrid != owner && table.DataGrid != null) - { - throw new ArgumentException(SR.DataGridTableStyleCollectionAddedParentedTableStyle, "table"); - } - - table.DataGrid = owner; - CheckForMappingNameDuplicates(table); - table.MappingNameChanged += new EventHandler(TableStyleMappingNameChanged); - int index = items.Add(table); - OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Add, table)); - - return index; - } - - private void TableStyleMappingNameChanged(object sender, EventArgs pcea) - { - OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Refresh, null)); - } - - public virtual void AddRange(DataGridTableStyle[] tables) - { - if (tables == null) - { - throw new ArgumentNullException(nameof(tables)); - } - foreach (DataGridTableStyle table in tables) - { - table.DataGrid = owner; - table.MappingNameChanged += new EventHandler(TableStyleMappingNameChanged); - items.Add(table); - } - OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Refresh, null)); - } - - public event CollectionChangeEventHandler CollectionChanged - { - add => onCollectionChanged += value; - remove => onCollectionChanged -= value; - } - - public void Clear() - { - for (int i = 0; i < items.Count; i++) - { - DataGridTableStyle element = (DataGridTableStyle)items[i]; - element.MappingNameChanged -= new EventHandler(TableStyleMappingNameChanged); - } - - items.Clear(); - OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Refresh, null)); - } - - /// - /// Checks to see if a DataGridTableStyle is contained in this collection. - /// - public bool Contains(DataGridTableStyle table) - { - int index = items.IndexOf(table); - return index != -1; - } - - /// - /// Checks to see if a with the given name - /// is contained in this collection. - /// - public bool Contains(string name) - { - int itemCount = items.Count; - for (int i = 0; i < itemCount; ++i) - { - DataGridTableStyle table = (DataGridTableStyle)items[i]; - // NOTE: case-insensitive - if (string.Compare(table.MappingName, name, true, CultureInfo.InvariantCulture) == 0) - { - return true; - } - } - return false; - } - - /* - public override IEnumerator GetEnumerator() { - return items.GetEnumerator(); - } - - public override IEnumerator GetEnumerator(bool allowRemove) { - if (!allowRemove) - return GetEnumerator(); - else - throw new NotSupportedException(SR.DataGridTableCollectionGetEnumerator); - } - */ - - protected void OnCollectionChanged(CollectionChangeEventArgs e) - { - onCollectionChanged?.Invoke(this, e); - - DataGrid grid = owner; - if (grid != null) - { - /* FOR DEMO: Microsoft: TableStylesCollection::OnCollectionChanged: set the datagridtble - DataView dataView = ((DataView) grid.DataSource); - if (dataView != null) { - DataTable dataTable = dataView.Table; - if (dataTable != null) { - if (Contains(dataTable)) { - grid.SetDataGridTable(this[dataTable]); - } - } - } - */ - grid.checkHierarchy = true; - } - } - - public void Remove(DataGridTableStyle table) - { - int tableIndex = -1; - int itemsCount = items.Count; - for (int i = 0; i < itemsCount; ++i) - { - if (items[i] == table) - { - tableIndex = i; - break; - } - } - - if (tableIndex == -1) - { - throw new ArgumentException(SR.DataGridTableCollectionMissingTable, "table"); - } - else - { - RemoveAt(tableIndex); - } - } - - public void RemoveAt(int index) - { - DataGridTableStyle element = (DataGridTableStyle)items[index]; - element.MappingNameChanged -= new EventHandler(TableStyleMappingNameChanged); - items.RemoveAt(index); - OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Remove, element)); - } - } -} diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTableStyle.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTableStyle.cs deleted file mode 100644 index 0fc0a1e0de1..00000000000 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTableStyle.cs +++ /dev/null @@ -1,1778 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Collections; -using System.ComponentModel; -using System.Diagnostics; -using System.Drawing; - -namespace System.Windows.Forms -{ - /// - /// Represents the table drawn by the control at run time. - /// - [ - ToolboxItem(false), - DesignTimeVisible(false), - //DefaultProperty("GridTableName") - ] - public class DataGridTableStyle : Component, IDataGridEditingService - { - // internal for DataGridColumn accessibility... - // - internal DataGrid dataGrid = null; - - // relationship UI - private int relationshipHeight = 0; - internal const int relationshipSpacing = 1; - private Rectangle relationshipRect = Rectangle.Empty; - private int focusedRelation = -1; - private int focusedTextWidth; - - // will contain a list of relationships that this table has - private readonly ArrayList relationsList = new ArrayList(2); - - // the name of the table - private string mappingName = string.Empty; - private readonly GridColumnStylesCollection gridColumns = null; - private bool readOnly = false; - private readonly bool isDefaultTableStyle = false; - - private static readonly object EventAllowSorting = new object(); - private static readonly object EventGridLineColor = new object(); - private static readonly object EventGridLineStyle = new object(); - private static readonly object EventHeaderBackColor = new object(); - private static readonly object EventHeaderForeColor = new object(); - private static readonly object EventHeaderFont = new object(); - private static readonly object EventLinkColor = new object(); - private static readonly object EventLinkHoverColor = new object(); - private static readonly object EventPreferredColumnWidth = new object(); - private static readonly object EventPreferredRowHeight = new object(); - private static readonly object EventColumnHeadersVisible = new object(); - private static readonly object EventRowHeaderWidth = new object(); - private static readonly object EventSelectionBackColor = new object(); - private static readonly object EventSelectionForeColor = new object(); - private static readonly object EventMappingName = new object(); - private static readonly object EventAlternatingBackColor = new object(); - private static readonly object EventBackColor = new object(); - private static readonly object EventForeColor = new object(); - private static readonly object EventReadOnly = new object(); - private static readonly object EventRowHeadersVisible = new object(); - - // add a bunch of properties, taken from the dataGrid - // - - // default values - // - private const bool defaultAllowSorting = true; - private const DataGridLineStyle defaultGridLineStyle = DataGridLineStyle.Solid; - private const int defaultPreferredColumnWidth = 75; - private const int defaultRowHeaderWidth = 35; - internal static readonly Font defaultFont = Control.DefaultFont; - internal static readonly int defaultFontHeight = defaultFont.Height; - - // the actual place holders for properties - // - private bool allowSorting = defaultAllowSorting; - private SolidBrush alternatingBackBrush = DefaultAlternatingBackBrush; - private SolidBrush backBrush = DefaultBackBrush; - private SolidBrush foreBrush = DefaultForeBrush; - private SolidBrush gridLineBrush = DefaultGridLineBrush; - private DataGridLineStyle gridLineStyle = defaultGridLineStyle; - internal SolidBrush headerBackBrush = DefaultHeaderBackBrush; - internal Font headerFont = null; // this is ambient property to Font value. - internal SolidBrush headerForeBrush = DefaultHeaderForeBrush; - internal Pen headerForePen = DefaultHeaderForePen; - private SolidBrush linkBrush = DefaultLinkBrush; - internal int preferredColumnWidth = defaultPreferredColumnWidth; - private int preferredRowHeight = defaultFontHeight + 3; - private SolidBrush selectionBackBrush = DefaultSelectionBackBrush; - private SolidBrush selectionForeBrush = DefaultSelectionForeBrush; - private int rowHeaderWidth = defaultRowHeaderWidth; - private bool rowHeadersVisible = true; - private bool columnHeadersVisible = true; - - // the dataGrid would need to know when the ColumnHeaderVisible, RowHeadersVisible, RowHeaderWidth - // and preferredColumnWidth, preferredRowHeight properties are changed in the current dataGridTableStyle - // also: for GridLineStyle, GridLineColor, ForeColor, BackColor, HeaderBackColor, HeaderFont, HeaderForeColor - // LinkColor, LinkHoverColor - // - - [ - SRCategory(nameof(SR.CatBehavior)), - DefaultValue(defaultAllowSorting), - SRDescription(nameof(SR.DataGridAllowSortingDescr)) - ] - public bool AllowSorting - { - get - { - return allowSorting; - } - set - { - if (isDefaultTableStyle) - { - throw new ArgumentException(string.Format(SR.DataGridDefaultTableSet, nameof(AllowSorting))); - } - - if (allowSorting != value) - { - allowSorting = value; - OnAllowSortingChanged(EventArgs.Empty); - } - } - } - - /// - /// [To be supplied] - /// - public event EventHandler AllowSortingChanged - { - add => Events.AddHandler(EventAllowSorting, value); - remove => Events.RemoveHandler(EventAllowSorting, value); - } - - [ - SRCategory(nameof(SR.CatColors)), - SRDescription(nameof(SR.DataGridAlternatingBackColorDescr)) - ] - public Color AlternatingBackColor - { - get - { - return alternatingBackBrush.Color; - } - set - { - if (isDefaultTableStyle) - { - throw new ArgumentException(string.Format(SR.DataGridDefaultTableSet, nameof(AlternatingBackColor))); - } - - if (System.Windows.Forms.DataGrid.IsTransparentColor(value)) - { - throw new ArgumentException(SR.DataGridTableStyleTransparentAlternatingBackColorNotAllowed, nameof(value)); - } - - if (value.IsEmpty) - { - throw new ArgumentException(string.Format(SR.DataGridEmptyColor, nameof(AlternatingBackColor)), nameof(value)); - } - if (!alternatingBackBrush.Color.Equals(value)) - { - alternatingBackBrush = new SolidBrush(value); - InvalidateInside(); - OnAlternatingBackColorChanged(EventArgs.Empty); - } - } - } - - public event EventHandler AlternatingBackColorChanged - { - add => Events.AddHandler(EventAlternatingBackColor, value); - remove => Events.RemoveHandler(EventAlternatingBackColor, value); - } - public void ResetAlternatingBackColor() - { - if (ShouldSerializeAlternatingBackColor()) - { - AlternatingBackColor = DefaultAlternatingBackBrush.Color; - InvalidateInside(); - } - } - - protected virtual bool ShouldSerializeAlternatingBackColor() - { - return !AlternatingBackBrush.Equals(DefaultAlternatingBackBrush); - } - - internal SolidBrush AlternatingBackBrush - { - get - { - return alternatingBackBrush; - } - } - - protected bool ShouldSerializeBackColor() - { - return !System.Windows.Forms.DataGridTableStyle.DefaultBackBrush.Equals(backBrush); - } - - protected bool ShouldSerializeForeColor() - { - return !System.Windows.Forms.DataGridTableStyle.DefaultForeBrush.Equals(foreBrush); - } - - internal SolidBrush BackBrush - { - get - { - return backBrush; - } - } - - [ - SRCategory(nameof(SR.CatColors)), - SRDescription(nameof(SR.ControlBackColorDescr)) - ] - public Color BackColor - { - get - { - return backBrush.Color; - } - set - { - if (isDefaultTableStyle) - { - throw new ArgumentException(string.Format(SR.DataGridDefaultTableSet, nameof(BackColor))); - } - - if (System.Windows.Forms.DataGrid.IsTransparentColor(value)) - { - throw new ArgumentException(SR.DataGridTableStyleTransparentBackColorNotAllowed, nameof(value)); - } - - if (value.IsEmpty) - { - throw new ArgumentException(string.Format(SR.DataGridEmptyColor, nameof(BackColor)), nameof(value)); - } - if (!backBrush.Color.Equals(value)) - { - backBrush = new SolidBrush(value); - InvalidateInside(); - OnBackColorChanged(EventArgs.Empty); - } - } - } - - public event EventHandler BackColorChanged - { - add => Events.AddHandler(EventBackColor, value); - remove => Events.RemoveHandler(EventBackColor, value); - } - - public void ResetBackColor() - { - if (!backBrush.Equals(DefaultBackBrush)) - { - BackColor = DefaultBackBrush.Color; - } - } - - internal int BorderWidth - { - get - { - DataGrid dataGrid = DataGrid; - if (dataGrid == null) - { - return 0; - } - // if the user set the GridLineStyle property on the dataGrid. - // then use the value of that property - DataGridLineStyle gridStyle; - int gridLineWidth; - if (IsDefault) - { - gridStyle = DataGrid.GridLineStyle; - gridLineWidth = DataGrid.GridLineWidth; - } - else - { - gridStyle = GridLineStyle; - gridLineWidth = GridLineWidth; - } - - if (gridStyle == DataGridLineStyle.None) - { - return 0; - } - - return gridLineWidth; - } - } - - internal static SolidBrush DefaultAlternatingBackBrush - { - get - { - return (SolidBrush)SystemBrushes.Window; - } - } - internal static SolidBrush DefaultBackBrush - { - get - { - return (SolidBrush)SystemBrushes.Window; - } - } - internal static SolidBrush DefaultForeBrush - { - get - { - return (SolidBrush)SystemBrushes.WindowText; - } - } - private static SolidBrush DefaultGridLineBrush - { - get - { - return (SolidBrush)SystemBrushes.Control; - } - } - private static SolidBrush DefaultHeaderBackBrush - { - get - { - return (SolidBrush)SystemBrushes.Control; - } - } - private static SolidBrush DefaultHeaderForeBrush - { - get - { - return (SolidBrush)SystemBrushes.ControlText; - } - } - private static Pen DefaultHeaderForePen - { - get - { - return new Pen(SystemColors.ControlText); - } - } - private static SolidBrush DefaultLinkBrush - { - get - { - return (SolidBrush)SystemBrushes.HotTrack; - } - } - private static SolidBrush DefaultSelectionBackBrush - { - get - { - return (SolidBrush)SystemBrushes.ActiveCaption; - } - } - private static SolidBrush DefaultSelectionForeBrush - { - get - { - return (SolidBrush)SystemBrushes.ActiveCaptionText; - } - } - - internal int FocusedRelation - { - get - { - return focusedRelation; - } - set - { - if (focusedRelation != value) - { - focusedRelation = value; - if (focusedRelation == -1) - { - focusedTextWidth = 0; - } - else - { - Graphics g = DataGrid.CreateGraphicsInternal(); - focusedTextWidth = (int)Math.Ceiling(g.MeasureString(((string)RelationsList[focusedRelation]), DataGrid.LinkFont).Width); - g.Dispose(); - } - } - } - } - - internal int FocusedTextWidth - { - get - { - return focusedTextWidth; - } - } - - [ - SRCategory(nameof(SR.CatColors)), - SRDescription(nameof(SR.ControlForeColorDescr)) - ] - public Color ForeColor - { - get - { - return foreBrush.Color; - } - set - { - if (isDefaultTableStyle) - { - throw new ArgumentException(string.Format(SR.DataGridDefaultTableSet, nameof(ForeColor))); - } - - if (value.IsEmpty) - { - throw new ArgumentException(string.Format(SR.DataGridEmptyColor, nameof(ForeColor)), nameof(value)); - } - if (!foreBrush.Color.Equals(value)) - { - foreBrush = new SolidBrush(value); - InvalidateInside(); - OnForeColorChanged(EventArgs.Empty); - } - } - } - - public event EventHandler ForeColorChanged - { - add => Events.AddHandler(EventForeColor, value); - remove => Events.RemoveHandler(EventForeColor, value); - } - - internal SolidBrush ForeBrush - { - get - { - return foreBrush; - } - } - - public void ResetForeColor() - { - if (!foreBrush.Equals(DefaultForeBrush)) - { - ForeColor = DefaultForeBrush.Color; - } - } - - [ - SRCategory(nameof(SR.CatColors)), - SRDescription(nameof(SR.DataGridGridLineColorDescr)) - ] - public Color GridLineColor - { - get - { - return gridLineBrush.Color; - } - set - { - if (isDefaultTableStyle) - { - throw new ArgumentException(string.Format(SR.DataGridDefaultTableSet, nameof(GridLineColor))); - } - - if (gridLineBrush.Color != value) - { - if (value.IsEmpty) - { - throw new ArgumentException(string.Format(SR.DataGridEmptyColor, nameof(GridLineColor)), nameof(value)); - } - - gridLineBrush = new SolidBrush(value); - OnGridLineColorChanged(EventArgs.Empty); - } - } - } - - public event EventHandler GridLineColorChanged - { - add => Events.AddHandler(EventGridLineColor, value); - remove => Events.RemoveHandler(EventGridLineColor, value); - } - - protected virtual bool ShouldSerializeGridLineColor() - { - return !GridLineBrush.Equals(DefaultGridLineBrush); - } - - public void ResetGridLineColor() - { - if (ShouldSerializeGridLineColor()) - { - GridLineColor = DefaultGridLineBrush.Color; - } - } - - internal SolidBrush GridLineBrush - { - get - { - return gridLineBrush; - } - } - - internal int GridLineWidth - { - get - { - Debug.Assert(GridLineStyle == DataGridLineStyle.Solid || GridLineStyle == DataGridLineStyle.None, "are there any other styles?"); - return GridLineStyle == DataGridLineStyle.Solid ? 1 : 0; - } - } - - [ - SRCategory(nameof(SR.CatAppearance)), - DefaultValue(defaultGridLineStyle), - SRDescription(nameof(SR.DataGridGridLineStyleDescr)) - ] - public DataGridLineStyle GridLineStyle - { - get - { - return gridLineStyle; - } - set - { - if (isDefaultTableStyle) - { - throw new ArgumentException(string.Format(SR.DataGridDefaultTableSet, nameof(GridLineStyle))); - } - - //valid values are 0x0 to 0x1. - if (!ClientUtils.IsEnumValid(value, (int)value, (int)DataGridLineStyle.None, (int)DataGridLineStyle.Solid)) - { - throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridLineStyle)); - } - if (gridLineStyle != value) - { - gridLineStyle = value; - OnGridLineStyleChanged(EventArgs.Empty); - } - } - } - - public event EventHandler GridLineStyleChanged - { - add => Events.AddHandler(EventGridLineStyle, value); - remove => Events.RemoveHandler(EventGridLineStyle, value); - } - - [ - SRCategory(nameof(SR.CatColors)), - SRDescription(nameof(SR.DataGridHeaderBackColorDescr)) - ] - public Color HeaderBackColor - { - get - { - return headerBackBrush.Color; - } - set - { - if (isDefaultTableStyle) - { - throw new ArgumentException(string.Format(SR.DataGridDefaultTableSet, nameof(HeaderBackColor))); - } - - if (System.Windows.Forms.DataGrid.IsTransparentColor(value)) - { - throw new ArgumentException(SR.DataGridTableStyleTransparentHeaderBackColorNotAllowed, nameof(value)); - } - - if (value.IsEmpty) - { - throw new ArgumentException(string.Format(SR.DataGridEmptyColor, nameof(HeaderBackColor)), nameof(value)); - } - - if (!value.Equals(headerBackBrush.Color)) - { - headerBackBrush = new SolidBrush(value); - OnHeaderBackColorChanged(EventArgs.Empty); - } - } - } - - public event EventHandler HeaderBackColorChanged - { - add => Events.AddHandler(EventHeaderBackColor, value); - remove => Events.RemoveHandler(EventHeaderBackColor, value); - } - - internal SolidBrush HeaderBackBrush - { - get - { - return headerBackBrush; - } - } - - protected virtual bool ShouldSerializeHeaderBackColor() - { - return !HeaderBackBrush.Equals(DefaultHeaderBackBrush); - } - - public void ResetHeaderBackColor() - { - if (ShouldSerializeHeaderBackColor()) - { - HeaderBackColor = DefaultHeaderBackBrush.Color; - } - } - - [ - SRCategory(nameof(SR.CatAppearance)), - Localizable(true), - AmbientValue(null), - SRDescription(nameof(SR.DataGridHeaderFontDescr)) - ] - public Font HeaderFont - { - get - { - return (headerFont ?? (DataGrid == null ? Control.DefaultFont : DataGrid.Font)); - } - set - { - if (isDefaultTableStyle) - { - throw new ArgumentException(string.Format(SR.DataGridDefaultTableSet, nameof(HeaderFont))); - } - - if (value == null && headerFont != null || (value != null && !value.Equals(headerFont))) - { - headerFont = value; - OnHeaderFontChanged(EventArgs.Empty); - } - } - } - - public event EventHandler HeaderFontChanged - { - add => Events.AddHandler(EventHeaderFont, value); - remove => Events.RemoveHandler(EventHeaderFont, value); - } - - private bool ShouldSerializeHeaderFont() - { - return (headerFont != null); - } - - public void ResetHeaderFont() - { - if (headerFont != null) - { - headerFont = null; - OnHeaderFontChanged(EventArgs.Empty); - } - } - - [ - SRCategory(nameof(SR.CatColors)), - SRDescription(nameof(SR.DataGridHeaderForeColorDescr)) - ] - public Color HeaderForeColor - { - get - { - return headerForePen.Color; - } - set - { - if (isDefaultTableStyle) - { - throw new ArgumentException(string.Format(SR.DataGridDefaultTableSet, nameof(HeaderForeColor))); - } - - if (value.IsEmpty) - { - throw new ArgumentException(string.Format(SR.DataGridEmptyColor, nameof(HeaderForeColor)), nameof(value)); - } - - if (!value.Equals(headerForePen.Color)) - { - headerForePen = new Pen(value); - headerForeBrush = new SolidBrush(value); - OnHeaderForeColorChanged(EventArgs.Empty); - } - } - } - - public event EventHandler HeaderForeColorChanged - { - add => Events.AddHandler(EventHeaderForeColor, value); - remove => Events.RemoveHandler(EventHeaderForeColor, value); - } - - protected virtual bool ShouldSerializeHeaderForeColor() - { - return !HeaderForePen.Equals(DefaultHeaderForePen); - } - - public void ResetHeaderForeColor() - { - if (ShouldSerializeHeaderForeColor()) - { - HeaderForeColor = DefaultHeaderForeBrush.Color; - } - } - - internal SolidBrush HeaderForeBrush - { - get - { - return headerForeBrush; - } - } - - internal Pen HeaderForePen - { - get - { - return headerForePen; - } - } - - [ - SRCategory(nameof(SR.CatColors)), - SRDescription(nameof(SR.DataGridLinkColorDescr)) - ] - public Color LinkColor - { - get - { - return linkBrush.Color; - } - set - { - if (isDefaultTableStyle) - { - throw new ArgumentException(string.Format(SR.DataGridDefaultTableSet, nameof(LinkColor))); - } - - if (value.IsEmpty) - { - throw new ArgumentException(string.Format(SR.DataGridEmptyColor, nameof(LinkColor)), nameof(value)); - } - - if (!linkBrush.Color.Equals(value)) - { - linkBrush = new SolidBrush(value); - OnLinkColorChanged(EventArgs.Empty); - } - } - } - - public event EventHandler LinkColorChanged - { - add => Events.AddHandler(EventLinkColor, value); - remove => Events.RemoveHandler(EventLinkColor, value); - } - - protected virtual bool ShouldSerializeLinkColor() - { - return !LinkBrush.Equals(DefaultLinkBrush); - } - - public void ResetLinkColor() - { - if (ShouldSerializeLinkColor()) - { - LinkColor = DefaultLinkBrush.Color; - } - } - - internal Brush LinkBrush - { - get - { - return linkBrush; - } - } - - [ - SRDescription(nameof(SR.DataGridLinkHoverColorDescr)), - SRCategory(nameof(SR.CatColors)), - Browsable(false), - EditorBrowsable(EditorBrowsableState.Never) - ] - public Color LinkHoverColor - { - get - { - return LinkColor; - } - set - { - } - } - - public event EventHandler LinkHoverColorChanged - { - add => Events.AddHandler(EventLinkHoverColor, value); - remove => Events.RemoveHandler(EventLinkHoverColor, value); - } - - protected virtual bool ShouldSerializeLinkHoverColor() - { - return false; - } - - internal Rectangle RelationshipRect - { - get - { - if (relationshipRect.IsEmpty) - { - ComputeRelationshipRect(); - } - return relationshipRect; - } - } - - private Rectangle ComputeRelationshipRect() - { - if (relationshipRect.IsEmpty && DataGrid.AllowNavigation) - { - Debug.WriteLineIf(CompModSwitches.DGRelationShpRowLayout.TraceVerbose, "GetRelationshipRect grinding away"); - Graphics g = DataGrid.CreateGraphicsInternal(); - relationshipRect = new Rectangle - { - X = 0 //indentWidth; - }; - // relationshipRect.Y = base.Height - BorderWidth; - - // Determine the width of the widest relationship name - int longestRelationship = 0; - for (int r = 0; r < RelationsList.Count; ++r) - { - int rwidth = (int)Math.Ceiling(g.MeasureString(((string)RelationsList[r]), DataGrid.LinkFont).Width) -; - if (rwidth > longestRelationship) - { - longestRelationship = rwidth; - } - } - - g.Dispose(); - - relationshipRect.Width = longestRelationship + 5; - relationshipRect.Width += 2; // relationshipRect border; - relationshipRect.Height = BorderWidth + relationshipHeight * RelationsList.Count; - relationshipRect.Height += 2; // relationship border - if (RelationsList.Count > 0) - { - relationshipRect.Height += 2 * relationshipSpacing; - } - } - return relationshipRect; - } - - internal void ResetRelationsUI() - { - relationshipRect = Rectangle.Empty; - focusedRelation = -1; - relationshipHeight = dataGrid.LinkFontHeight + relationshipSpacing; - } - - internal int RelationshipHeight - { - get - { - return relationshipHeight; - } - } - - public void ResetLinkHoverColor() - { - } - - [ - DefaultValue(defaultPreferredColumnWidth), - SRCategory(nameof(SR.CatLayout)), - Localizable(true), - SRDescription(nameof(SR.DataGridPreferredColumnWidthDescr)), - TypeConverter(typeof(DataGridPreferredColumnWidthTypeConverter)) - ] - public int PreferredColumnWidth - { - get - { - return preferredColumnWidth; - } - set - { - if (isDefaultTableStyle) - { - throw new ArgumentException(string.Format(SR.DataGridDefaultTableSet, nameof(PreferredColumnWidth))); - } - - if (value < 0) - { - throw new ArgumentOutOfRangeException(nameof(value), value, SR.DataGridColumnWidth); - } - - if (preferredColumnWidth != value) - { - preferredColumnWidth = value; - OnPreferredColumnWidthChanged(EventArgs.Empty); - } - } - } - - public event EventHandler PreferredColumnWidthChanged - { - add => Events.AddHandler(EventPreferredColumnWidth, value); - remove => Events.RemoveHandler(EventPreferredColumnWidth, value); - } - - [ - SRCategory(nameof(SR.CatLayout)), - Localizable(true), - SRDescription(nameof(SR.DataGridPreferredRowHeightDescr)) - ] - public int PreferredRowHeight - { - get - { - return preferredRowHeight; - } - set - { - if (isDefaultTableStyle) - { - throw new ArgumentException(string.Format(SR.DataGridDefaultTableSet, nameof(PreferredRowHeight))); - } - - if (value < 0) - { - throw new ArgumentOutOfRangeException(nameof(value), value, SR.DataGridRowRowHeight); - } - - if (preferredRowHeight != value) - { - preferredRowHeight = value; - OnPreferredRowHeightChanged(EventArgs.Empty); - } - } - } - - public event EventHandler PreferredRowHeightChanged - { - add => Events.AddHandler(EventPreferredRowHeight, value); - remove => Events.RemoveHandler(EventPreferredRowHeight, value); - } - - private void ResetPreferredRowHeight() - { - PreferredRowHeight = defaultFontHeight + 3; - } - - protected bool ShouldSerializePreferredRowHeight() - { - return preferredRowHeight != defaultFontHeight + 3; - } - - [ - SRCategory(nameof(SR.CatDisplay)), - DefaultValue(true), - SRDescription(nameof(SR.DataGridColumnHeadersVisibleDescr)) - ] - public bool ColumnHeadersVisible - { - get - { - return columnHeadersVisible; - } - set - { - if (columnHeadersVisible != value) - { - columnHeadersVisible = value; - OnColumnHeadersVisibleChanged(EventArgs.Empty); - } - } - } - - public event EventHandler ColumnHeadersVisibleChanged - { - add => Events.AddHandler(EventColumnHeadersVisible, value); - remove => Events.RemoveHandler(EventColumnHeadersVisible, value); - } - - [ - SRCategory(nameof(SR.CatDisplay)), - DefaultValue(true), - SRDescription(nameof(SR.DataGridRowHeadersVisibleDescr)) - ] - public bool RowHeadersVisible - { - get - { - return rowHeadersVisible; - } - set - { - if (rowHeadersVisible != value) - { - rowHeadersVisible = value; - OnRowHeadersVisibleChanged(EventArgs.Empty); - } - } - } - - public event EventHandler RowHeadersVisibleChanged - { - add => Events.AddHandler(EventRowHeadersVisible, value); - remove => Events.RemoveHandler(EventRowHeadersVisible, value); - } - - [ - SRCategory(nameof(SR.CatLayout)), - DefaultValue(defaultRowHeaderWidth), - Localizable(true), - SRDescription(nameof(SR.DataGridRowHeaderWidthDescr)) - ] - public int RowHeaderWidth - { - get - { - return rowHeaderWidth; - } - set - { - if (DataGrid != null) - { - value = Math.Max(DataGrid.MinimumRowHeaderWidth(), value); - } - - if (rowHeaderWidth != value) - { - rowHeaderWidth = value; - OnRowHeaderWidthChanged(EventArgs.Empty); - } - } - } - - public event EventHandler RowHeaderWidthChanged - { - add => Events.AddHandler(EventRowHeaderWidth, value); - remove => Events.RemoveHandler(EventRowHeaderWidth, value); - } - - [ - SRCategory(nameof(SR.CatColors)), - SRDescription(nameof(SR.DataGridSelectionBackColorDescr)) - ] - public Color SelectionBackColor - { - get - { - return selectionBackBrush.Color; - } - set - { - if (isDefaultTableStyle) - { - throw new ArgumentException(string.Format(SR.DataGridDefaultTableSet, nameof(SelectionBackColor))); - } - - if (System.Windows.Forms.DataGrid.IsTransparentColor(value)) - { - throw new ArgumentException(SR.DataGridTableStyleTransparentSelectionBackColorNotAllowed, nameof(value)); - } - - if (value.IsEmpty) - { - throw new ArgumentException(string.Format(SR.DataGridEmptyColor, nameof(SelectionBackColor)), nameof(value)); - } - - if (!value.Equals(selectionBackBrush.Color)) - { - selectionBackBrush = new SolidBrush(value); - InvalidateInside(); - OnSelectionBackColorChanged(EventArgs.Empty); - } - } - } - - public event EventHandler SelectionBackColorChanged - { - add => Events.AddHandler(EventSelectionBackColor, value); - remove => Events.RemoveHandler(EventSelectionBackColor, value); - } - - internal SolidBrush SelectionBackBrush - { - get - { - return selectionBackBrush; - } - } - - internal SolidBrush SelectionForeBrush - { - get - { - return selectionForeBrush; - } - } - - protected bool ShouldSerializeSelectionBackColor() - { - return !DefaultSelectionBackBrush.Equals(selectionBackBrush); - } - - public void ResetSelectionBackColor() - { - if (ShouldSerializeSelectionBackColor()) - { - SelectionBackColor = DefaultSelectionBackBrush.Color; - } - } - - [ - Description("The foreground color for the current data grid row"), - SRCategory(nameof(SR.CatColors)), - SRDescription(nameof(SR.DataGridSelectionForeColorDescr)) - ] - public Color SelectionForeColor - { - get - { - return selectionForeBrush.Color; - } - set - { - if (isDefaultTableStyle) - { - throw new ArgumentException(string.Format(SR.DataGridDefaultTableSet, nameof(SelectionForeColor))); - } - - if (value.IsEmpty) - { - throw new ArgumentException(string.Format(SR.DataGridEmptyColor, nameof(SelectionForeColor)), nameof(value)); - } - - if (!value.Equals(selectionForeBrush.Color)) - { - selectionForeBrush = new SolidBrush(value); - InvalidateInside(); - OnSelectionForeColorChanged(EventArgs.Empty); - } - } - } - - public event EventHandler SelectionForeColorChanged - { - add => Events.AddHandler(EventSelectionForeColor, value); - remove => Events.RemoveHandler(EventSelectionForeColor, value); - } - - protected virtual bool ShouldSerializeSelectionForeColor() - { - return !SelectionForeBrush.Equals(DefaultSelectionForeBrush); - } - - public void ResetSelectionForeColor() - { - if (ShouldSerializeSelectionForeColor()) - { - SelectionForeColor = DefaultSelectionForeBrush.Color; - } - } - - // will need this function from the dataGrid - // - private void InvalidateInside() - { - if (DataGrid != null) - { - DataGrid.InvalidateInside(); - } - } - - public static readonly DataGridTableStyle DefaultTableStyle = new DataGridTableStyle(true); - - /// - /// Initializes a new instance of the class. - /// - public DataGridTableStyle(bool isDefaultTableStyle) - { - gridColumns = new GridColumnStylesCollection(this, isDefaultTableStyle); - gridColumns.CollectionChanged += new CollectionChangeEventHandler(OnColumnCollectionChanged); - this.isDefaultTableStyle = isDefaultTableStyle; - } - - public DataGridTableStyle() : this(false) - { - } - - /// - /// Initializes a new instance of the class with the specified - /// . - /// - public DataGridTableStyle(CurrencyManager listManager) : this() - { - Debug.Assert(listManager != null, "the DataGridTabel cannot use a null listManager"); - mappingName = listManager.GetListName(); - // set up the Relations and the columns - SetGridColumnStylesCollection(listManager); - } - - internal void SetRelationsList(CurrencyManager listManager) - { - PropertyDescriptorCollection propCollection = listManager.GetItemProperties(); - Debug.Assert(!IsDefault, "the grid can set the relations only on a table that was manually added by the user"); - int propCount = propCollection.Count; - if (relationsList.Count > 0) - { - relationsList.Clear(); - } - - for (int i = 0; i < propCount; i++) - { - PropertyDescriptor prop = propCollection[i]; - Debug.Assert(prop != null, "prop is null: how that happened?"); - if (PropertyDescriptorIsARelation(prop)) - { - // relation - relationsList.Add(prop.Name); - } - } - } - - internal void SetGridColumnStylesCollection(CurrencyManager listManager) - { - // when we are setting the gridColumnStyles, do not handle any gridColumnCollectionChanged events - gridColumns.CollectionChanged -= new CollectionChangeEventHandler(OnColumnCollectionChanged); - - PropertyDescriptorCollection propCollection = listManager.GetItemProperties(); - - // we need to clear the relations list - if (relationsList.Count > 0) - { - relationsList.Clear(); - } - - Debug.Assert(propCollection != null, "propCollection is null: how that happened?"); - int propCount = propCollection.Count; - for (int i = 0; i < propCount; i++) - { - PropertyDescriptor prop = propCollection[i]; - Debug.Assert(prop != null, "prop is null: how that happened?"); - // do not take into account the properties that are browsable. - if (!prop.IsBrowsable) - { - continue; - } - - if (PropertyDescriptorIsARelation(prop)) - { - // relation - relationsList.Add(prop.Name); - } - else - { - // column - DataGridColumnStyle col = CreateGridColumn(prop, isDefaultTableStyle); - if (isDefaultTableStyle) - { - gridColumns.AddDefaultColumn(col); - } - else - { - col.MappingName = prop.Name; - col.HeaderText = prop.Name; - gridColumns.Add(col); - } - } - } - - // now we are able to handle the collectionChangeEvents - gridColumns.CollectionChanged += new CollectionChangeEventHandler(OnColumnCollectionChanged); - } - - private static bool PropertyDescriptorIsARelation(PropertyDescriptor prop) - { - return typeof(IList).IsAssignableFrom(prop.PropertyType) && !typeof(Array).IsAssignableFrom(prop.PropertyType); - } - - internal protected virtual DataGridColumnStyle CreateGridColumn(PropertyDescriptor prop) - { - return CreateGridColumn(prop, false); - } - - internal protected virtual DataGridColumnStyle CreateGridColumn(PropertyDescriptor prop, bool isDefault) - { - if (prop == null) - { - throw new ArgumentNullException(nameof(prop)); - } - - DataGridColumnStyle ret = null; - Type dataType = prop.PropertyType; - - if (dataType.Equals(typeof(bool))) - { - ret = new DataGridBoolColumn(prop, isDefault); - } - else if (dataType.Equals(typeof(string))) - { - ret = new DataGridTextBoxColumn(prop, isDefault); - } - else if (dataType.Equals(typeof(DateTime))) - { - ret = new DataGridTextBoxColumn(prop, "d", isDefault); - } - else if (dataType.Equals(typeof(short)) || - dataType.Equals(typeof(int)) || - dataType.Equals(typeof(long)) || - dataType.Equals(typeof(ushort)) || - dataType.Equals(typeof(uint)) || - dataType.Equals(typeof(ulong)) || - dataType.Equals(typeof(decimal)) || - dataType.Equals(typeof(double)) || - dataType.Equals(typeof(float)) || - dataType.Equals(typeof(byte)) || - dataType.Equals(typeof(sbyte))) - { - ret = new DataGridTextBoxColumn(prop, "G", isDefault); - } - else - { - ret = new DataGridTextBoxColumn(prop, isDefault); - } - return ret; - } - - internal void ResetRelationsList() - { - if (isDefaultTableStyle) - { - relationsList.Clear(); - } - } - - // =------------------------------------------------------------------ - // = Properties - // =------------------------------------------------------------------ - - /// - /// Gets the name of this grid table. - /// - [Editor("System.Windows.Forms.Design.DataGridTableStyleMappingNameEditor, " + AssemblyRef.SystemDesign, typeof(Drawing.Design.UITypeEditor)), DefaultValue("")] - public string MappingName - { - get - { - return mappingName; - } - set - { - if (value == null) - { - value = string.Empty; - } - - if (value.Equals(mappingName)) - { - return; - } - - string originalMappingName = MappingName; - mappingName = value; - - // this could throw - try - { - if (DataGrid != null) - { - DataGrid.TableStyles.CheckForMappingNameDuplicates(this); - } - } - catch - { - mappingName = originalMappingName; - throw; - } - OnMappingNameChanged(EventArgs.Empty); - } - } - - public event EventHandler MappingNameChanged - { - add => Events.AddHandler(EventMappingName, value); - remove => Events.RemoveHandler(EventMappingName, value); - } - - /// - /// Gets the - /// list of relation objects for the grid table. - /// - internal ArrayList RelationsList - { - get - { - return relationsList; - } - } - - /// - /// Gets the collection of columns drawn for this table. - /// - [ - Localizable(true), - DesignerSerializationVisibility(DesignerSerializationVisibility.Content) - ] - public virtual GridColumnStylesCollection GridColumnStyles - { - get - { - return gridColumns; - } - } - - /// - /// Gets or sets the - /// control displaying the table. - /// - internal void SetInternalDataGrid(DataGrid dG, bool force) - { - if (dataGrid != null && dataGrid.Equals(dG) && !force) - { - return; - } - else - { - dataGrid = dG; - if (dG != null && dG.Initializing) - { - return; - } - - int nCols = gridColumns.Count; - for (int i = 0; i < nCols; i++) - { - gridColumns[i].SetDataGridInternalInColumn(dG); - } - } - } - - /// - /// Gets or sets the control for the drawn table. - /// - [Browsable(false)] - public virtual DataGrid DataGrid - { - get - { - return dataGrid; - } - set - { - SetInternalDataGrid(value, true); - } - } - - /// - /// Gets or sets a value indicating whether columns can be - /// edited. - /// - [DefaultValue(false)] - public virtual bool ReadOnly - { - get - { - return readOnly; - } - set - { - if (readOnly != value) - { - readOnly = value; - OnReadOnlyChanged(EventArgs.Empty); - } - } - } - - public event EventHandler ReadOnlyChanged - { - add => Events.AddHandler(EventReadOnly, value); - remove => Events.RemoveHandler(EventReadOnly, value); - } - - // =------------------------------------------------------------------ - // = Methods - // =------------------------------------------------------------------ - - /// - /// Requests an edit operation. - /// - public bool BeginEdit(DataGridColumnStyle gridColumn, int rowNumber) - { - DataGrid grid = DataGrid; - if (grid == null) - { - return false; - } - else - { - return grid.BeginEdit(gridColumn, rowNumber); - } - } - - /// - /// Requests an end to an edit - /// operation. - /// - public bool EndEdit(DataGridColumnStyle gridColumn, int rowNumber, bool shouldAbort) - { - DataGrid grid = DataGrid; - if (grid == null) - { - return false; - } - else - { - return grid.EndEdit(gridColumn, rowNumber, shouldAbort); - } - } - - internal void InvalidateColumn(DataGridColumnStyle column) - { - int index = GridColumnStyles.IndexOf(column); - if (index >= 0 && DataGrid != null) - { - DataGrid.InvalidateColumn(index); - } - } - - private void OnColumnCollectionChanged(object sender, CollectionChangeEventArgs e) - { - gridColumns.CollectionChanged -= new CollectionChangeEventHandler(OnColumnCollectionChanged); - - try - { - DataGrid grid = DataGrid; - DataGridColumnStyle col = e.Element as DataGridColumnStyle; - if (e.Action == CollectionChangeAction.Add) - { - if (col != null) - { - col.SetDataGridInternalInColumn(grid); - } - } - else if (e.Action == CollectionChangeAction.Remove) - { - if (col != null) - { - col.SetDataGridInternalInColumn(null); - } - } - else - { - // refresh - Debug.Assert(e.Action == CollectionChangeAction.Refresh, "there are only Add, Remove and Refresh in the CollectionChangeAction"); - // if we get a column in this collectionChangeEventArgs it means - // that the propertyDescriptor in that column changed. - if (e.Element != null) - { - for (int i = 0; i < gridColumns.Count; i++) - { - gridColumns[i].SetDataGridInternalInColumn(null); - } - } - } - - if (grid != null) - { - grid.OnColumnCollectionChanged(this, e); - } - } - finally - { - gridColumns.CollectionChanged += new CollectionChangeEventHandler(OnColumnCollectionChanged); - } - } - -#if false - /// - /// The DataColumnCollection class actually wires up this - /// event handler to the PropertyChanged events of - /// a DataGridTable's columns. - /// - internal void OnColumnChanged(object sender, PropertyChangedEvent event) { - if (event.PropertyName.Equals("Visible")) - GenerateVisibleColumnsCache(); - } -#endif - protected virtual void OnReadOnlyChanged(EventArgs e) - { - if (Events[EventReadOnly] is EventHandler eh) - { - eh(this, e); - } - } - - protected virtual void OnMappingNameChanged(EventArgs e) - { - if (Events[EventMappingName] is EventHandler eh) - { - eh(this, e); - } - } - - protected virtual void OnAlternatingBackColorChanged(EventArgs e) - { - if (Events[EventAlternatingBackColor] is EventHandler eh) - { - eh(this, e); - } - } - - protected virtual void OnForeColorChanged(EventArgs e) - { - if (Events[EventForeColor] is EventHandler eh) - { - eh(this, e); - } - } - - protected virtual void OnBackColorChanged(EventArgs e) - { - if (Events[EventBackColor] is EventHandler eh) - { - eh(this, e); - } - } - - protected virtual void OnAllowSortingChanged(EventArgs e) - { - if (Events[EventAllowSorting] is EventHandler eh) - { - eh(this, e); - } - } - protected virtual void OnGridLineColorChanged(EventArgs e) - { - if (Events[EventGridLineColor] is EventHandler eh) - { - eh(this, e); - } - } - protected virtual void OnGridLineStyleChanged(EventArgs e) - { - if (Events[EventGridLineStyle] is EventHandler eh) - { - eh(this, e); - } - } - protected virtual void OnHeaderBackColorChanged(EventArgs e) - { - if (Events[EventHeaderBackColor] is EventHandler eh) - { - eh(this, e); - } - } - protected virtual void OnHeaderFontChanged(EventArgs e) - { - if (Events[EventHeaderFont] is EventHandler eh) - { - eh(this, e); - } - } - protected virtual void OnHeaderForeColorChanged(EventArgs e) - { - if (Events[EventHeaderForeColor] is EventHandler eh) - { - eh(this, e); - } - } - protected virtual void OnLinkColorChanged(EventArgs e) - { - if (Events[EventLinkColor] is EventHandler eh) - { - eh(this, e); - } - } - protected virtual void OnLinkHoverColorChanged(EventArgs e) - { - if (Events[EventLinkHoverColor] is EventHandler eh) - { - eh(this, e); - } - } - protected virtual void OnPreferredRowHeightChanged(EventArgs e) - { - if (Events[EventPreferredRowHeight] is EventHandler eh) - { - eh(this, e); - } - } - protected virtual void OnPreferredColumnWidthChanged(EventArgs e) - { - if (Events[EventPreferredColumnWidth] is EventHandler eh) - { - eh(this, e); - } - } - protected virtual void OnColumnHeadersVisibleChanged(EventArgs e) - { - if (Events[EventColumnHeadersVisible] is EventHandler eh) - { - eh(this, e); - } - } - protected virtual void OnRowHeadersVisibleChanged(EventArgs e) - { - if (Events[EventRowHeadersVisible] is EventHandler eh) - { - eh(this, e); - } - } - protected virtual void OnRowHeaderWidthChanged(EventArgs e) - { - if (Events[EventRowHeaderWidth] is EventHandler eh) - { - eh(this, e); - } - } - protected virtual void OnSelectionForeColorChanged(EventArgs e) - { - if (Events[EventSelectionForeColor] is EventHandler eh) - { - eh(this, e); - } - } - protected virtual void OnSelectionBackColorChanged(EventArgs e) - { - if (Events[EventSelectionBackColor] is EventHandler eh) - { - eh(this, e); - } - } - - protected override void Dispose(bool disposing) - { - if (disposing) - { - GridColumnStylesCollection cols = GridColumnStyles; - if (cols != null) - { - for (int i = 0; i < cols.Count; i++) - { - cols[i].Dispose(); - } - } - } - base.Dispose(disposing); - } - - internal bool IsDefault - { - get - { - return isDefaultTableStyle; - } - } - - } -} diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTextBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTextBox.cs deleted file mode 100644 index f601101481a..00000000000 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTextBox.cs +++ /dev/null @@ -1,298 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.ComponentModel; -using System.Runtime.InteropServices; -using static Interop; - -namespace System.Windows.Forms -{ - /// - /// Represents a control that is hosted in a - /// . - /// - [ - ComVisible(true), - ClassInterface(ClassInterfaceType.AutoDispatch), - ToolboxItem(false), - DesignTimeVisible(false) - ] - public class DataGridTextBox : TextBox - { - private bool isInEditOrNavigateMode = true; - - // only needed to signal the dataGrid that an edit - // takes place - private DataGrid dataGrid; - - public DataGridTextBox() : base() - { - TabStop = false; - } - /// - /// Sets the to which this control belongs. - /// - public void SetDataGrid(DataGrid parentGrid) - { - dataGrid = parentGrid; - } - - protected override void WndProc(ref Message m) - { - // but what if we get a CtrlV? - // what about deleting from the menu? - if (m.Msg == WindowMessages.WM_PASTE || m.Msg == WindowMessages.WM_CUT || m.Msg == WindowMessages.WM_CLEAR) - { - IsInEditOrNavigateMode = false; - dataGrid.ColumnStartedEditing(Bounds); - } - - base.WndProc(ref m); - - } - - protected override void OnMouseWheel(MouseEventArgs e) - { - dataGrid.TextBoxOnMouseWheel(e); - } - - protected override void OnKeyPress(KeyPressEventArgs e) - { - base.OnKeyPress(e); - - // Shift-Space should not cause the grid to - // be put in edit mode - if (e.KeyChar == ' ' && (Control.ModifierKeys & Keys.Shift) == Keys.Shift) - { - return; - } - - // if the edit box is in ReadOnly mode, then do not tell the DataGrid about the - // edit - if (ReadOnly) - { - return; - } - - // Ctrl-* should not put the grid in edit mode - if ((Control.ModifierKeys & Keys.Control) == Keys.Control && ((Control.ModifierKeys & Keys.Alt) == 0)) - { - return; - } - - IsInEditOrNavigateMode = false; - - // let the DataGrid know about the edit - dataGrid.ColumnStartedEditing(Bounds); - } - - protected internal override bool ProcessKeyMessage(ref Message m) - { - Keys key = (Keys)unchecked((int)(long)m.WParam); - Keys modifierKeys = ModifierKeys; - - if ((key | modifierKeys) == Keys.Enter || (key | modifierKeys) == Keys.Escape || ((key | modifierKeys) == (Keys.Enter | Keys.Control)) - ) - { - // enter and escape keys are sent directly to the DataGrid - // for those keys, eat the WM_CHAR part of the KeyMessage - // - if (m.Msg == WindowMessages.WM_CHAR) - { - return true; - } - - return ProcessKeyPreview(ref m); - } - - if (m.Msg == WindowMessages.WM_CHAR) - { - if (key == Keys.LineFeed) // eat the LineFeed we get when the user presses Ctrl-Enter in a gridTextBox - { - return true; - } - - return ProcessKeyEventArgs(ref m); - } - - // now the edit control will be always on top of the grid - // we only want to process the WM_KEYUP message ( the same way the grid was doing when the grid was getting all - // the keys ) - if (m.Msg == WindowMessages.WM_KEYUP) - { - return true; - } - - Keys keyData = key & Keys.KeyCode; - - switch (keyData) - { - case Keys.Right: - // here is the deal with Keys.Right: - // if the end of the selection is at the end of the string - // send this character to the dataGrid - // else, process the KeyEvent - // - if (SelectionStart + SelectionLength == Text.Length) - { - return ProcessKeyPreview(ref m); - } - - return ProcessKeyEventArgs(ref m); - case Keys.Left: - // if the end of the selection is at the begining of the string - // or if the entire text is selected and we did not start editing - // send this character to the dataGrid - // else, process the KeyEvent - // - if (SelectionStart + SelectionLength == 0 || - (IsInEditOrNavigateMode && SelectionLength == Text.Length)) - { - return ProcessKeyPreview(ref m); - } - - return ProcessKeyEventArgs(ref m); - case Keys.Down: - // if the end of the selection is on the last line of the text then - // send this character to the dataGrid - // else, process the KeyEvent - // - int end = SelectionStart + SelectionLength; - if (Text.IndexOf("\r\n", end) == -1) - { - return ProcessKeyPreview(ref m); - } - - return ProcessKeyEventArgs(ref m); - case Keys.Up: - // if the end of the selection is on the first line of the text then - // send this character to the dataGrid - // else, process the KeyEvent - // - if (Text.IndexOf("\r\n") < 0 || SelectionStart + SelectionLength < Text.IndexOf("\r\n")) - { - return ProcessKeyPreview(ref m); - } - - return ProcessKeyEventArgs(ref m); - case Keys.Home: - case Keys.End: - if (SelectionLength == Text.Length) - { - return ProcessKeyPreview(ref m); - } - else - { - return ProcessKeyEventArgs(ref m); - } - - case Keys.Prior: - case Keys.Next: - case Keys.Oemplus: - case Keys.Add: - case Keys.OemMinus: - case Keys.Subtract: - if (IsInEditOrNavigateMode) - { - // this will ultimately call parent's ProcessKeyPreview - // in our case, DataGrid's ProcessKeyPreview - return ProcessKeyPreview(ref m); - } - else - { - return ProcessKeyEventArgs(ref m); - } - case Keys.Space: - if (IsInEditOrNavigateMode && (Control.ModifierKeys & Keys.Shift) == Keys.Shift) - { - // when we get a SHIFT-SPACEBAR message, disregard the WM_CHAR part of the message - if (m.Msg == WindowMessages.WM_CHAR) - { - return true; - } - - // if the user pressed the SHIFT key at the same time with - // the space key, send the key message to the DataGrid - return ProcessKeyPreview(ref m); - } - return ProcessKeyEventArgs(ref m); - case Keys.A: - if (IsInEditOrNavigateMode && (Control.ModifierKeys & Keys.Control) == Keys.Control) - { - // when we get a Control-A message, disregard the WM_CHAR part of the message - if (m.Msg == WindowMessages.WM_CHAR) - { - return true; - } - - // if the user pressed the Control key at the same time with - // the space key, send the key message to the DataGrid - return ProcessKeyPreview(ref m); - } - return ProcessKeyEventArgs(ref m); - case Keys.F2: - IsInEditOrNavigateMode = false; - // do not select all the text, but - // position the caret at the end of the text - SelectionStart = Text.Length; - return true; - case Keys.Delete: - if (IsInEditOrNavigateMode) - { - // pass the delete to the parent, in our case, the DataGrid - // if the dataGrid used the key, then we aren't gonne - // use it anymore, else we are - if (ProcessKeyPreview(ref m)) - { - return true; - } - else - { - // the edit control will use the - // delete key: we are in Edit mode now: - IsInEditOrNavigateMode = false; - dataGrid.ColumnStartedEditing(Bounds); - - return ProcessKeyEventArgs(ref m); - } - } - else - { - return ProcessKeyEventArgs(ref m); - } - - case Keys.Tab: - // the TextBox gets the Control-Tab messages, - // not the parent - if ((ModifierKeys & Keys.Control) == Keys.Control) - { - return ProcessKeyPreview(ref m); - } - else - { - return ProcessKeyEventArgs(ref m); - } - - default: - return ProcessKeyEventArgs(ref m); - } - } - - public bool IsInEditOrNavigateMode - { - get - { - return isInEditOrNavigateMode; - } - set - { - isInEditOrNavigateMode = value; - if (value) - { - SelectAll(); - } - } - } - } -} diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTextBoxColumn.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTextBoxColumn.cs deleted file mode 100644 index aa276985acc..00000000000 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTextBoxColumn.cs +++ /dev/null @@ -1,640 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.ComponentModel; -using System.Diagnostics; -using System.Drawing; -using System.Globalization; - -namespace System.Windows.Forms -{ - /// - /// Hosts a System.Windows.Forms.TextBox control in a cell of a System.Windows.Forms.DataGridColumnStyle for editing strings. - /// - public class DataGridTextBoxColumn : DataGridColumnStyle - { - // ui State - private readonly int xMargin = 2; - private readonly int yMargin = 1; - // private int fontHandle = 0; - private string format = null; - private TypeConverter typeConverter; - private IFormatProvider formatInfo = null; - private Reflection.MethodInfo parseMethod; - - // hosted control - private readonly DataGridTextBox edit; - - // editing state - private string oldValue = null; - private int editRow = -1; - - /// - /// Initializes a new instance of the System.Windows.Forms.DataGridTextBoxColumn - /// class. - /// - public DataGridTextBoxColumn() : this(null, null) - { - } - - /// - /// Initializes a new instance of a System.Windows.Forms.DataGridTextBoxColumn with - /// a specified System.Data.DataColumn. - /// - public DataGridTextBoxColumn(PropertyDescriptor prop) - : this(prop, null, false) - { - } - - /// - /// Initializes a new instance of a System.Windows.Forms.DataGridTextBoxColumn. with - /// the specified System.Data.DataColumn and System.Windows.Forms.ComponentModel.Format. - /// - public DataGridTextBoxColumn(PropertyDescriptor prop, string format) : this(prop, format, false) { } - - public DataGridTextBoxColumn(PropertyDescriptor prop, string format, bool isDefault) : base(prop, isDefault) - { - edit = new DataGridTextBox - { - BorderStyle = BorderStyle.None, - Multiline = true, - AcceptsReturn = true, - Visible = false - }; - Format = format; - } - - public DataGridTextBoxColumn(PropertyDescriptor prop, bool isDefault) : this(prop, null, isDefault) { } - - // =------------------------------------------------------------------ - // = Properties - // =------------------------------------------------------------------ - - /// - /// Gets the hosted System.Windows.Forms.TextBox control. - /// - [Browsable(false)] - public virtual TextBox TextBox - { - get - { - return edit; - } - } - - internal override bool KeyPress(int rowNum, Keys keyData) - { - if (edit.IsInEditOrNavigateMode) - { - return base.KeyPress(rowNum, keyData); - } - - // if the edit box is editing, then - // pass this keystroke to the edit box - // - return false; - } - - /// - /// Adds a System.Windows.Forms.TextBox control to the System.Windows.Forms.DataGrid control's System.Windows.Forms.Control.ControlCollection - /// . - /// - protected override void SetDataGridInColumn(DataGrid value) - { - base.SetDataGridInColumn(value); - if (edit.ParentInternal != null) - { - edit.ParentInternal.Controls.Remove(edit); - } - if (value != null) - { - value.Controls.Add(edit); - } - - // we have to tell the edit control about its dataGrid - edit.SetDataGrid(value); - } - - /* CUT as part of the new DataGridTableStyleSheet thing - public override Font Font { - set { - base.Font = value; - Font f = base.Font; - edit.Font = f; - // if (f != null) { - // fontHandle = f.Handle; - // } - } - } - */ - - /// - /// Gets or sets the System.Windows.Forms.ComponentModel.Format for the System.Windows.Forms.DataGridTextBoxColumn - /// . - /// - [ - SRDescription(nameof(SR.FormatControlFormatDescr)), - DefaultValue(null) - ] - public override PropertyDescriptor PropertyDescriptor - { - set - { - base.PropertyDescriptor = value; - if (PropertyDescriptor != null) - { - if (PropertyDescriptor.PropertyType != typeof(object)) - { - typeConverter = TypeDescriptor.GetConverter(PropertyDescriptor.PropertyType); - parseMethod = PropertyDescriptor.PropertyType.GetMethod("Parse", new Type[] { typeof(string), typeof(IFormatProvider) }); - } - } - } - } - - // add the corresponding value Editor: rip one from the valueEditor for the DisplayMember in the - // format object - [DefaultValue(null), Editor("System.Windows.Forms.Design.DataGridColumnStyleFormatEditor, " + AssemblyRef.SystemDesign, typeof(Drawing.Design.UITypeEditor))] - public string Format - { - get - { - return format; - } - set - { - if (value == null) - { - value = string.Empty; - } - - if (format == null || !format.Equals(value)) - { - format = value; - - // if the associated typeConverter cannot convert from string, - // then we can't modify the column value. hence, make it readOnly - // - if (format.Length == 0) - { - if (typeConverter != null && !typeConverter.CanConvertFrom(typeof(string))) - { - ReadOnly = true; - } - } - - Invalidate(); - } - } - } - - [Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced)] - public IFormatProvider FormatInfo - { - get - { - return formatInfo; - } - set - { - if (formatInfo == null || !formatInfo.Equals(value)) - { - formatInfo = value; - } - } - } - - public override bool ReadOnly - { - get - { - return base.ReadOnly; - } - set - { - // if the gridColumn is can't convert the string to - // the backGround propertyDescriptor, then make the column ReadOnly - if (!value && (format == null || format.Length == 0)) - { - if (typeConverter != null && !typeConverter.CanConvertFrom(typeof(string))) - { - return; - } - } - base.ReadOnly = value; - } - } - - // =------------------------------------------------------------------ - // = Methods - // =------------------------------------------------------------------ - - private void DebugOut(string s) - { - Debug.WriteLineIf(CompModSwitches.DGEditColumnEditing.TraceVerbose, "DGEditColumnEditing: " + s); - } - - // will hide the edit control - /// - /// Informs the column the focus is being conceded. - /// - protected internal override void ConcedeFocus() - { - edit.Bounds = Rectangle.Empty; - // edit.Visible = false; - // HideEditBox(); - } - - /// - /// Hides the System.Windows.Forms.TextBox - /// control and moves the focus to the System.Windows.Forms.DataGrid - /// control. - /// - protected void HideEditBox() - { - bool wasFocused = edit.Focused; - edit.Visible = false; - - // it seems that edit.Visible = false will take away the focus from - // the edit control. And this means that we will not give the focus to the grid - // If all the columns would have an edit control this would not be bad - // ( or if the grid is the only control on the form ), - // but when we have a DataGridBoolColumn then the focus will be taken away - // by the next control in the form. - // - // if (edit.Focused && this.DataGridTableStyle.DataGrid.CanFocus) { - - // when the user deletes the current ( ie active ) column from the - // grid, the grid should still call EndEdit ( so that the changes that the user made - // before deleting the column will go to the backEnd) - // however, in that situation, we are left w/ the editColumn which is not parented. - // the grid will call Edit to reset the EditColumn - if (wasFocused && DataGridTableStyle != null && DataGridTableStyle.DataGrid != null && DataGridTableStyle.DataGrid.CanFocus) - { - DataGridTableStyle.DataGrid.Focus(); - Debug.Assert(!edit.Focused, "the edit control just conceeded focus to the dataGrid"); - } - } - - protected internal override void UpdateUI(CurrencyManager source, int rowNum, string displayText) - { - edit.Text = GetText(GetColumnValueAtRow(source, rowNum)); - if (!edit.ReadOnly && displayText != null) - { - edit.Text = displayText; - } - } - - /// - /// Ends an edit operation on the System.Windows.Forms.DataGridColumnStyle - /// . - /// - protected void EndEdit() - { - edit.IsInEditOrNavigateMode = true; - DebugOut("Ending Edit"); - Invalidate(); - } - - /// - /// Returns the optimum width and - /// height of the cell in a specified row relative - /// to the specified value. - /// - protected internal override Size GetPreferredSize(Graphics g, object value) - { - Size extents = Size.Ceiling(g.MeasureString(GetText(value), DataGridTableStyle.DataGrid.Font)); - extents.Width += xMargin * 2 + DataGridTableStyle.GridLineWidth; - extents.Height += yMargin; - return extents; - } - - /// - /// Gets the height of a cell in a System.Windows.Forms.DataGridColumnStyle - /// . - /// - protected internal override int GetMinimumHeight() - { - // why + 3? cause we have to give some way to the edit box. - return FontHeight + yMargin + 3; - } - - /// - /// Gets the height to be used in for automatically resizing columns. - /// - protected internal override int GetPreferredHeight(Graphics g, object value) - { - int newLineIndex = 0; - int newLines = 0; - string valueString = GetText(value); - while (newLineIndex != -1 && newLineIndex < valueString.Length) - { - newLineIndex = valueString.IndexOf("\r\n", newLineIndex + 1); - newLines++; - } - - return FontHeight * newLines + yMargin; - } - - /// - /// Initiates a request to interrupt an edit procedure. - /// - protected internal override void Abort(int rowNum) - { - RollBack(); - HideEditBox(); - EndEdit(); - } - - // used for Alt0 functionality - /// - /// Enters a in the column. - /// - protected internal override void EnterNullValue() - { - if (ReadOnly) - { - return; - } - - // if the edit box is not visible, then - // do not put the edit text in it - if (!edit.Visible) - { - return; - } - - // if we are editing, then we should be able to enter alt-0 in a cell. - // - if (!edit.IsInEditOrNavigateMode) - { - return; - } - - edit.Text = NullText; - // edit.Visible = true; - edit.IsInEditOrNavigateMode = false; - // tell the dataGrid that there is an edit: - if (DataGridTableStyle != null && DataGridTableStyle.DataGrid != null) - { - DataGridTableStyle.DataGrid.ColumnStartedEditing(edit.Bounds); - } - } - - /// - /// Inititates a request to complete an editing procedure. - /// - protected internal override bool Commit(CurrencyManager dataSource, int rowNum) - { - // always hide the edit box - // HideEditBox(); - edit.Bounds = Rectangle.Empty; - - if (edit.IsInEditOrNavigateMode) - { - return true; - } - - try - { - object value = edit.Text; - if (NullText.Equals(value)) - { - value = Convert.DBNull; - edit.Text = NullText; - } - else if (format != null && format.Length != 0 && parseMethod != null && FormatInfo != null) - { - // use reflection to get the Parse method on the - // type of the propertyDescriptor. - value = (object)parseMethod.Invoke(null, new object[] { edit.Text, FormatInfo }); - if (value is IFormattable) - { - edit.Text = ((IFormattable)value).ToString(format, formatInfo); - } - else - { - edit.Text = value.ToString(); - } - } - else if (typeConverter != null && typeConverter.CanConvertFrom(typeof(string))) - { - value = typeConverter.ConvertFromString(edit.Text); - edit.Text = typeConverter.ConvertToString(value); - } - - SetColumnValueAtRow(dataSource, rowNum, value); - } - catch - { - // MessageBox.Show("There was an error caught setting field \"" - // + this.PropertyDescriptor.Name + "\" to the value \"" + edit.Text + "\"\n" - // + "The value is being rolled back to the original.\n" - // + "The error was a '" + e.Message + "' " + e.StackTrace - // , "Error commiting changes...", MessageBox.IconError); - // Debug.WriteLine(e.GetType().Name); - RollBack(); - return false; - } - DebugOut("OnCommit completed without Exception."); - EndEdit(); - return true; - } - - /// - /// Prepares a cell for editing. - /// - protected internal override void Edit(CurrencyManager source, - int rowNum, - Rectangle bounds, - bool readOnly, - string displayText, - bool cellIsVisible) - { - DebugOut("Begining Edit, rowNum :" + rowNum.ToString(CultureInfo.InvariantCulture)); - - Rectangle originalBounds = bounds; - - edit.ReadOnly = readOnly || ReadOnly || DataGridTableStyle.ReadOnly; - - edit.Text = GetText(GetColumnValueAtRow(source, rowNum)); - if (!edit.ReadOnly && displayText != null) - { - // tell the grid that we are changing stuff - DataGridTableStyle.DataGrid.ColumnStartedEditing(bounds); - // tell the edit control that the user changed it - edit.IsInEditOrNavigateMode = false; - edit.Text = displayText; - } - - if (cellIsVisible) - { - bounds.Offset(xMargin, 2 * yMargin); - bounds.Width -= xMargin; - bounds.Height -= 2 * yMargin; - DebugOut("edit bounds: " + bounds.ToString()); - edit.Bounds = bounds; - - edit.Visible = true; - - edit.TextAlign = Alignment; - } - else - { - edit.Bounds = Rectangle.Empty; - // edit.Bounds = originalBounds; - // edit.Visible = false; - } - - edit.RightToLeft = DataGridTableStyle.DataGrid.RightToLeft; - - edit.Focus(); - - editRow = rowNum; - - if (!edit.ReadOnly) - { - oldValue = edit.Text; - } - - // select the text even if the text box is read only - // because the navigation code in the DataGridTextBox::ProcessKeyMessage - // uses the SelectedText property - if (displayText == null) - { - edit.SelectAll(); - } - else - { - int end = edit.Text.Length; - edit.Select(end, 0); - } - - if (edit.Visible) - { - DataGridTableStyle.DataGrid.Invalidate(originalBounds); - } - } - - internal override string GetDisplayText(object value) - { - return GetText(value); - } - - private string GetText(object value) - { - if (value is DBNull) - { - return NullText; - } - else if (format != null && format.Length != 0 && (value is IFormattable)) - { - try - { - return ((IFormattable)value).ToString(format, formatInfo); - } - catch - { - // - } - } - else - { - // use the typeConverter: - if (typeConverter != null && typeConverter.CanConvertTo(typeof(string))) - { - return (string)typeConverter.ConvertTo(value, typeof(string)); - } - } - return (value != null ? value.ToString() : ""); - } - - /// - /// Paints the a System.Windows.Forms.DataGridColumnStyle with the specified System.Drawing.Graphics, - /// System.Drawing.Rectangle, DataView.Rectangle, and row number. - /// - protected internal override void Paint(Graphics g, Rectangle bounds, CurrencyManager source, int rowNum) - { - Paint(g, bounds, source, rowNum, false); - } - - /// - /// Paints a System.Windows.Forms.DataGridColumnStyle with the specified System.Drawing.Graphics, System.Drawing.Rectangle, DataView, row number, and alignment. - /// - protected internal override void Paint(Graphics g, Rectangle bounds, CurrencyManager source, int rowNum, bool alignToRight) - { - string text = GetText(GetColumnValueAtRow(source, rowNum)); - PaintText(g, bounds, text, alignToRight); - } - - /// - /// Paints a System.Windows.Forms.DataGridColumnStyle with the specified System.Drawing.Graphics, - /// System.Drawing.Rectangle, DataView.Rectangle, row number, background color, - /// and foreground color.. - /// - protected internal override void Paint(Graphics g, Rectangle bounds, CurrencyManager source, int rowNum, - Brush backBrush, Brush foreBrush, bool alignToRight) - { - string text = GetText(GetColumnValueAtRow(source, rowNum)); - PaintText(g, bounds, text, backBrush, foreBrush, alignToRight); - } - - /// - /// Draws the text and - /// rectangle at the given location with the specified alignment. - /// - protected void PaintText(Graphics g, Rectangle bounds, string text, bool alignToRight) - { - PaintText(g, bounds, text, DataGridTableStyle.BackBrush, DataGridTableStyle.ForeBrush, alignToRight); - } - - /// - /// Draws the text and rectangle at the specified location with the - /// specified colors and alignment. - /// - protected void PaintText(Graphics g, Rectangle textBounds, string text, Brush backBrush, Brush foreBrush, bool alignToRight) - { - /* - if (edit.Visible) - g.BackColor = BackColor; - */ - - Rectangle rect = textBounds; - - StringFormat format = new StringFormat(); - if (alignToRight) - { - format.FormatFlags |= StringFormatFlags.DirectionRightToLeft; - } - - format.Alignment = Alignment == HorizontalAlignment.Left ? StringAlignment.Near : Alignment == HorizontalAlignment.Center ? StringAlignment.Center : StringAlignment.Far; - - // do not wrap the text - // - format.FormatFlags |= StringFormatFlags.NoWrap; - - g.FillRectangle(backBrush, rect); - // by design, painting leaves a little padding around the rectangle. - // so do not deflate the rectangle. - rect.Offset(0, 2 * yMargin); - rect.Height -= 2 * yMargin; - g.DrawString(text, DataGridTableStyle.DataGrid.Font, foreBrush, rect, format); - format.Dispose(); - } - - private void RollBack() - { - Debug.Assert(!edit.IsInEditOrNavigateMode, "Must be editing to rollback changes..."); - edit.Text = oldValue; - } - - protected internal override void ReleaseHostedControl() - { - if (edit.ParentInternal != null) - { - edit.ParentInternal.Controls.Remove(edit); - } - } - } -} diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridToolTip.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridToolTip.cs deleted file mode 100644 index f3dd136d667..00000000000 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridToolTip.cs +++ /dev/null @@ -1,82 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Diagnostics; -using System.Drawing; -using System.Runtime.InteropServices; -using static Interop; - -namespace System.Windows.Forms -{ - // this class is basically a NativeWindow that does toolTipping - // should be one for the entire grid - internal class DataGridToolTip : MarshalByRefObject - { - // the toolTip control - private NativeWindow tipWindow = null; - - // the dataGrid which contains this toolTip - private readonly DataGrid dataGrid = null; - - // CONSTRUCTOR - public DataGridToolTip(DataGrid dataGrid) - { - Debug.Assert(dataGrid != null, "can't attach a tool tip to a null grid"); - this.dataGrid = dataGrid; - } - - // will ensure that the toolTip window was created - public void CreateToolTipHandle() - { - if (tipWindow == null || tipWindow.Handle == IntPtr.Zero) - { - NativeMethods.INITCOMMONCONTROLSEX icc = new NativeMethods.INITCOMMONCONTROLSEX - { - dwICC = NativeMethods.ICC_TAB_CLASSES - }; - icc.dwSize = Marshal.SizeOf(icc); - SafeNativeMethods.InitCommonControlsEx(icc); - CreateParams cparams = new CreateParams - { - Parent = dataGrid.Handle, - ClassName = NativeMethods.TOOLTIPS_CLASS, - Style = NativeMethods.TTS_ALWAYSTIP - }; - tipWindow = new NativeWindow(); - tipWindow.CreateHandle(cparams); - - User32.SendMessageW(tipWindow, WindowMessages.TTM_SETMAXTIPWIDTH, IntPtr.Zero, (IntPtr)SystemInformation.MaxWindowTrackSize.Width); - SafeNativeMethods.SetWindowPos(new HandleRef(tipWindow, tipWindow.Handle), NativeMethods.HWND_NOTOPMOST, 0, 0, 0, 0, NativeMethods.SWP_NOSIZE | NativeMethods.SWP_NOMOVE | NativeMethods.SWP_NOACTIVATE); - User32.SendMessageW(tipWindow, WindowMessages.TTM_SETDELAYTIME, (IntPtr)ComCtl32.TTDT.INITIAL, (IntPtr)0); - } - } - - public void AddToolTip(string toolTipString, IntPtr toolTipId, Rectangle iconBounds) - { - Debug.Assert(tipWindow != null && tipWindow.Handle != IntPtr.Zero, "the tipWindow was not initialized, bailing out"); - if (iconBounds.IsEmpty) - throw new ArgumentNullException(nameof(iconBounds), SR.DataGridToolTipEmptyIcon); - - if (toolTipString == null) - throw new ArgumentNullException(nameof(toolTipString)); - - var info = new ComCtl32.ToolInfoWrapper(dataGrid, toolTipId, ComCtl32.TTF.SUBCLASS, toolTipString, iconBounds); - info.SendMessage(tipWindow, WindowMessages.TTM_ADDTOOLW); - } - - public void RemoveToolTip(IntPtr toolTipId) - { - var info = new ComCtl32.ToolInfoWrapper(dataGrid, toolTipId); - info.SendMessage(tipWindow, WindowMessages.TTM_DELTOOLW); - } - - // will destroy the tipWindow - public void Destroy() - { - Debug.Assert(tipWindow != null, "how can one destroy a null window"); - tipWindow.DestroyHandle(); - tipWindow = null; - } - } -} diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ErrorProvider.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ErrorProvider.cs index 877a35fb9b8..ab0ce74638c 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ErrorProvider.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ErrorProvider.cs @@ -676,7 +676,7 @@ public void Clear() /// public bool CanExtend(object extendee) { - return extendee is Control && !(extendee is Form) && !(extendee is ToolBar); + return extendee is Control && !(extendee is Form); } /// @@ -1072,7 +1072,7 @@ public void Remove(ControlItem item) if (_tipWindow != null) { var info = new ComCtl32.ToolInfoWrapper(this, item.Id); - info .SendMessage(_tipWindow, WindowMessages.TTM_DELTOOLW); + info.SendMessage(_tipWindow, WindowMessages.TTM_DELTOOLW); } if (items.Count == 0) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Form.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Form.cs index 813f15ecace..8946d5edd44 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Form.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Form.cs @@ -121,11 +121,6 @@ public partial class Form : ContainerControl private static readonly int PropDefaultButton = PropertyStore.CreateKey(); private static readonly int PropDialogOwner = PropertyStore.CreateKey(); - private static readonly int PropMainMenu = PropertyStore.CreateKey(); - private static readonly int PropDummyMenu = PropertyStore.CreateKey(); - private static readonly int PropCurMenu = PropertyStore.CreateKey(); - private static readonly int PropMergedMenu = PropertyStore.CreateKey(); - private static readonly int PropOwner = PropertyStore.CreateKey(); private static readonly int PropOwnedForms = PropertyStore.CreateKey(); private static readonly int PropMaximizedBounds = PropertyStore.CreateKey(); @@ -1117,21 +1112,7 @@ public DialogResult DialogResult internal override bool HasMenu { - get - { - bool hasMenu = false; - - // Verify that the menu actually contains items so that any - // size calculations will only include a menu height if the menu actually exists. - // Note that Windows will not draw a menu bar for a menu that does not contain - // any items. - Menu menu = Menu; - if (TopLevel && menu != null && menu.ItemCount > 0) - { - hasMenu = true; - } - return hasMenu; - } + get => false; } /// @@ -1492,7 +1473,7 @@ public MenuStrip MainMenuStrip set { Properties.SetObject(PropMainMenuStrip, value); - if (IsHandleCreated && Menu == null) + if (IsHandleCreated) { UpdateMenuHandles(); } @@ -1522,55 +1503,6 @@ public new Padding Margin remove => base.MarginChanged -= value; } - /// - /// Gets or sets the - /// that is displayed in the form. - /// - [ - SRCategory(nameof(SR.CatWindowStyle)), - DefaultValue(null), - SRDescription(nameof(SR.FormMenuDescr)), - TypeConverter(typeof(ReferenceConverter)), - Browsable(false), - ] - public MainMenu Menu - { - get - { - return (MainMenu)Properties.GetObject(PropMainMenu); - } - set - { - MainMenu mainMenu = Menu; - - if (mainMenu != value) - { - if (mainMenu != null) - { - mainMenu.form = null; - } - - Properties.SetObject(PropMainMenu, value); - - if (value != null) - { - if (value.form != null) - { - value.form.Menu = null; - } - value.form = this; - } - - if (formState[FormStateSetClientSize] == 1 && !IsHandleCreated) - { - ClientSize = ClientSize; - } - - MenuChanged(Windows.Forms.Menu.CHANGE_ITEMS, value); - } - } - } - /// /// Gets the minimum size the form can be resized to. /// @@ -1801,7 +1733,6 @@ private Form MdiParentInternal } } - InvalidateMergedMenu(); UpdateMenuHandles(); } finally @@ -1824,65 +1755,6 @@ private MdiControlStrip MdiControlStrip set { Properties.SetObject(PropMdiControlStrip, value); } } - /// - /// Gets the merged menu for the - /// form. - /// - [ - SRCategory(nameof(SR.CatWindowStyle)), - Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced), - DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), - SRDescription(nameof(SR.FormMergedMenuDescr)), - ] - public MainMenu MergedMenu - { - get - { - return MergedMenuPrivate; - } - } - - private MainMenu MergedMenuPrivate - { - get - { - Form formMdiParent = (Form)Properties.GetObject(PropFormMdiParent); - if (formMdiParent == null) - { - return null; - } - - MainMenu mergedMenu = (MainMenu)Properties.GetObject(PropMergedMenu); - if (mergedMenu != null) - { - return mergedMenu; - } - - MainMenu parentMenu = formMdiParent.Menu; - MainMenu mainMenu = Menu; - - if (mainMenu == null) - { - return parentMenu; - } - - if (parentMenu == null) - { - return mainMenu; - } - - // Create a menu that merges the two and save it for next time. - mergedMenu = new MainMenu - { - ownerForm = this - }; - mergedMenu.MergeMenu(parentMenu); - mergedMenu.MergeMenu(mainMenu); - Properties.SetObject(PropMergedMenu, mergedMenu); - return mergedMenu; - } - } - /// /// Gets or sets a value indicating whether the minimize button is displayed in the caption bar of the form. /// @@ -2577,7 +2449,6 @@ protected override void SetVisibleCore(bool value) if (!value) { - InvalidateMergedMenu(); SetState(STATE_VISIBLE, false); } else @@ -3464,7 +3335,7 @@ protected override void CreateHandle() } // avoid extra SetMenu calls for perf - if (Menu != null || !TopLevel || IsMdiContainer) + if (!TopLevel || IsMdiContainer) { UpdateMenuHandles(); } @@ -3654,41 +3525,6 @@ protected override void Dispose(bool disposing) base.Dispose(disposing); ctlClient = null; - - MainMenu mainMenu = Menu; - - // We should only dispose this form's menus! - if (mainMenu != null && mainMenu.ownerForm == this) - { - mainMenu.Dispose(); - Properties.SetObject(PropMainMenu, null); - } - - if (Properties.GetObject(PropCurMenu) != null) - { - Properties.SetObject(PropCurMenu, null); - } - - MenuChanged(Windows.Forms.Menu.CHANGE_ITEMS, null); - - MainMenu dummyMenu = (MainMenu)Properties.GetObject(PropDummyMenu); - - if (dummyMenu != null) - { - dummyMenu.Dispose(); - Properties.SetObject(PropDummyMenu, null); - } - - MainMenu mergedMenu = (MainMenu)Properties.GetObject(PropMergedMenu); - - if (mergedMenu != null) - { - if (mergedMenu.ownerForm == this || mergedMenu.form == null) - { - mergedMenu.Dispose(); - } - Properties.SetObject(PropMergedMenu, null); - } } else { @@ -4145,30 +3981,6 @@ protected void CenterToScreen() Location = p; } - /// - /// Invalidates the merged menu, forcing the menu to be recreated if - /// needed again. - /// - private void InvalidateMergedMenu() - { - // here, we just set the merged menu to null (indicating that the menu structure - // needs to be rebuilt). Then, we signal the parent to updated its menus. - if (Properties.ContainsObject(PropMergedMenu)) - { - if (Properties.GetObject(PropMergedMenu) is MainMenu menu && menu.ownerForm == this) - { - menu.Dispose(); - } - Properties.SetObject(PropMergedMenu, null); - } - - Form parForm = ParentForm; - if (parForm != null) - { - parForm.MenuChanged(0, parForm.Menu); - } - } - /// /// Arranges the Multiple Document Interface /// (MDI) child forms according to value. @@ -4178,67 +3990,6 @@ public void LayoutMdi(MdiLayout value) ctlClient?.LayoutMdi(value); } - // Package scope for menu interop - internal void MenuChanged(int change, Menu menu) - { - Form parForm = ParentForm; - if (parForm != null && this == parForm.ActiveMdiChildInternal) - { - parForm.MenuChanged(change, menu); - return; - } - - switch (change) - { - case Windows.Forms.Menu.CHANGE_ITEMS: - case Windows.Forms.Menu.CHANGE_MERGE: - if (ctlClient == null || !ctlClient.IsHandleCreated) - { - if (menu == Menu && change == Windows.Forms.Menu.CHANGE_ITEMS) - { - UpdateMenuHandles(); - } - - break; - } - - // Tell the children to toss their mergedMenu. - if (IsHandleCreated) - { - UpdateMenuHandles(null, false); - } - - Control.ControlCollection children = ctlClient.Controls; - for (int i = children.Count; i-- > 0;) - { - Control ctl = children[i]; - if (ctl is Form && ctl.Properties.ContainsObject(PropMergedMenu)) - { - if (ctl.Properties.GetObject(PropMergedMenu) is MainMenu mainMenu && mainMenu.ownerForm == ctl) - { - mainMenu.Dispose(); - } - ctl.Properties.SetObject(PropMergedMenu, null); - } - } - - UpdateMenuHandles(); - break; - case Windows.Forms.Menu.CHANGE_VISIBLE: - if (menu == Menu || (ActiveMdiChildInternal != null && menu == ActiveMdiChildInternal.Menu)) - { - UpdateMenuHandles(); - } - break; - case Windows.Forms.Menu.CHANGE_MDI: - if (ctlClient != null && ctlClient.IsHandleCreated) - { - UpdateMenuHandles(); - } - break; - } - } - /// /// The activate event is fired when the form is activated. /// @@ -4871,12 +4622,6 @@ protected override bool ProcessCmdKey(ref Message msg, Keys keyData) return true; } - MainMenu curMenu = (MainMenu)Properties.GetObject(PropCurMenu); - if (curMenu != null && curMenu.ProcessCmdKey(ref msg, keyData)) - { - return true; - } - // Process MDI accelerator keys. bool retValue = false; @@ -6060,67 +5805,34 @@ private void UpdateLayered() private void UpdateMenuHandles() { - Form form; - - // Forget the current menu. - if (Properties.GetObject(PropCurMenu) != null) - { - Properties.SetObject(PropCurMenu, null); - } - if (IsHandleCreated) { if (!TopLevel) { - UpdateMenuHandles(null, true); + UpdateMenuHandles(true); } else { - form = ActiveMdiChildInternal; + Form form = ActiveMdiChildInternal; if (form != null) { - UpdateMenuHandles(form.MergedMenuPrivate, true); + UpdateMenuHandles(true); } else { - UpdateMenuHandles(Menu, true); + UpdateMenuHandles(true); } } } } - private void UpdateMenuHandles(MainMenu menu, bool forceRedraw) + private void UpdateMenuHandles(bool forceRedraw) { Debug.Assert(IsHandleCreated, "shouldn't call when handle == 0"); - int suspendCount = formStateEx[FormStateExUpdateMenuHandlesSuspendCount]; - if (suspendCount > 0 && menu != null) - { - formStateEx[FormStateExUpdateMenuHandlesDeferred] = 1; - return; - } - - MainMenu curMenu = menu; - if (curMenu != null) - { - curMenu.form = this; - } - - if (curMenu != null || Properties.ContainsObject(PropCurMenu)) - { - Properties.SetObject(PropCurMenu, curMenu); - } - if (ctlClient == null || !ctlClient.IsHandleCreated) { - if (menu != null) - { - UnsafeNativeMethods.SetMenu(new HandleRef(this, Handle), new HandleRef(menu, menu.Handle)); - } - else - { - UnsafeNativeMethods.SetMenu(new HandleRef(this, Handle), NativeMethods.NullHandleRef); - } + UnsafeNativeMethods.SetMenu(new HandleRef(this, Handle), NativeMethods.NullHandleRef); } else { @@ -6129,43 +5841,13 @@ private void UpdateMenuHandles(MainMenu menu, bool forceRedraw) // the MainMenuStrip as the place to store the system menu controls for the maximized MDI child. MenuStrip mainMenuStrip = MainMenuStrip; - if (mainMenuStrip == null || menu != null) - { // We are dealing with a Win32 Menu; MenuStrip doesn't have control buttons. - - // We have a MainMenu and we're going to use it - - // We need to set the "dummy" menu even when a menu is being removed - // (set to null) so that duplicate control buttons are not placed on the menu bar when - // an ole menu is being removed. - // Make MDI forget the mdi item position. - MainMenu dummyMenu = (MainMenu)Properties.GetObject(PropDummyMenu); - - if (dummyMenu == null) - { - dummyMenu = new MainMenu - { - ownerForm = this - }; - Properties.SetObject(PropDummyMenu, dummyMenu); - } - UnsafeNativeMethods.SendMessage(new HandleRef(ctlClient, ctlClient.Handle), WindowMessages.WM_MDISETMENU, dummyMenu.Handle, IntPtr.Zero); - - if (menu != null) - { - - // Microsoft, 5/2/1998 - don't use Win32 native Mdi lists... - // - UnsafeNativeMethods.SendMessage(new HandleRef(ctlClient, ctlClient.Handle), WindowMessages.WM_MDISETMENU, menu.Handle, IntPtr.Zero); - } - } - // (New fix: Only destroy Win32 Menu if using a MenuStrip) - if (menu == null && mainMenuStrip != null) - { // If MainMenuStrip, we need to remove any Win32 Menu to make room for it. + if (mainMenuStrip != null) + { + // If MainMenuStrip, we need to remove any Win32 Menu to make room for it. IntPtr hMenu = UnsafeNativeMethods.GetMenu(new HandleRef(this, Handle)); if (hMenu != IntPtr.Zero) { - // We had a MainMenu and now we're switching over to MainMenuStrip // Remove the current menu. @@ -6186,6 +5868,7 @@ private void UpdateMenuHandles(MainMenu menu, bool forceRedraw) } } } + if (forceRedraw) { SafeNativeMethods.DrawMenuBar(new HandleRef(this, Handle)); @@ -6319,25 +6002,21 @@ private void UpdateMdiControlStrip(bool maximized) if (ActiveMdiChildInternal.ControlBox) { Debug.WriteLineIf(ToolStrip.MDIMergeDebug.TraceVerbose, "UpdateMdiControlStrip: Detected ControlBox on ActiveMDI child, adding in MDIControlStrip."); - Debug.WriteLineIf(ToolStrip.MDIMergeDebug.TraceVerbose && Menu != null, "UpdateMdiControlStrip: Bailing as we detect there's already an HMenu to do this for us."); // determine if we need to add control gadgets into the MenuStrip - if (Menu == null) + // double check GetMenu incase someone is using interop + IntPtr hMenu = UnsafeNativeMethods.GetMenu(new HandleRef(this, Handle)); + if (hMenu == IntPtr.Zero) { - // double check GetMenu incase someone is using interop - IntPtr hMenu = UnsafeNativeMethods.GetMenu(new HandleRef(this, Handle)); - if (hMenu == IntPtr.Zero) + MenuStrip sourceMenuStrip = ToolStripManager.GetMainMenuStrip(this); + if (sourceMenuStrip != null) { - MenuStrip sourceMenuStrip = ToolStripManager.GetMainMenuStrip(this); - if (sourceMenuStrip != null) - { - MdiControlStrip = new MdiControlStrip(ActiveMdiChildInternal); - Debug.WriteLineIf(ToolStrip.MDIMergeDebug.TraceVerbose, "UpdateMdiControlStrip: built up an MDI control strip for " + ActiveMdiChildInternal.Text + " with " + MdiControlStrip.Items.Count.ToString(CultureInfo.InvariantCulture) + " items."); - Debug.WriteLineIf(ToolStrip.MDIMergeDebug.TraceVerbose, "UpdateMdiControlStrip: merging MDI control strip into source menustrip - items before: " + sourceMenuStrip.Items.Count.ToString(CultureInfo.InvariantCulture)); - ToolStripManager.Merge(MdiControlStrip, sourceMenuStrip); - Debug.WriteLineIf(ToolStrip.MDIMergeDebug.TraceVerbose, "UpdateMdiControlStrip: merging MDI control strip into source menustrip - items after: " + sourceMenuStrip.Items.Count.ToString(CultureInfo.InvariantCulture)); - MdiControlStrip.MergedMenu = sourceMenuStrip; - } + MdiControlStrip = new MdiControlStrip(ActiveMdiChildInternal); + Debug.WriteLineIf(ToolStrip.MDIMergeDebug.TraceVerbose, "UpdateMdiControlStrip: built up an MDI control strip for " + ActiveMdiChildInternal.Text + " with " + MdiControlStrip.Items.Count.ToString(CultureInfo.InvariantCulture) + " items."); + Debug.WriteLineIf(ToolStrip.MDIMergeDebug.TraceVerbose, "UpdateMdiControlStrip: merging MDI control strip into source menustrip - items before: " + sourceMenuStrip.Items.Count.ToString(CultureInfo.InvariantCulture)); + ToolStripManager.Merge(MdiControlStrip, sourceMenuStrip); + Debug.WriteLineIf(ToolStrip.MDIMergeDebug.TraceVerbose, "UpdateMdiControlStrip: merging MDI control strip into source menustrip - items after: " + sourceMenuStrip.Items.Count.ToString(CultureInfo.InvariantCulture)); + MdiControlStrip.MergedMenu = sourceMenuStrip; } } } @@ -6894,55 +6573,6 @@ private void WmGetMinMaxInfoHelper(ref Message m, Size minTrack, Size maxTrack, m.Result = IntPtr.Zero; } - /// - /// WM_INITMENUPOPUP handler - /// - private void WmInitMenuPopup(ref Message m) - { - MainMenu curMenu = (MainMenu)Properties.GetObject(PropCurMenu); - if (curMenu != null) - { - - //curMenu.UpdateRtl((RightToLeft == RightToLeft.Yes)); - - if (curMenu.ProcessInitMenuPopup(m.WParam)) - { - return; - } - } - base.WndProc(ref m); - } - - /// - /// Handles the WM_MENUCHAR message - /// - private void WmMenuChar(ref Message m) - { - MainMenu curMenu = (MainMenu)Properties.GetObject(PropCurMenu); - if (curMenu == null) - { - - Form formMdiParent = (Form)Properties.GetObject(PropFormMdiParent); - if (formMdiParent != null && formMdiParent.Menu != null) - { - UnsafeNativeMethods.PostMessage(new HandleRef(formMdiParent, formMdiParent.Handle), WindowMessages.WM_SYSCOMMAND, new IntPtr(NativeMethods.SC_KEYMENU), m.WParam); - m.Result = (IntPtr)NativeMethods.Util.MAKELONG(0, 1); - return; - } - } - if (curMenu != null) - { - curMenu.WmMenuChar(ref m); - if (m.Result != IntPtr.Zero) - { - // This char is a mnemonic on our menu. - return; - } - } - - base.WndProc(ref m); - } - /// /// WM_MDIACTIVATE handler /// @@ -6990,28 +6620,6 @@ private void WmNcButtonDown(ref Message m) /// private void WmNCDestroy(ref Message m) { - MainMenu mainMenu = Menu; - MainMenu dummyMenu = (MainMenu)Properties.GetObject(PropDummyMenu); - MainMenu curMenu = (MainMenu)Properties.GetObject(PropCurMenu); - MainMenu mergedMenu = (MainMenu)Properties.GetObject(PropMergedMenu); - - if (mainMenu != null) - { - mainMenu.ClearHandles(); - } - if (curMenu != null) - { - curMenu.ClearHandles(); - } - if (mergedMenu != null) - { - mergedMenu.ClearHandles(); - } - if (dummyMenu != null) - { - dummyMenu.ClearHandles(); - } - base.WndProc(ref m); // Destroy the owner window, if we created one. We @@ -7156,18 +6764,6 @@ private void WmSize(ref Message m) } } - /// - /// WM_UNINITMENUPOPUP handler - /// - private void WmUnInitMenuPopup(ref Message m) - { - if (Menu != null) - { - //Whidbey addition - also raise the MainMenu.Collapse event for the current menu - Menu.OnCollapse(EventArgs.Empty); - } - } - /// /// WM_WINDOWPOSCHANGED handler /// @@ -7232,15 +6828,6 @@ protected override void WndProc(ref Message m) WmEraseBkgnd(ref m); break; - case WindowMessages.WM_INITMENUPOPUP: - WmInitMenuPopup(ref m); - break; - case WindowMessages.WM_UNINITMENUPOPUP: - WmUnInitMenuPopup(ref m); - break; - case WindowMessages.WM_MENUCHAR: - WmMenuChar(ref m); - break; case WindowMessages.WM_NCDESTROY: WmNCDestroy(ref m); break; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/GridTablesFactory.cs b/src/System.Windows.Forms/src/System/Windows/Forms/GridTablesFactory.cs deleted file mode 100644 index ebc0b939a0d..00000000000 --- a/src/System.Windows.Forms/src/System/Windows/Forms/GridTablesFactory.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System.Windows.Forms -{ - public static class GridTablesFactory - { - /// - /// Takes a DataView and creates an intelligent mapping of DataView storage - /// types into available DataColumn types. - /// - public static DataGridTableStyle[] CreateGridTables(DataGridTableStyle gridTable, object dataSource, string dataMember, BindingContext bindingManager) - { - return new DataGridTableStyle[] { gridTable }; - } - } -} diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/IDataGridEditingService.cs b/src/System.Windows.Forms/src/System/Windows/Forms/IDataGridEditingService.cs deleted file mode 100644 index 911af12452a..00000000000 --- a/src/System.Windows.Forms/src/System/Windows/Forms/IDataGridEditingService.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System.Windows.Forms -{ - /// - /// The DataGrid exposes hooks to request editing commands via this interface. - /// - public interface IDataGridEditingService - { - bool BeginEdit(DataGridColumnStyle gridColumn, int rowNumber); - bool EndEdit(DataGridColumnStyle gridColumn, int rowNumber, bool shouldAbort); - } -} diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/MainMenu.cs b/src/System.Windows.Forms/src/System/Windows/Forms/MainMenu.cs deleted file mode 100644 index 4ab2c41d9ef..00000000000 --- a/src/System.Windows.Forms/src/System/Windows/Forms/MainMenu.cs +++ /dev/null @@ -1,204 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.ComponentModel; - -namespace System.Windows.Forms -{ - /// - /// Represents a menu structure for a form. - /// - [ToolboxItemFilter("System.Windows.Forms.MainMenu")] - public class MainMenu : Menu - { - internal Form form; - internal Form ownerForm; // this is the form that created this menu, and is the only form allowed to dispose it. - private RightToLeft rightToLeft = System.Windows.Forms.RightToLeft.Inherit; - private EventHandler onCollapse; - - /// - /// Creates a new MainMenu control. - /// - public MainMenu() - : base(null) - { - } - - /// - /// Initializes a new instance of the class with the specified container. - /// - public MainMenu(IContainer container) : this() - { - if (container == null) - { - throw new ArgumentNullException(nameof(container)); - } - - container.Add(this); - } - - /// - /// Creates a new MainMenu control with the given items to start - /// with. - /// - public MainMenu(MenuItem[] items) - : base(items) - { - } - - [SRDescription(nameof(SR.MainMenuCollapseDescr))] - public event EventHandler Collapse - { - add => onCollapse += value; - remove => onCollapse -= value; - } - - /// - /// This is used for international applications where the language - /// is written from RightToLeft. When this property is true, - /// text alignment and reading order will be from right to left. - /// - // Add an AmbientValue attribute so that the Reset context menu becomes available in the Property Grid. - [ - Localizable(true), - AmbientValue(RightToLeft.Inherit), - SRDescription(nameof(SR.MenuRightToLeftDescr)) - ] - public virtual RightToLeft RightToLeft - { - get - { - if (System.Windows.Forms.RightToLeft.Inherit == rightToLeft) - { - if (form != null) - { - return form.RightToLeft; - } - else - { - return RightToLeft.Inherit; - } - } - else - { - return rightToLeft; - } - } - set - { - - //valid values are 0x0 to 0x2 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)RightToLeft.No, (int)RightToLeft.Inherit)) - { - throw new InvalidEnumArgumentException(nameof(RightToLeft), (int)value, typeof(RightToLeft)); - } - if (rightToLeft != value) - { - rightToLeft = value; - UpdateRtl((value == System.Windows.Forms.RightToLeft.Yes)); - } - - } - } - - internal override bool RenderIsRightToLeft - { - get - { - return (RightToLeft == System.Windows.Forms.RightToLeft.Yes && (form == null || !form.IsMirrored)); - } - } - - /// - /// Creates a new MainMenu object which is a dupliate of this one. - /// - public virtual MainMenu CloneMenu() - { - MainMenu newMenu = new MainMenu(); - newMenu.CloneMenu(this); - return newMenu; - } - - protected override IntPtr CreateMenuHandle() - { - return UnsafeNativeMethods.CreateMenu(); - } - - /// - /// Clears out this MainMenu object and discards all of it's resources. - /// If the menu is parented in a form, it is disconnected from that as - /// well. - /// - protected override void Dispose(bool disposing) - { - if (disposing) - { - if (form != null && (ownerForm == null || form == ownerForm)) - { - form.Menu = null; - } - } - base.Dispose(disposing); - } - - /// - /// Indicates which form in which we are currently residing [if any] - /// - public Form GetForm() - { - return form; - } - - internal Form GetFormUnsafe() - { - return form; - } - - internal override void ItemsChanged(int change) - { - base.ItemsChanged(change); - if (form != null) - { - form.MenuChanged(change, this); - } - } - - internal virtual void ItemsChanged(int change, Menu menu) - { - if (form != null) - { - form.MenuChanged(change, menu); - } - } - - /// - /// Fires the collapse event - /// - protected internal virtual void OnCollapse(EventArgs e) - { - onCollapse?.Invoke(this, e); - } - - /// - /// Returns true if the RightToLeft should be persisted in code gen. - /// - internal virtual bool ShouldSerializeRightToLeft() - { - if (System.Windows.Forms.RightToLeft.Inherit == RightToLeft) - { - return false; - } - return true; - } - - /// - /// Returns a string representation for this control. - /// - public override string ToString() - { - // Removing GetForm information - return base.ToString(); - } - } -} diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Menu.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Menu.cs deleted file mode 100644 index 89b6c8356de..00000000000 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Menu.cs +++ /dev/null @@ -1,1235 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Collections; -using System.ComponentModel; -using System.Diagnostics; -using System.Globalization; -using System.Runtime.InteropServices; - -namespace System.Windows.Forms -{ - /// - /// This is the base class for all menu components (MainMenu, MenuItem, and ContextMenu). - /// - [ToolboxItemFilter("System.Windows.Forms")] - [ListBindable(false)] - public abstract class Menu : Component - { - internal const int CHANGE_ITEMS = 0; // item(s) added or removed - internal const int CHANGE_VISIBLE = 1; // item(s) hidden or shown - internal const int CHANGE_MDI = 2; // mdi item changed - internal const int CHANGE_MERGE = 3; // mergeType or mergeOrder changed - internal const int CHANGE_ITEMADDED = 4; // mergeType or mergeOrder changed - - /// - /// Used by findMenuItem - /// - public const int FindHandle = 0; - /// - /// Used by findMenuItem - /// - public const int FindShortcut = 1; - - private MenuItemCollection itemsCollection; - internal MenuItem[] items; - private int _itemCount; - internal IntPtr handle; - internal bool created; - private object userData; - private string name; - - /// - /// This is an abstract class. Instances cannot be created, so the constructor - /// is only called from derived classes. - /// - protected Menu(MenuItem[] items) - { - if (items != null) - { - MenuItems.AddRange(items); - } - } - - /// - /// The HMENU handle corresponding to this menu. - /// - [ - Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced), - DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), - SRDescription(nameof(SR.ControlHandleDescr)) - ] - public IntPtr Handle - { - get - { - if (handle == IntPtr.Zero) - { - handle = CreateMenuHandle(); - } - - CreateMenuItems(); - return handle; - } - } - - /// - /// Specifies whether this menu contains any items. - /// - [ - Browsable(false), - DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), - SRDescription(nameof(SR.MenuIsParentDescr)) - ] - public virtual bool IsParent - { - get - { - return null != items && ItemCount > 0; - } - } - - internal int ItemCount - { - get - { - return _itemCount; - } - } - - /// - /// The MenuItem that contains the list of MDI child windows. - /// - [ - Browsable(false), - DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), - SRDescription(nameof(SR.MenuMDIListItemDescr)) - ] - public MenuItem MdiListItem - { - get - { - for (int i = 0; i < ItemCount; i++) - { - MenuItem item = items[i]; - if (item.MdiList) - { - return item; - } - - if (item.IsParent) - { - item = item.MdiListItem; - if (item != null) - { - return item; - } - } - } - return null; - } - } - - /// - /// Name of this control. The designer will set this to the same - /// as the programatic Id "(name)" of the control - however this - /// property has no bearing on the runtime aspects of this control. - /// - [ - DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), - Browsable(false) - ] - public string Name - { - get - { - return WindowsFormsUtils.GetComponentName(this, name); - } - set - { - if (value == null || value.Length == 0) - { - name = null; - } - else - { - name = value; - } - if (Site != null) - { - Site.Name = name; - } - } - } - - [ - Browsable(false), - DesignerSerializationVisibility(DesignerSerializationVisibility.Content), - SRDescription(nameof(SR.MenuMenuItemsDescr)), - MergableProperty(false) - ] - public MenuItemCollection MenuItems - { - get - { - if (itemsCollection == null) - { - itemsCollection = new MenuItemCollection(this); - } - return itemsCollection; - } - } - - internal virtual bool RenderIsRightToLeft - { - get - { - Debug.Assert(true, "Should never get called"); - return false; - - } - } - - [ - SRCategory(nameof(SR.CatData)), - Localizable(false), - Bindable(true), - SRDescription(nameof(SR.ControlTagDescr)), - DefaultValue(null), - TypeConverter(typeof(StringConverter)), - ] - public object Tag - { - get - { - return userData; - } - set - { - userData = value; - } - } - - /// - /// Notifies Menu that someone called Windows.DeleteMenu on its handle. - /// - internal void ClearHandles() - { - if (handle != IntPtr.Zero) - { - UnsafeNativeMethods.DestroyMenu(new HandleRef(this, handle)); - } - handle = IntPtr.Zero; - if (created) - { - for (int i = 0; i < ItemCount; i++) - { - items[i].ClearHandles(); - } - created = false; - } - } - - /// - /// Sets this menu to be an identical copy of another menu. - /// - protected internal void CloneMenu(Menu menuSrc) - { - if (menuSrc == null) - { - throw new ArgumentNullException(nameof(menuSrc)); - } - - MenuItem[] newItems = null; - if (menuSrc.items != null) - { - int count = menuSrc.MenuItems.Count; - newItems = new MenuItem[count]; - for (int i = 0; i < count; i++) - { - newItems[i] = menuSrc.MenuItems[i].CloneMenu(); - } - } - MenuItems.Clear(); - if (newItems != null) - { - MenuItems.AddRange(newItems); - } - } - - protected virtual IntPtr CreateMenuHandle() - { - return UnsafeNativeMethods.CreatePopupMenu(); - } - - internal void CreateMenuItems() - { - if (!created) - { - for (int i = 0; i < ItemCount; i++) - { - items[i].CreateMenuItem(); - } - created = true; - } - } - - internal void DestroyMenuItems() - { - if (created) - { - for (int i = 0; i < ItemCount; i++) - { - items[i].ClearHandles(); - } - while (UnsafeNativeMethods.GetMenuItemCount(new HandleRef(this, handle)) > 0) - { - UnsafeNativeMethods.RemoveMenu(new HandleRef(this, handle), 0, NativeMethods.MF_BYPOSITION); - } - created = false; - } - } - - /// - /// Disposes of the component. Call dispose when the component is no longer needed. - /// This method removes the component from its container (if the component has a site) - /// and triggers the dispose event. - /// - protected override void Dispose(bool disposing) - { - if (disposing) - { - while (ItemCount > 0) - { - MenuItem item = items[--_itemCount]; - - // remove the item before we dispose it so it still has valid state - // for undo/redo - // - if (item.Site != null && item.Site.Container != null) - { - item.Site.Container.Remove(item); - } - - item.Parent = null; - item.Dispose(); - } - items = null; - } - if (handle != IntPtr.Zero) - { - UnsafeNativeMethods.DestroyMenu(new HandleRef(this, handle)); - handle = IntPtr.Zero; - if (disposing) - { - ClearHandles(); - } - } - base.Dispose(disposing); - } - - public MenuItem FindMenuItem(int type, IntPtr value) - { - for (int i = 0; i < ItemCount; i++) - { - MenuItem item = items[i]; - switch (type) - { - case FindHandle: - if (item.handle == value) - { - return item; - } - - break; - case FindShortcut: - if (item.Shortcut == (Shortcut)(int)value) - { - return item; - } - - break; - } - item = item.FindMenuItem(type, value); - if (item != null) - { - return item; - } - } - return null; - } - - protected int FindMergePosition(int mergeOrder) - { - int iMin, iLim, iT; - - for (iMin = 0, iLim = ItemCount; iMin < iLim;) - { - iT = (iMin + iLim) / 2; - if (items[iT].MergeOrder <= mergeOrder) - { - iMin = iT + 1; - } - else - { - iLim = iT; - } - } - return iMin; - } - - // A new method for finding the approximate merge position. The original - // method assumed (incorrectly) that the MergeOrder of the target menu would be sequential - // as it's guaranteed to be in the MDI imlementation of merging container and child - // menus. However, user code can call MergeMenu independently on a source and target - // menu whose MergeOrder values are not necessarily pre-sorted. - internal int xFindMergePosition(int mergeOrder) - { - int nPosition = 0; - - // Iterate from beginning to end since we can't assume any sequential ordering to MergeOrder - for (int nLoop = 0; nLoop < ItemCount; nLoop++) - { - - if (items[nLoop].MergeOrder > mergeOrder) - { - // We didn't find what we're looking for, but we've found a stopping point. - break; - } - else if (items[nLoop].MergeOrder < mergeOrder) - { - // We might have found what we're looking for, but we'll have to come around again - // to know. - nPosition = nLoop + 1; - } - else if (mergeOrder == items[nLoop].MergeOrder) - { - // We've found what we're looking for, so use this value for the merge order - nPosition = nLoop; - break; - } - } - - return nPosition; - } - - //There's a win32 problem that doesn't allow menus to cascade right to left - //unless we explicitely set the bit on the menu the first time it pops up - internal void UpdateRtl(bool setRightToLeftBit) - { - foreach (MenuItem item in MenuItems) - { - item.UpdateItemRtl(setRightToLeftBit); - item.UpdateRtl(setRightToLeftBit); - } - } - - /// - /// Returns the ContextMenu that contains this menu. The ContextMenu - /// is at the top of this menu's parent chain. - /// Returns null if this menu is not contained in a ContextMenu. - /// This can occur if it's contained in a MainMenu or if it isn't - /// currently contained in any menu at all. - /// - public ContextMenu GetContextMenu() - { - Menu menuT; - for (menuT = this; !(menuT is ContextMenu);) - { - if (!(menuT is MenuItem)) - { - return null; - } - - menuT = ((MenuItem)menuT).Parent; - } - return (ContextMenu)menuT; - - } - - /// - /// Returns the MainMenu item that contains this menu. The MainMenu - /// is at the top of this menu's parent chain. - /// Returns null if this menu is not contained in a MainMenu. - /// This can occur if it's contained in a ContextMenu or if it isn't - /// currently contained in any menu at all. - /// - public MainMenu GetMainMenu() - { - Menu menuT; - for (menuT = this; !(menuT is MainMenu);) - { - if (!(menuT is MenuItem)) - { - return null; - } - - menuT = ((MenuItem)menuT).Parent; - } - return (MainMenu)menuT; - } - - internal virtual void ItemsChanged(int change) - { - switch (change) - { - case CHANGE_ITEMS: - case CHANGE_VISIBLE: - DestroyMenuItems(); - break; - } - } - - /// - /// Walks the menu item collection, using a caller-supplied delegate to find one - /// with a matching access key. Walk starts at specified item index and performs one - /// full pass of the entire collection, looping back to the top if necessary. - /// - /// Return value is intended for return from WM_MENUCHAR message. It includes both - /// index of matching item, and action for OS to take (execute or select). Zero is - /// used to indicate that no match was found (OS should ignore key and beep). - /// - private IntPtr MatchKeyToMenuItem(int startItem, char key, MenuItemKeyComparer comparer) - { - int firstMatch = -1; - bool multipleMatches = false; - - for (int i = 0; i < items.Length && !multipleMatches; ++i) - { - int itemIndex = (startItem + i) % items.Length; - MenuItem mi = items[itemIndex]; - if (mi != null && comparer(mi, key)) - { - if (firstMatch < 0) - { - // Using Index doesnt respect hidden items. - firstMatch = mi.MenuIndex; - } - else - { - multipleMatches = true; - } - } - } - - if (firstMatch < 0) - { - return IntPtr.Zero; - } - - int action = multipleMatches ? NativeMethods.MNC_SELECT : NativeMethods.MNC_EXECUTE; - return (IntPtr)NativeMethods.Util.MAKELONG(firstMatch, action); - } - - /// Delegate type used by MatchKeyToMenuItem - private delegate bool MenuItemKeyComparer(MenuItem mi, char key); - - /// - /// Merges another menu's items with this one's. Menu items are merged according to their - /// mergeType and mergeOrder properties. This function is typically used to - /// merge an MDI container's menu with that of its active MDI child. - /// - public virtual void MergeMenu(Menu menuSrc) - { - if (menuSrc == null) - { - throw new ArgumentNullException(nameof(menuSrc)); - } - if (menuSrc == this) - { - throw new ArgumentException(SR.MenuMergeWithSelf, nameof(menuSrc)); - } - - int i, j; - MenuItem item; - MenuItem itemDst; - - if (menuSrc.items != null && items == null) - { - MenuItems.Clear(); - } - - for (i = 0; i < menuSrc.ItemCount; i++) - { - item = menuSrc.items[i]; - - switch (item.MergeType) - { - default: - continue; - case MenuMerge.Add: - MenuItems.Add(FindMergePosition(item.MergeOrder), item.MergeMenu()); - continue; - case MenuMerge.Replace: - case MenuMerge.MergeItems: - break; - } - - int mergeOrder = item.MergeOrder; - // Can we find a menu item with a matching merge order? - // Use new method to find the approximate merge position. The original - // method assumed (incorrectly) that the MergeOrder of the target menu would be sequential - // as it's guaranteed to be in the MDI imlementation of merging container and child - // menus. However, user code can call MergeMenu independently on a source and target - // menu whose MergeOrder values are not necessarily pre-sorted. - for (j = xFindMergePosition(mergeOrder); ; j++) - { - - if (j >= ItemCount) - { - // A matching merge position could not be found, - // so simply append this menu item to the end. - MenuItems.Add(j, item.MergeMenu()); - break; - } - itemDst = items[j]; - if (itemDst.MergeOrder != mergeOrder) - { - MenuItems.Add(j, item.MergeMenu()); - break; - } - if (itemDst.MergeType != MenuMerge.Add) - { - if (item.MergeType != MenuMerge.MergeItems - || itemDst.MergeType != MenuMerge.MergeItems) - { - itemDst.Dispose(); - MenuItems.Add(j, item.MergeMenu()); - } - else - { - itemDst.MergeMenu(item); - } - break; - } - } - } - } - - internal virtual bool ProcessInitMenuPopup(IntPtr handle) - { - MenuItem item = FindMenuItem(FindHandle, handle); - if (item != null) - { - item.OnInitMenuPopup(EventArgs.Empty); - item.CreateMenuItems(); - return true; - } - return false; - } - - protected internal virtual bool ProcessCmdKey(ref Message msg, Keys keyData) - { - MenuItem item = FindMenuItem(FindShortcut, (IntPtr)(int)keyData); - return item != null ? item.ShortcutClick() : false; - } - - /// - /// Returns index of currently selected menu item in - /// this menu, or -1 if no item is currently selected. - /// - internal int SelectedMenuItemIndex - { - get - { - for (int i = 0; i < items.Length; ++i) - { - MenuItem mi = items[i]; - if (mi != null && mi.Selected) - { - return i; - } - } - return -1; - } - } - - /// - /// Returns a string representation for this control. - /// - public override string ToString() - { - string s = base.ToString(); - return s + ", Items.Count: " + ItemCount.ToString(CultureInfo.CurrentCulture); - } - - /// - /// Handles the WM_MENUCHAR message, forwarding it to the intended Menu - /// object. All the real work is done inside WmMenuCharInternal(). - /// - internal void WmMenuChar(ref Message m) - { - Menu menu = (m.LParam == handle) ? this : FindMenuItem(FindHandle, m.LParam); - - if (menu == null) - { - return; - } - - char menuKey = char.ToUpper((char)NativeMethods.Util.LOWORD(m.WParam), CultureInfo.CurrentCulture); - - m.Result = menu.WmMenuCharInternal(menuKey); - } - - /// - /// Handles WM_MENUCHAR to provide access key support for owner-draw menu items (which - /// means *all* menu items on a menu when IsImageMarginPresent == true). Attempts to - /// simulate the exact behavior that the OS provides for non owner-draw menu items. - /// - internal IntPtr WmMenuCharInternal(char key) - { - // Start looking just beyond the current selected item (otherwise just start at the top) - int startItem = (SelectedMenuItemIndex + 1) % items.Length; - - // First, search for match among owner-draw items with explicitly defined access keys (eg. "S&ave") - IntPtr result = MatchKeyToMenuItem(startItem, key, new MenuItemKeyComparer(CheckOwnerDrawItemWithMnemonic)); - - // Next, search for match among owner-draw items with no access keys (looking at first char of item text) - if (result == IntPtr.Zero) - { - result = MatchKeyToMenuItem(startItem, key, new MenuItemKeyComparer(CheckOwnerDrawItemNoMnemonic)); - } - - return result; - } - - /// MenuItemKeyComparer delegate used by WmMenuCharInternal - private bool CheckOwnerDrawItemWithMnemonic(MenuItem mi, char key) - { - return mi.OwnerDraw && - mi.Mnemonic == key; - } - - /// MenuItemKeyComparer delegate used by WmMenuCharInternal - private bool CheckOwnerDrawItemNoMnemonic(MenuItem mi, char key) - { - return mi.OwnerDraw && - mi.Mnemonic == 0 && - mi.Text.Length > 0 && - char.ToUpper(mi.Text[0], CultureInfo.CurrentCulture) == key; - } - - [ListBindable(false)] - public class MenuItemCollection : IList - { - private readonly Menu owner; - - /// A caching mechanism for key accessor - /// We use an index here rather than control so that we don't have lifetime - /// issues by holding on to extra references. - private int lastAccessedIndex = -1; - - public MenuItemCollection(Menu owner) - { - this.owner = owner; - } - - public virtual MenuItem this[int index] - { - get - { - if (index < 0 || index >= owner.ItemCount) - { - throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); - } - - return owner.items[index]; - } - // set not supported - } - - object IList.this[int index] - { - get - { - return this[index]; - } - set - { - throw new NotSupportedException(); - } - } - - /// - /// Retrieves the child control with the specified key. - /// - public virtual MenuItem this[string key] - { - get - { - // We do not support null and empty string as valid keys. - if (string.IsNullOrEmpty(key)) - { - return null; - } - - // Search for the key in our collection - int index = IndexOfKey(key); - if (IsValidIndex(index)) - { - return this[index]; - } - else - { - return null; - } - - } - } - - public int Count - { - get - { - return owner.ItemCount; - } - } - - object ICollection.SyncRoot - { - get - { - return this; - } - } - - bool ICollection.IsSynchronized - { - get - { - return false; - } - } - - bool IList.IsFixedSize - { - get - { - return false; - } - } - - public bool IsReadOnly - { - get - { - return false; - } - } - - /// - /// Adds a new MenuItem to the end of this menu with the specified caption. - /// - public virtual MenuItem Add(string caption) - { - MenuItem item = new MenuItem(caption); - Add(item); - return item; - } - - /// - /// Adds a new MenuItem to the end of this menu with the specified caption, - /// and click handler. - /// - public virtual MenuItem Add(string caption, EventHandler onClick) - { - MenuItem item = new MenuItem(caption, onClick); - Add(item); - return item; - } - - /// - /// Adds a new MenuItem to the end of this menu with the specified caption, - /// click handler, and items. - /// - public virtual MenuItem Add(string caption, MenuItem[] items) - { - MenuItem item = new MenuItem(caption, items); - Add(item); - return item; - } - - /// - /// Adds a MenuItem to the end of this menu - /// MenuItems can only be contained in one menu at a time, and may not be added - /// more than once to the same menu. - /// - public virtual int Add(MenuItem item) - { - return Add(owner.ItemCount, item); - } - - /// - /// Adds a MenuItem to this menu at the specified index. The item currently at - /// that index, and all items after it, will be moved up one slot. - /// MenuItems can only be contained in one menu at a time, and may not be added - /// more than once to the same menu. - /// - public virtual int Add(int index, MenuItem item) - { - if (item == null) - { - throw new ArgumentNullException(nameof(item)); - } - - // MenuItems can only belong to one menu at a time - if (item.Parent != null) - { - - // First check that we're not adding ourself, i.e. walk - // the parent chain for equality - if (owner is MenuItem parent) - { - while (parent != null) - { - if (parent.Equals(item)) - { - throw new ArgumentException(string.Format(SR.MenuItemAlreadyExists, item.Text), "item"); - } - if (parent.Parent is MenuItem) - { - parent = (MenuItem)parent.Parent; - } - else - { - break; - } - } - } - - //if we're re-adding an item back to the same collection - //the target index needs to be decremented since we're - //removing an item from the collection - if (item.Parent.Equals(owner) && index > 0) - { - index--; - } - - item.Parent.MenuItems.Remove(item); - } - - // Validate our index - if (index < 0 || index > owner.ItemCount) - { - throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); - } - - if (owner.items == null || owner.items.Length == owner.ItemCount) - { - MenuItem[] newItems = new MenuItem[owner.ItemCount < 2 ? 4 : owner.ItemCount * 2]; - if (owner.ItemCount > 0) - { - System.Array.Copy(owner.items, 0, newItems, 0, owner.ItemCount); - } - - owner.items = newItems; - } - System.Array.Copy(owner.items, index, owner.items, index + 1, owner.ItemCount - index); - owner.items[index] = item; - owner._itemCount++; - item.Parent = owner; - owner.ItemsChanged(CHANGE_ITEMS); - if (owner is MenuItem) - { - ((MenuItem)owner).ItemsChanged(CHANGE_ITEMADDED, item); - } - - return index; - } - - public virtual void AddRange(MenuItem[] items) - { - if (items == null) - { - throw new ArgumentNullException(nameof(items)); - } - foreach (MenuItem item in items) - { - Add(item); - } - } - - int IList.Add(object value) - { - if (value is MenuItem) - { - return Add((MenuItem)value); - } - else - { - throw new ArgumentException(SR.MenuBadMenuItem, "value"); - } - } - - public bool Contains(MenuItem value) - { - return IndexOf(value) != -1; - } - - bool IList.Contains(object value) - { - if (value is MenuItem) - { - return Contains((MenuItem)value); - } - else - { - return false; - } - } - - /// - /// Returns true if the collection contains an item with the specified key, false otherwise. - /// - public virtual bool ContainsKey(string key) - { - return IsValidIndex(IndexOfKey(key)); - } - - /// - /// Searches for Controls by their Name property, builds up an array - /// of all the controls that match. - /// - public MenuItem[] Find(string key, bool searchAllChildren) - { - - if ((key == null) || (key.Length == 0)) - { - throw new ArgumentNullException(nameof(key), SR.FindKeyMayNotBeEmptyOrNull); - } - - ArrayList foundMenuItems = FindInternal(key, searchAllChildren, this, new ArrayList()); - - // Make this a stongly typed collection. - MenuItem[] stronglyTypedfoundMenuItems = new MenuItem[foundMenuItems.Count]; - foundMenuItems.CopyTo(stronglyTypedfoundMenuItems, 0); - - return stronglyTypedfoundMenuItems; - } - - /// - /// Searches for Controls by their Name property, builds up an array list - /// of all the controls that match. - /// - private ArrayList FindInternal(string key, bool searchAllChildren, MenuItemCollection menuItemsToLookIn, ArrayList foundMenuItems) - { - if ((menuItemsToLookIn == null) || (foundMenuItems == null)) - { - return null; // - } - - // Perform breadth first search - as it's likely people will want controls belonging - // to the same parent close to each other. - - for (int i = 0; i < menuItemsToLookIn.Count; i++) - { - if (menuItemsToLookIn[i] == null) - { - continue; - } - - if (WindowsFormsUtils.SafeCompareStrings(menuItemsToLookIn[i].Name, key, /* ignoreCase = */ true)) - { - foundMenuItems.Add(menuItemsToLookIn[i]); - } - } - - // Optional recurive search for controls in child collections. - - if (searchAllChildren) - { - for (int i = 0; i < menuItemsToLookIn.Count; i++) - { - if (menuItemsToLookIn[i] == null) - { - continue; - } - if ((menuItemsToLookIn[i].MenuItems != null) && menuItemsToLookIn[i].MenuItems.Count > 0) - { - // if it has a valid child collecion, append those results to our collection - foundMenuItems = FindInternal(key, searchAllChildren, menuItemsToLookIn[i].MenuItems, foundMenuItems); - } - } - } - return foundMenuItems; - } - - public int IndexOf(MenuItem value) - { - for (int index = 0; index < Count; ++index) - { - if (this[index] == value) - { - return index; - } - } - return -1; - } - - int IList.IndexOf(object value) - { - if (value is MenuItem) - { - return IndexOf((MenuItem)value); - } - else - { - return -1; - } - } - - /// - /// The zero-based index of the first occurrence of value within the entire CollectionBase, if found; otherwise, -1. - /// - public virtual int IndexOfKey(string key) - { - // Step 0 - Arg validation - if (string.IsNullOrEmpty(key)) - { - return -1; // we dont support empty or null keys. - } - - // step 1 - check the last cached item - if (IsValidIndex(lastAccessedIndex)) - { - if (WindowsFormsUtils.SafeCompareStrings(this[lastAccessedIndex].Name, key, /* ignoreCase = */ true)) - { - return lastAccessedIndex; - } - } - - // step 2 - search for the item - for (int i = 0; i < Count; i++) - { - if (WindowsFormsUtils.SafeCompareStrings(this[i].Name, key, /* ignoreCase = */ true)) - { - lastAccessedIndex = i; - return i; - } - } - - // step 3 - we didn't find it. Invalidate the last accessed index and return -1. - lastAccessedIndex = -1; - return -1; - } - - void IList.Insert(int index, object value) - { - if (value is MenuItem) - { - Add(index, (MenuItem)value); - } - else - { - throw new ArgumentException(SR.MenuBadMenuItem, "value"); - } - } - - /// - /// Determines if the index is valid for the collection. - /// - private bool IsValidIndex(int index) - { - return ((index >= 0) && (index < Count)); - } - - /// - /// Removes all existing MenuItems from this menu - /// - public virtual void Clear() - { - if (owner.ItemCount > 0) - { - - for (int i = 0; i < owner.ItemCount; i++) - { - owner.items[i].Parent = null; - } - - owner._itemCount = 0; - owner.items = null; - - owner.ItemsChanged(CHANGE_ITEMS); - - if (owner is MenuItem) - { - ((MenuItem)(owner)).UpdateMenuItem(true); - } - } - } - - public void CopyTo(Array dest, int index) - { - if (owner.ItemCount > 0) - { - System.Array.Copy(owner.items, 0, dest, index, owner.ItemCount); - } - } - - public IEnumerator GetEnumerator() - { - return new WindowsFormsUtils.ArraySubsetEnumerator(owner.items, owner.ItemCount); - } - - /// - /// Removes the item at the specified index in this menu. All subsequent - /// items are moved up one slot. - /// - public virtual void RemoveAt(int index) - { - if (index < 0 || index >= owner.ItemCount) - { - throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); - } - - MenuItem item = owner.items[index]; - item.Parent = null; - owner._itemCount--; - System.Array.Copy(owner.items, index + 1, owner.items, index, owner.ItemCount - index); - owner.items[owner.ItemCount] = null; - owner.ItemsChanged(CHANGE_ITEMS); - - //if the last item was removed, clear the collection - // - if (owner.ItemCount == 0) - { - Clear(); - } - - } - - /// - /// Removes the menu iteml with the specified key. - /// - public virtual void RemoveByKey(string key) - { - int index = IndexOfKey(key); - if (IsValidIndex(index)) - { - RemoveAt(index); - } - } - - /// - /// Removes the specified item from this menu. All subsequent - /// items are moved down one slot. - /// - public virtual void Remove(MenuItem item) - { - if (item.Parent == owner) - { - RemoveAt(item.Index); - } - } - - void IList.Remove(object value) - { - if (value is MenuItem) - { - Remove((MenuItem)value); - } - } - } - } -} diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/MenuItem.cs b/src/System.Windows.Forms/src/System/Windows/Forms/MenuItem.cs deleted file mode 100644 index 927d36f010b..00000000000 --- a/src/System.Windows.Forms/src/System/Windows/Forms/MenuItem.cs +++ /dev/null @@ -1,1801 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Collections; -using System.ComponentModel; -using System.Globalization; -using System.Diagnostics; -using System.Drawing; -using System.Runtime.InteropServices; -using System.Threading; - -namespace System.Windows.Forms -{ - /// - /// Represents an individual item that is displayed within a - /// or . - /// - [ToolboxItem(false)] - [DesignTimeVisible(false)] - [DefaultEvent(nameof(Click))] - [DefaultProperty(nameof(Text))] - public class MenuItem : Menu - { - private const int StateBarBreak = 0x00000020; - private const int StateBreak = 0x00000040; - private const int StateChecked = 0x00000008; - private const int StateDefault = 0x00001000; - private const int StateDisabled = 0x00000003; - private const int StateRadioCheck = 0x00000200; - private const int StateHidden = 0x00010000; - private const int StateMdiList = 0x00020000; - private const int StateCloneMask = 0x0003136B; - private const int StateOwnerDraw = 0x00000100; - private const int StateInMdiPopup = 0x00000200; - private const int StateHiLite = 0x00000080; - - private bool _hasHandle; - private MenuItemData _data; - private int _dataVersion; - private MenuItem _nextLinkedItem; // Next item linked to the same MenuItemData. - - // We need to store a table of all created menuitems, so that other objects - // such as ContainerControl can get a reference to a particular menuitem, - // given a unique ID. - private static readonly Hashtable s_allCreatedMenuItems = new Hashtable(); - private const uint FirstUniqueID = 0xC0000000; - private static long s_nextUniqueID = FirstUniqueID; - private uint _uniqueID = 0; - private IntPtr _msaaMenuInfoPtr = IntPtr.Zero; - private bool _menuItemIsCreated = false; - -#if DEBUG - private string _debugText; - private readonly int _creationNumber; - private static int CreateCount; -#endif - - /// - /// Initializes a with a blank caption. - /// - public MenuItem() : this(MenuMerge.Add, 0, 0, null, null, null, null, null) - { - } - - /// - /// Initializes a new instance of the class - /// with a specified caption for the menu item. - /// - public MenuItem(string text) : this(MenuMerge.Add, 0, 0, text, null, null, null, null) - { - } - - /// - /// Initializes a new instance of the class with a specified caption and event handler - /// for the menu item. - /// - public MenuItem(string text, EventHandler onClick) : this(MenuMerge.Add, 0, 0, text, onClick, null, null, null) - { - } - - /// - /// Initializes a new instance of the class with a specified caption, event handler, - /// and associated shorcut key for the menu item. - /// - public MenuItem(string text, EventHandler onClick, Shortcut shortcut) : this(MenuMerge.Add, 0, shortcut, text, onClick, null, null, null) - { - } - - /// - /// Initializes a new instance of the class with a specified caption and an array of - /// submenu items defined for the menu item. - /// - public MenuItem(string text, MenuItem[] items) : this(MenuMerge.Add, 0, 0, text, null, null, null, items) - { - } - - internal MenuItem(MenuItemData data) : base(null) - { - data.AddItem(this); - -#if DEBUG - _debugText = data._caption; -#endif - } - - /// - /// Initializes a new instance of the class with a specified caption, defined - /// event-handlers for the Click, Select and Popup events, a shortcut key, - /// a merge type, and order specified for the menu item. - /// - public MenuItem(MenuMerge mergeType, int mergeOrder, Shortcut shortcut, - string text, EventHandler onClick, EventHandler onPopup, - EventHandler onSelect, MenuItem[] items) : base(items) - { - new MenuItemData(this, mergeType, mergeOrder, shortcut, true, - text, onClick, onPopup, onSelect, null, null); - -#if DEBUG - _debugText = text; - _creationNumber = CreateCount++; -#endif - } - - /// - /// Gets or sets a value indicating whether the item is placed on a new line (for a - /// menu item added to a object) or in a - /// new column (for a submenu or menu displayed in a ). - /// - [Browsable(false)] - [DefaultValue(false)] - public bool BarBreak - { - get - { - CheckIfDisposed(); - return (_data.State & StateBarBreak) != 0; - } - set - { - CheckIfDisposed(); - _data.SetState(StateBarBreak, value); - } - } - - /// - /// Gets or sets a value indicating whether the item is placed on a new line (for a - /// menu item added to a object) or in a - /// new column (for a submenu or menu displayed in a ). - /// - [Browsable(false)] - [DefaultValue(false)] - public bool Break - { - get - { - CheckIfDisposed(); - return (_data.State & StateBreak) != 0; - } - set - { - CheckIfDisposed(); - _data.SetState(StateBreak, value); - } - } - - /// - /// Gets or sets a value indicating whether a checkmark appears beside the text of - /// the menu item. - /// - [DefaultValue(false)] - [SRDescription(nameof(SR.MenuItemCheckedDescr))] - public bool Checked - { - get - { - CheckIfDisposed(); - return (_data.State & StateChecked) != 0; - } - set - { - CheckIfDisposed(); - - if (value && (ItemCount != 0 || Parent is MainMenu)) - { - throw new ArgumentException(SR.MenuItemInvalidCheckProperty, nameof(value)); - } - - _data.SetState(StateChecked, value); - } - } - - /// - /// Gets or sets a value indicating whether the menu item is the default. - /// - [DefaultValue(false)] - [SRDescription(nameof(SR.MenuItemDefaultDescr))] - public bool DefaultItem - { - get - { - CheckIfDisposed(); - return (_data.State & StateDefault) != 0; - } - set - { - CheckIfDisposed(); - if (Parent != null) - { - if (value) - { - UnsafeNativeMethods.SetMenuDefaultItem(new HandleRef(Parent, Parent.handle), MenuID, false); - } - else if (DefaultItem) - { - UnsafeNativeMethods.SetMenuDefaultItem(new HandleRef(Parent, Parent.handle), -1, false); - } - } - - _data.SetState(StateDefault, value); - } - } - - /// - /// Gets or sets a value indicating whether code that you provide draws the menu - /// item or Windows draws the menu item. - /// - [SRCategory(nameof(SR.CatBehavior))] - [DefaultValue(false)] - [SRDescription(nameof(SR.MenuItemOwnerDrawDescr))] - public bool OwnerDraw - { - get - { - CheckIfDisposed(); - return ((_data.State & StateOwnerDraw) != 0); - } - set - { - CheckIfDisposed(); - _data.SetState(StateOwnerDraw, value); - } - } - - /// - /// Gets or sets a value indicating whether the menu item is enabled. - /// - [Localizable(true)] - [DefaultValue(true)] - [SRDescription(nameof(SR.MenuItemEnabledDescr))] - public bool Enabled - { - get - { - CheckIfDisposed(); - return (_data.State & StateDisabled) == 0; - } - set - { - CheckIfDisposed(); - _data.SetState(StateDisabled, !value); - } - } - - /// - /// Gets or sets the menu item's position in its parent menu. - /// - [Browsable(false)] - public int Index - { - get - { - if (Parent != null) - { - for (int i = 0; i < Parent.ItemCount; i++) - { - if (Parent.items[i] == this) - { - return i; - } - } - } - - return -1; - } - set - { - int oldIndex = Index; - if (oldIndex >= 0) - { - if (value < 0 || value >= Parent.ItemCount) - { - throw new ArgumentOutOfRangeException(nameof(value), string.Format(SR.InvalidArgument, nameof(Index), value)); - } - - if (value != oldIndex) - { - // The menu reverts to null when we're removed, so hold onto it in a - // local variable - Menu parent = Parent; - parent.MenuItems.RemoveAt(oldIndex); - parent.MenuItems.Add(value, this); - } - } - } - } - - /// - /// Gets a value indicating whether the menu item contains child menu items. - /// - [Browsable(false)] - public override bool IsParent - { - get - { - if (_data != null && MdiList) - { - for (int i = 0; i < ItemCount; i++) - { - if (!(items[i]._data.UserData is MdiListUserData)) - { - return true; - } - } - - if (FindMdiForms().Length > 0) - { - return true; - } - - if (Parent != null && !(Parent is MenuItem)) - { - return true; - } - - return false; - } - - return base.IsParent; - } - } - - /// - /// Gets or sets a value indicating whether the menu item will be populated with a - /// list of the MDI child windows that are displayed within the associated form. - /// - [DefaultValue(false)] - [SRDescription(nameof(SR.MenuItemMDIListDescr))] - public bool MdiList - { - get - { - CheckIfDisposed(); - return (_data.State & StateMdiList) != 0; - } - set - { - CheckIfDisposed(); - _data.MdiList = value; - CleanListItems(this); - } - } - - /// - /// Gets the Windows identifier for this menu item. - /// - protected int MenuID - { - get - { - CheckIfDisposed(); - return _data.GetMenuID(); - } - } - - /// - /// Is this menu item currently selected (highlighted) by the user? - /// - internal bool Selected - { - get - { - if (Parent == null) - { - return false; - } - - var info = new NativeMethods.MENUITEMINFO_T - { - cbSize = Marshal.SizeOf(), - fMask = NativeMethods.MIIM_STATE - }; - UnsafeNativeMethods.GetMenuItemInfo(new HandleRef(Parent, Parent.handle), MenuID, false, info); - - return (info.fState & StateHiLite) != 0; - } - } - - /// - /// Gets the zero-based index of this menu item in the parent menu, or -1 if this - /// menu item is not associated with a parent menu. - /// - internal int MenuIndex - { - get - { - if (Parent == null) - { - return -1; - } - - int count = UnsafeNativeMethods.GetMenuItemCount(new HandleRef(Parent, Parent.Handle)); - int id = MenuID; - NativeMethods.MENUITEMINFO_T info = new NativeMethods.MENUITEMINFO_T - { - cbSize = Marshal.SizeOf(), - fMask = NativeMethods.MIIM_ID | NativeMethods.MIIM_SUBMENU - }; - - for (int i = 0; i < count; i++) - { - UnsafeNativeMethods.GetMenuItemInfo(new HandleRef(Parent, Parent.handle), i, true, info); - - // For sub menus, the handle is always valid. - // For items, however, it is always zero. - if ((info.hSubMenu == IntPtr.Zero || info.hSubMenu == Handle) && info.wID == id) - { - return i; - } - } - - return -1; - } - } - - /// - /// Gets or sets a value that indicates the behavior of this - /// menu item when its menu is merged with another. - /// - [DefaultValue(MenuMerge.Add)] - [SRDescription(nameof(SR.MenuItemMergeTypeDescr))] - public MenuMerge MergeType - { - get - { - CheckIfDisposed(); - return _data._mergeType; - } - set - { - CheckIfDisposed(); - if (!ClientUtils.IsEnumValid(value, (int)value, (int)MenuMerge.Add, (int)MenuMerge.Remove)) - { - throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(MenuMerge)); - } - - _data.MergeType = value; - } - } - - /// - /// Gets or sets the relative position the menu item when its - /// menu is merged with another. - /// - [DefaultValue(0)] - [SRDescription(nameof(SR.MenuItemMergeOrderDescr))] - public int MergeOrder - { - get - { - CheckIfDisposed(); - return _data._mergeOrder; - } - set - { - CheckIfDisposed(); - _data.MergeOrder = value; - } - } - - /// - /// Retrieves the hotkey mnemonic that is associated with this menu item. - /// The mnemonic is the first character after an ampersand symbol in the menu's text - /// that is not itself an ampersand symbol. If no such mnemonic is defined this - /// will return zero. - /// - [Browsable(false)] - public char Mnemonic - { - get - { - CheckIfDisposed(); - return _data.Mnemonic; - } - } - - /// - /// Gets the menu in which this menu item appears. - /// - [Browsable(false)] - public Menu Parent { get; internal set; } - - /// - /// Gets or sets a value that indicates whether the menu item, if checked, - /// displays a radio-button mark instead of a check mark. - /// - [DefaultValue(false)] - [SRDescription(nameof(SR.MenuItemRadioCheckDescr))] - public bool RadioCheck - { - get - { - CheckIfDisposed(); - return (_data.State & StateRadioCheck) != 0; - } - set - { - CheckIfDisposed(); - _data.SetState(StateRadioCheck, value); - } - } - - internal override bool RenderIsRightToLeft => Parent != null && Parent.RenderIsRightToLeft; - - /// - /// Gets or sets the text of the menu item. - /// - [Localizable(true)] - [SRDescription(nameof(SR.MenuItemTextDescr))] - public string Text - { - get - { - CheckIfDisposed(); - return _data._caption; - } - set - { - CheckIfDisposed(); - _data.SetCaption(value); - } - } - - /// - /// Gets or sets the shortcut key associated with the menu item. - /// - [Localizable(true)] - [DefaultValue(Shortcut.None)] - [SRDescription(nameof(SR.MenuItemShortCutDescr))] - public Shortcut Shortcut - { - get - { - CheckIfDisposed(); - return _data._shortcut; - } - set - { - CheckIfDisposed(); - if (!Enum.IsDefined(typeof(Shortcut), value)) - { - throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(Shortcut)); - } - - _data._shortcut = value; - UpdateMenuItem(force: true); - } - } - - /// - /// Gets or sets a value that indicates whether the shortcut key that is associated - /// with the menu item is displayed next to the menu item caption. - /// - [DefaultValue(true), - Localizable(true)] - [SRDescription(nameof(SR.MenuItemShowShortCutDescr))] - public bool ShowShortcut - { - get - { - CheckIfDisposed(); - return _data._showShortcut; - } - set - { - CheckIfDisposed(); - if (value != _data._showShortcut) - { - _data._showShortcut = value; - UpdateMenuItem(force: true); - } - } - } - - /// - /// Gets or sets a value that indicates whether the menu item is visible on its - /// parent menu. - /// - [Localizable(true)] - [DefaultValue(true)] - [SRDescription(nameof(SR.MenuItemVisibleDescr))] - public bool Visible - { - get - { - CheckIfDisposed(); - return (_data.State & StateHidden) == 0; - } - set - { - CheckIfDisposed(); - _data.Visible = value; - } - } - - /// - /// Occurs when the menu item is clicked or selected using a shortcut key defined - /// for the menu item. - /// - [SRDescription(nameof(SR.MenuItemOnClickDescr))] - public event EventHandler Click - { - add - { - CheckIfDisposed(); - _data._onClick += value; - } - remove - { - CheckIfDisposed(); - _data._onClick -= value; - } - } - - /// - /// Occurs when when the property of a menu item is set to and - /// a request is made to draw the menu item. - /// - [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.drawItemEventDescr))] - public event DrawItemEventHandler DrawItem - { - add - { - CheckIfDisposed(); - _data._onDrawItem += value; - } - remove - { - CheckIfDisposed(); - _data._onDrawItem -= value; - } - } - - /// - /// Occurs when when the menu needs to know the size of a menu item before drawing it. - /// - [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.measureItemEventDescr))] - public event MeasureItemEventHandler MeasureItem - { - add - { - CheckIfDisposed(); - _data._onMeasureItem += value; - } - remove - { - CheckIfDisposed(); - _data._onMeasureItem -= value; - } - } - - /// - /// Occurs before a menu item's list of menu items is displayed. - /// - [SRDescription(nameof(SR.MenuItemOnInitDescr))] - public event EventHandler Popup - { - add - { - CheckIfDisposed(); - _data._onPopup += value; - } - remove - { - CheckIfDisposed(); - _data._onPopup -= value; - } - } - - /// - /// Occurs when the user hovers their mouse over a menu item or selects it with the - /// keyboard but has not activated it. - /// - [SRDescription(nameof(SR.MenuItemOnSelectDescr))] - public event EventHandler Select - { - add - { - CheckIfDisposed(); - _data._onSelect += value; - } - remove - { - CheckIfDisposed(); - _data._onSelect -= value; - } - } - - private static void CleanListItems(MenuItem senderMenu) - { - // Remove dynamic items. - for (int i = senderMenu.MenuItems.Count - 1; i >= 0; i--) - { - MenuItem item = senderMenu.MenuItems[i]; - if (item._data.UserData is MdiListUserData) - { - item.Dispose(); - continue; - } - } - } - - /// - /// Creates and returns an identical copy of this menu item. - /// - public virtual MenuItem CloneMenu() - { - var newItem = new MenuItem(); - newItem.CloneMenu(this); - return newItem; - } - - /// - /// Creates a copy of the specified menu item. - /// - protected void CloneMenu(MenuItem itemSrc) - { - base.CloneMenu(itemSrc); - int state = itemSrc._data.State; - new MenuItemData(this, - itemSrc.MergeType, itemSrc.MergeOrder, itemSrc.Shortcut, itemSrc.ShowShortcut, - itemSrc.Text, itemSrc._data._onClick, itemSrc._data._onPopup, itemSrc._data._onSelect, - itemSrc._data._onDrawItem, itemSrc._data._onMeasureItem); - _data.SetState(state & StateCloneMask, true); - } - - internal virtual void CreateMenuItem() - { - if ((_data.State & StateHidden) == 0) - { - NativeMethods.MENUITEMINFO_T info = CreateMenuItemInfo(); - UnsafeNativeMethods.InsertMenuItem(new HandleRef(Parent, Parent.handle), -1, true, info); - - _hasHandle = info.hSubMenu != IntPtr.Zero; - _dataVersion = _data._version; - - _menuItemIsCreated = true; - if (RenderIsRightToLeft) - { - Parent.UpdateRtl(true); - } - -#if DEBUG - NativeMethods.MENUITEMINFO_T infoVerify = new NativeMethods.MENUITEMINFO_T - { - cbSize = Marshal.SizeOf(), - fMask = NativeMethods.MIIM_ID | NativeMethods.MIIM_STATE | - NativeMethods.MIIM_SUBMENU | NativeMethods.MIIM_TYPE - }; - UnsafeNativeMethods.GetMenuItemInfo(new HandleRef(Parent, Parent.handle), MenuID, false, infoVerify); -#endif - } - } - - private NativeMethods.MENUITEMINFO_T CreateMenuItemInfo() - { - var info = new NativeMethods.MENUITEMINFO_T - { - fMask = NativeMethods.MIIM_ID | NativeMethods.MIIM_STATE | - NativeMethods.MIIM_SUBMENU | NativeMethods.MIIM_TYPE | NativeMethods.MIIM_DATA, - fType = _data.State & (StateBarBreak | StateBreak | StateRadioCheck | StateOwnerDraw) - }; - - // Top level menu items shouldn't have barbreak or break bits set on them. - bool isTopLevel = Parent == GetMainMenu(); - - if (_data._caption.Equals("-")) - { - if (isTopLevel) - { - _data._caption = " "; - info.fType |= NativeMethods.MFT_MENUBREAK; - } - else - { - info.fType |= NativeMethods.MFT_SEPARATOR; - } - } - - info.fState = _data.State & (StateChecked | StateDefault | StateDisabled); - - info.wID = MenuID; - if (IsParent) - { - info.hSubMenu = Handle; - } - - info.hbmpChecked = IntPtr.Zero; - info.hbmpUnchecked = IntPtr.Zero; - - // Assign a unique ID to this menu item object. - // The ID is stored in the dwItemData of the corresponding Win32 menu item, so - // that when we get Win32 messages about the item later, we can delegate to the - // original object menu item object. A static hash table is used to map IDs to - // menu item objects. - if (_uniqueID == 0) - { - lock (s_allCreatedMenuItems) - { - _uniqueID = (uint)Interlocked.Increment(ref s_nextUniqueID); - Debug.Assert(_uniqueID >= FirstUniqueID); // ...check for ID range exhaustion (unlikely!) - // We add a weak ref wrapping a MenuItem to the static hash table, as - // supposed to adding the item ref itself, to allow the item to be finalized - // in case it is not disposed and no longer referenced anywhere else, hence - // preventing leaks. - s_allCreatedMenuItems.Add(_uniqueID, new WeakReference(this)); - } - } - - if (IntPtr.Size == 4) - { - // Store the unique ID in the dwItemData.. - // For simple menu items, we can just put the unique ID in the dwItemData. - // But for owner-draw items, we need to point the dwItemData at an MSAAMENUINFO - // structure so that MSAA can get the item text. - // To allow us to reliably distinguish between IDs and structure pointers later - // on, we keep IDs in the 0xC0000000-0xFFFFFFFF range. This is the top 1Gb of - // unmananged process memory, where an app's heap allocations should never come - // from. So that we can still get the ID from the dwItemData for an owner-draw - // item later on, a copy of the ID is tacked onto the end of the MSAAMENUINFO - // structure. - if (_data.OwnerDraw) - { - info.dwItemData = AllocMsaaMenuInfo(); - } - else - { - info.dwItemData = (IntPtr)unchecked((int)_uniqueID); - } - } - else - { - // On Win64, there are no reserved address ranges we can use for menu item IDs. So instead we will - // have to allocate an MSAMENUINFO heap structure for all menu items, not just owner-drawn ones. - info.dwItemData = AllocMsaaMenuInfo(); - } - - // We won't render the shortcut if: 1) it's not set, 2) we're a parent, 3) we're toplevel - if (_data._showShortcut && _data._shortcut != 0 && !IsParent && !isTopLevel) - { - info.dwTypeData = _data._caption + "\t" + TypeDescriptor.GetConverter(typeof(Keys)).ConvertToString((Keys)(int)_data._shortcut); - } - else - { - // Windows issue: Items with empty captions sometimes block keyboard - // access to other items in same menu. - info.dwTypeData = (_data._caption.Length == 0 ? " " : _data._caption); - } - info.cch = 0; - - return info; - } - - /// - /// Disposes the . - /// - protected override void Dispose(bool disposing) - { - if (disposing) - { - Parent?.MenuItems.Remove(this); - _data?.RemoveItem(this); - lock (s_allCreatedMenuItems) - { - s_allCreatedMenuItems.Remove(_uniqueID); - } - - _uniqueID = 0; - - } - - FreeMsaaMenuInfo(); - base.Dispose(disposing); - } - - /// - /// Given a unique menu item ID, find the corresponding MenuItem - /// object, using the master lookup table of all created MenuItems. - /// - internal static MenuItem GetMenuItemFromUniqueID(uint uniqueID) - { - WeakReference weakRef = (WeakReference)s_allCreatedMenuItems[uniqueID]; - if (weakRef != null && weakRef.IsAlive) - { - return (MenuItem)weakRef.Target; - } - Debug.Fail("Weakref for menu item has expired or has been removed! Who is trying to access this ID?"); - return null; - } - - /// - /// Given the "item data" value of a Win32 menu item, find the corresponding MenuItem object (using - /// the master lookup table of all created MenuItems). The item data may be either the unique menu - /// item ID, or a pointer to an MSAAMENUINFO structure with a copy of the unique ID tacked to the end. - /// To reliably tell IDs and structure addresses apart, IDs live in the 0xC0000000-0xFFFFFFFF range. - /// This is the top 1Gb of unmananged process memory, where an app's heap allocations should never be. - /// - internal static MenuItem GetMenuItemFromItemData(IntPtr itemData) - { - uint uniqueID = (uint)(ulong)itemData; - if (uniqueID == 0) - { - return null; - } - - if (IntPtr.Size == 4) - { - if (uniqueID < FirstUniqueID) - { - MsaaMenuInfoWithId msaaMenuInfo = Marshal.PtrToStructure(itemData); - uniqueID = msaaMenuInfo._uniqueID; - } - } - else - { - // Its always a pointer on Win64 (see CreateMenuItemInfo) - MsaaMenuInfoWithId msaaMenuInfo = Marshal.PtrToStructure(itemData); - uniqueID = msaaMenuInfo._uniqueID; - } - - return GetMenuItemFromUniqueID(uniqueID); - } - - /// - /// MsaaMenuInfoWithId is an MSAAMENUINFO structure with a menu item ID field tacked onto the - /// end. This allows us to pass the data we need to Win32 / MSAA, and still be able to get the ID - /// out again later on, so we can delegate Win32 menu messages back to the correct MenuItem object. - /// - [StructLayout(LayoutKind.Sequential)] - private struct MsaaMenuInfoWithId - { - public readonly NativeMethods.MSAAMENUINFO _msaaMenuInfo; - public readonly uint _uniqueID; - - public MsaaMenuInfoWithId(string text, uint uniqueID) - { - _msaaMenuInfo = new NativeMethods.MSAAMENUINFO(text); - _uniqueID = uniqueID; - } - } - - /// - /// Creates an MSAAMENUINFO structure (in the unmanaged heap) based on the current state - /// of this MenuItem object. Address of this structure is cached in the object so we can - /// free it later on using FreeMsaaMenuInfo(). If structure has already been allocated, - /// it is destroyed and a new one created. - /// - private IntPtr AllocMsaaMenuInfo() - { - FreeMsaaMenuInfo(); - _msaaMenuInfoPtr = Marshal.AllocHGlobal(Marshal.SizeOf()); - - if (IntPtr.Size == 4) - { - // We only check this on Win32, irrelevant on Win64 (see CreateMenuItemInfo) - // Check for incursion into menu item ID range (unlikely!) - Debug.Assert(((uint)(ulong)_msaaMenuInfoPtr) < FirstUniqueID); - } - - MsaaMenuInfoWithId msaaMenuInfoStruct = new MsaaMenuInfoWithId(_data._caption, _uniqueID); - Marshal.StructureToPtr(msaaMenuInfoStruct, _msaaMenuInfoPtr, false); - Debug.Assert(_msaaMenuInfoPtr != IntPtr.Zero); - return _msaaMenuInfoPtr; - } - - /// - /// Frees the MSAAMENUINFO structure (in the unmanaged heap) for the current MenuObject - /// object, if one has previously been allocated. Takes care to free sub-structures too, - /// to avoid leaks! - /// - private void FreeMsaaMenuInfo() - { - if (_msaaMenuInfoPtr != IntPtr.Zero) - { - Marshal.DestroyStructure(_msaaMenuInfoPtr, typeof(MsaaMenuInfoWithId)); - Marshal.FreeHGlobal(_msaaMenuInfoPtr); - _msaaMenuInfoPtr = IntPtr.Zero; - } - } - - internal override void ItemsChanged(int change) - { - base.ItemsChanged(change); - - if (change == CHANGE_ITEMS) - { - // when the menu collection changes deal with it locally - Debug.Assert(!created, "base.ItemsChanged should have wiped out our handles"); - if (Parent != null && Parent.created) - { - UpdateMenuItem(force: true); - CreateMenuItems(); - } - } - else - { - if (!_hasHandle && IsParent) - { - UpdateMenuItem(force: true); - } - - MainMenu main = GetMainMenu(); - if (main != null && ((_data.State & StateInMdiPopup) == 0)) - { - main.ItemsChanged(change, this); - } - } - } - - internal void ItemsChanged(int change, MenuItem item) - { - if (change == CHANGE_ITEMADDED && - _data != null && - _data.baseItem != null && - _data.baseItem.MenuItems.Contains(item)) - { - if (Parent != null && Parent.created) - { - UpdateMenuItem(force: true); - CreateMenuItems(); - } - else if (_data != null) - { - MenuItem currentMenuItem = _data.firstItem; - while (currentMenuItem != null) - { - if (currentMenuItem.created) - { - MenuItem newItem = item.CloneMenu(); - item._data.AddItem(newItem); - currentMenuItem.MenuItems.Add(newItem); - break; - } - currentMenuItem = currentMenuItem._nextLinkedItem; - } - } - } - } - - internal Form[] FindMdiForms() - { - Form[] forms = null; - MainMenu main = GetMainMenu(); - Form menuForm = null; - if (main != null) - { - menuForm = main.GetFormUnsafe(); - } - if (menuForm != null) - { - forms = menuForm.MdiChildren; - } - if (forms == null) - { - forms = Array.Empty
(); - } - - return forms; - } - - /// - /// See the similar code in MdiWindowListStrip.PopulateItems, which is - /// unfortunately just different enough in its working environment that we - /// can't readily combine the two. But if you're fixing something here, chances - /// are that the same issue will need scrutiny over there. - /// -// "-" is OK - private void PopulateMdiList() - { - MenuItem senderMenu = this; - _data.SetState(StateInMdiPopup, true); - try - { - CleanListItems(this); - - // Add new items - Form[] forms = FindMdiForms(); - if (forms != null && forms.Length > 0) - { - - Form activeMdiChild = GetMainMenu().GetFormUnsafe().ActiveMdiChild; - - if (senderMenu.MenuItems.Count > 0) - { - MenuItem sep = (MenuItem)Activator.CreateInstance(GetType()); - sep._data.UserData = new MdiListUserData(); - sep.Text = "-"; - senderMenu.MenuItems.Add(sep); - } - - // Build a list of child windows to be displayed in - // the MDIList menu item... - // Show the first maxMenuForms visible elements of forms[] as Window menu items, except: - // Always show the active form, even if it's not in the first maxMenuForms visible elements of forms[]. - // If the active form isn't in the first maxMenuForms forms, then show the first maxMenuForms-1 elements - // in forms[], and make the active form the last one on the menu. - // Don't count nonvisible forms against the limit on Window menu items. - - const int MaxMenuForms = 9; // Max number of Window menu items for forms - int visibleChildren = 0; // the number of visible child forms (so we know to show More Windows...) - int accel = 1; // prefix the form name with this digit, underlined, as an accelerator - int formsAddedToMenu = 0; - bool activeFormAdded = false; - for (int i = 0; i < forms.Length; i++) - { - if (forms[i].Visible) - { - visibleChildren++; - if ((activeFormAdded && (formsAddedToMenu < MaxMenuForms)) || // don't exceed max - (!activeFormAdded && (formsAddedToMenu < (MaxMenuForms - 1)) || // save room for active if it's not in yet - (forms[i].Equals(activeMdiChild)))) - { - // there's always room for activeMdiChild - MenuItem windowItem = (MenuItem)Activator.CreateInstance(GetType()); - windowItem._data.UserData = new MdiListFormData(this, i); - - if (forms[i].Equals(activeMdiChild)) - { - windowItem.Checked = true; - activeFormAdded = true; - } - - windowItem.Text = string.Format(CultureInfo.CurrentUICulture, "&{0} {1}", accel, forms[i].Text); - accel++; - formsAddedToMenu++; - senderMenu.MenuItems.Add(windowItem); - } - } - } - - // Display the More Windows menu option when there are more than 9 MDI - // Child menu items to be displayed. This is necessary because we're managing our own - // MDI lists, rather than letting Windows do this for us. - if (visibleChildren > MaxMenuForms) - { - MenuItem moreWindows = (MenuItem)Activator.CreateInstance(GetType()); - moreWindows._data.UserData = new MdiListMoreWindowsData(this); - moreWindows.Text = SR.MDIMenuMoreWindows; - senderMenu.MenuItems.Add(moreWindows); - } - } - } - finally - { - _data.SetState(StateInMdiPopup, false); - } - } - - /// - /// Merges this menu item with another menu item and returns the resulting merged - /// . - /// - public virtual MenuItem MergeMenu() - { - CheckIfDisposed(); - - MenuItem newItem = (MenuItem)Activator.CreateInstance(GetType()); - _data.AddItem(newItem); - newItem.MergeMenu(this); - return newItem; - } - - /// - /// Merges another menu item with this menu item. - /// - public void MergeMenu(MenuItem itemSrc) - { - base.MergeMenu(itemSrc); - itemSrc._data.AddItem(this); - } - - /// - /// Raises the event. - /// - protected virtual void OnClick(EventArgs e) - { - CheckIfDisposed(); - - if (_data.UserData is MdiListUserData) - { - ((MdiListUserData)_data.UserData).OnClick(e); - } - else if (_data.baseItem != this) - { - _data.baseItem.OnClick(e); - } - else - { - _data._onClick?.Invoke(this, e); - } - } - - /// - /// Raises the event. - /// - protected virtual void OnDrawItem(DrawItemEventArgs e) - { - CheckIfDisposed(); - - if (_data.baseItem != this) - { - _data.baseItem.OnDrawItem(e); - } - else - { - _data._onDrawItem?.Invoke(this, e); - } - } - - /// - /// Raises the event. - /// - protected virtual void OnMeasureItem(MeasureItemEventArgs e) - { - CheckIfDisposed(); - - if (_data.baseItem != this) - { - _data.baseItem.OnMeasureItem(e); - } - else - { - _data._onMeasureItem?.Invoke(this, e); - } - } - - /// - /// Raises the event. - /// - protected virtual void OnPopup(EventArgs e) - { - CheckIfDisposed(); - - bool recreate = false; - for (int i = 0; i < ItemCount; i++) - { - if (items[i].MdiList) - { - recreate = true; - items[i].UpdateMenuItem(force: true); - } - } - if (recreate || (_hasHandle && !IsParent)) - { - UpdateMenuItem(force: true); - } - - if (_data.baseItem != this) - { - _data.baseItem.OnPopup(e); - } - else - { - _data._onPopup?.Invoke(this, e); - } - - // Update any subitem states that got changed in the event - for (int i = 0; i < ItemCount; i++) - { - MenuItem item = items[i]; - if (item._dataVersion != item._data._version) - { - item.UpdateMenuItem(force: true); - } - } - - if (MdiList) - { - PopulateMdiList(); - } - } - - /// - /// Raises the event. - /// - protected virtual void OnSelect(EventArgs e) - { - CheckIfDisposed(); - - if (_data.baseItem != this) - { - _data.baseItem.OnSelect(e); - } - else - { - _data._onSelect?.Invoke(this, e); - } - } - - protected internal virtual void OnInitMenuPopup(EventArgs e) => OnPopup(e); - - /// - /// Generates a event for the MenuItem, - /// simulating a click by a user. - /// - public void PerformClick() => OnClick(EventArgs.Empty); - - /// - /// Raises the event for this menu item. - /// - public virtual void PerformSelect() => OnSelect(EventArgs.Empty); - - internal virtual bool ShortcutClick() - { - if (Parent is MenuItem parent) - { - if (!parent.ShortcutClick() || Parent != parent) - { - return false; - } - } - if ((_data.State & StateDisabled) != 0) - { - return false; - } - if (ItemCount > 0) - { - OnPopup(EventArgs.Empty); - } - else - { - OnClick(EventArgs.Empty); - } - - return true; - } - - public override string ToString() - { - string s = base.ToString(); - string menuItemText = _data?._caption ?? string.Empty; - ; - return s + ", Text: " + menuItemText; - } - - internal void UpdateItemRtl(bool setRightToLeftBit) - { - if (!_menuItemIsCreated) - { - return; - } - - var info = new NativeMethods.MENUITEMINFO_T - { - fMask = NativeMethods.MIIM_TYPE | NativeMethods.MIIM_STATE | NativeMethods.MIIM_SUBMENU, - dwTypeData = new string('\0', Text.Length + 2), - cbSize = Marshal.SizeOf() - }; - info.cch = info.dwTypeData.Length - 1; - UnsafeNativeMethods.GetMenuItemInfo(new HandleRef(Parent, Parent.handle), MenuID, false, info); - if (setRightToLeftBit) - { - info.fType |= NativeMethods.MFT_RIGHTJUSTIFY | NativeMethods.MFT_RIGHTORDER; - } - else - { - info.fType &= ~(NativeMethods.MFT_RIGHTJUSTIFY | NativeMethods.MFT_RIGHTORDER); - } - - UnsafeNativeMethods.SetMenuItemInfo(new HandleRef(Parent, Parent.handle), MenuID, false, info); - } - - internal void UpdateMenuItem(bool force) - { - if (Parent == null || !Parent.created) - { - return; - } - - if (force || Parent is MainMenu || Parent is ContextMenu) - { - NativeMethods.MENUITEMINFO_T info = CreateMenuItemInfo(); - UnsafeNativeMethods.SetMenuItemInfo(new HandleRef(Parent, Parent.handle), MenuID, false, info); -#if DEBUG - var infoVerify = new NativeMethods.MENUITEMINFO_T - { - cbSize = Marshal.SizeOf(), - fMask = NativeMethods.MIIM_ID | NativeMethods.MIIM_STATE | - NativeMethods.MIIM_SUBMENU | NativeMethods.MIIM_TYPE - }; - UnsafeNativeMethods.GetMenuItemInfo(new HandleRef(Parent, Parent.handle), MenuID, false, infoVerify); -#endif - - if (_hasHandle && info.hSubMenu == IntPtr.Zero) - { - ClearHandles(); - } - - _hasHandle = info.hSubMenu != IntPtr.Zero; - _dataVersion = _data._version; - if (Parent is MainMenu mainMenu) - { - Form f = mainMenu.GetFormUnsafe(); - if (f != null) - { - SafeNativeMethods.DrawMenuBar(new HandleRef(f, f.Handle)); - } - } - } - } - - internal void WmDrawItem(ref Message m) - { - // Handles the OnDrawItem message sent from ContainerControl - NativeMethods.DRAWITEMSTRUCT dis = (NativeMethods.DRAWITEMSTRUCT)m.GetLParam(typeof(NativeMethods.DRAWITEMSTRUCT)); - Debug.WriteLineIf(Control.s_paletteTracing.TraceVerbose, Handle + ": Force set palette in MenuItem drawitem"); - IntPtr oldPal = Control.SetUpPalette(dis.hDC, false /*force*/, false); - try - { - Graphics g = Graphics.FromHdcInternal(dis.hDC); - try - { - OnDrawItem(new DrawItemEventArgs(g, SystemInformation.MenuFont, Rectangle.FromLTRB(dis.rcItem.left, dis.rcItem.top, dis.rcItem.right, dis.rcItem.bottom), Index, (DrawItemState)dis.itemState)); - } - finally - { - g.Dispose(); - } - } - finally - { - if (oldPal != IntPtr.Zero) - { - SafeNativeMethods.SelectPalette(new HandleRef(null, dis.hDC), new HandleRef(null, oldPal), 0); - } - } - - m.Result = (IntPtr)1; - } - - internal void WmMeasureItem(ref Message m) - { - // Handles the OnMeasureItem message sent from ContainerControl - - // Obtain the measure item struct - NativeMethods.MEASUREITEMSTRUCT mis = (NativeMethods.MEASUREITEMSTRUCT)m.GetLParam(typeof(NativeMethods.MEASUREITEMSTRUCT)); - - // The OnMeasureItem handler now determines the height and width of the item - using ScreenDC screendc = ScreenDC.Create(); - Graphics graphics = Graphics.FromHdcInternal(screendc); - MeasureItemEventArgs mie = new MeasureItemEventArgs(graphics, Index); - using (graphics) - { - OnMeasureItem(mie); - } - - // Update the measure item struct with the new width and height - mis.itemHeight = mie.ItemHeight; - mis.itemWidth = mie.ItemWidth; - Marshal.StructureToPtr(mis, m.LParam, false); - - m.Result = (IntPtr)1; - } - - private void CheckIfDisposed() - { - if (_data == null) - { - throw new ObjectDisposedException(GetType().FullName); - } - } - - internal class MenuItemData : ICommandExecutor - { - internal MenuItem baseItem; - internal MenuItem firstItem; - - private int _state; - internal int _version; - internal MenuMerge _mergeType; - internal int _mergeOrder; - internal string _caption; - internal short _mnemonic; - internal Shortcut _shortcut; - internal bool _showShortcut; - internal EventHandler _onClick; - internal EventHandler _onPopup; - internal EventHandler _onSelect; - internal DrawItemEventHandler _onDrawItem; - internal MeasureItemEventHandler _onMeasureItem; - - private Command _cmd; - - internal MenuItemData(MenuItem baseItem, MenuMerge mergeType, int mergeOrder, Shortcut shortcut, bool showShortcut, - string caption, EventHandler onClick, EventHandler onPopup, EventHandler onSelect, - DrawItemEventHandler onDrawItem, MeasureItemEventHandler onMeasureItem) - { - AddItem(baseItem); - _mergeType = mergeType; - _mergeOrder = mergeOrder; - _shortcut = shortcut; - _showShortcut = showShortcut; - _caption = caption ?? string.Empty; - _onClick = onClick; - _onPopup = onPopup; - _onSelect = onSelect; - _onDrawItem = onDrawItem; - _onMeasureItem = onMeasureItem; - _version = 1; - _mnemonic = -1; - } - - internal bool OwnerDraw - { - get => ((State & StateOwnerDraw) != 0); - set => SetState(StateOwnerDraw, value); - } - - internal bool MdiList - { - get => ((State & StateMdiList) == StateMdiList); - set - { - if (((_state & StateMdiList) != 0) != value) - { - SetState(StateMdiList, value); - for (MenuItem item = firstItem; item != null; item = item._nextLinkedItem) - { - item.ItemsChanged(Menu.CHANGE_MDI); - } - } - } - } - - internal MenuMerge MergeType - { - get => _mergeType; - set - { - if (_mergeType != value) - { - _mergeType = value; - ItemsChanged(Menu.CHANGE_MERGE); - } - } - } - - internal int MergeOrder - { - get => _mergeOrder; - set - { - if (_mergeOrder != value) - { - _mergeOrder = value; - ItemsChanged(Menu.CHANGE_MERGE); - } - } - } - - internal char Mnemonic - { - get - { - if (_mnemonic == -1) - { - _mnemonic = (short)WindowsFormsUtils.GetMnemonic(_caption, true); - } - - return (char)_mnemonic; - } - } - - internal int State => _state; - - internal bool Visible - { - get => (_state & MenuItem.StateHidden) == 0; - set - { - if (((_state & MenuItem.StateHidden) == 0) != value) - { - _state = value ? _state & ~MenuItem.StateHidden : _state | MenuItem.StateHidden; - ItemsChanged(Menu.CHANGE_VISIBLE); - } - } - } - - internal object UserData { get; set; } - - internal void AddItem(MenuItem item) - { - if (item._data != this) - { - item._data?.RemoveItem(item); - - item._nextLinkedItem = firstItem; - firstItem = item; - if (baseItem == null) - { - baseItem = item; - } - - item._data = this; - item._dataVersion = 0; - item.UpdateMenuItem(false); - } - } - - public void Execute() - { - baseItem?.OnClick(EventArgs.Empty); - } - - internal int GetMenuID() - { - if (_cmd == null) - { - _cmd = new Command(this); - } - - return _cmd.ID; - } - - internal void ItemsChanged(int change) - { - for (MenuItem item = firstItem; item != null; item = item._nextLinkedItem) - { - item.Parent?.ItemsChanged(change); - } - } - - internal void RemoveItem(MenuItem item) - { - Debug.Assert(item._data == this, "bad item passed to MenuItemData.removeItem"); - - if (item == firstItem) - { - firstItem = item._nextLinkedItem; - } - else - { - MenuItem itemT; - for (itemT = firstItem; item != itemT._nextLinkedItem;) - { - itemT = itemT._nextLinkedItem; - } - - itemT._nextLinkedItem = item._nextLinkedItem; - } - item._nextLinkedItem = null; - item._data = null; - item._dataVersion = 0; - - if (item == baseItem) - { - baseItem = firstItem; - } - - if (firstItem == null) - { - // No longer needed. Toss all references and the Command object. - Debug.Assert(baseItem == null, "why isn't baseItem null?"); - _onClick = null; - _onPopup = null; - _onSelect = null; - _onDrawItem = null; - _onMeasureItem = null; - if (_cmd != null) - { - _cmd.Dispose(); - _cmd = null; - } - } - } - - internal void SetCaption(string value) - { - if (value == null) - { - value = string.Empty; - } - - if (!_caption.Equals(value)) - { - _caption = value; - UpdateMenuItems(); - } - -#if DEBUG - if (value.Length > 0) - { - baseItem._debugText = value; - } -#endif - } - - internal void SetState(int flag, bool value) - { - if (((_state & flag) != 0) != value) - { - _state = value ? _state | flag : _state & ~flag; - UpdateMenuItems(); - } - } - - internal void UpdateMenuItems() - { - _version++; - for (MenuItem item = firstItem; item != null; item = item._nextLinkedItem) - { - item.UpdateMenuItem(force: true); - } - } - - } - - private class MdiListUserData - { - public virtual void OnClick(EventArgs e) - { - } - } - - private class MdiListFormData : MdiListUserData - { - private readonly MenuItem _parent; - private readonly int _boundIndex; - - public MdiListFormData(MenuItem parentItem, int boundFormIndex) - { - _boundIndex = boundFormIndex; - _parent = parentItem; - } - - public override void OnClick(EventArgs e) - { - if (_boundIndex != -1) - { - Form[] forms = _parent.FindMdiForms(); - Debug.Assert(forms != null, "Didn't get a list of the MDI Forms."); - - if (forms != null && forms.Length > _boundIndex) - { - Form boundForm = forms[_boundIndex]; - boundForm.Activate(); - if (boundForm.ActiveControl != null && !boundForm.ActiveControl.Focused) - { - boundForm.ActiveControl.Focus(); - } - } - } - } - } - - private class MdiListMoreWindowsData : MdiListUserData - { - private readonly MenuItem _parent; - - public MdiListMoreWindowsData(MenuItem parent) - { - _parent = parent; - } - - public override void OnClick(EventArgs e) - { - Form[] forms = _parent.FindMdiForms(); - Debug.Assert(forms != null, "Didn't get a list of the MDI Forms."); - Form active = _parent.GetMainMenu().GetFormUnsafe().ActiveMdiChild; - Debug.Assert(active != null, "Didn't get the active MDI child"); - if (forms != null && forms.Length > 0 && active != null) - { - using (var dialog = new MdiWindowDialog()) - { - dialog.SetItems(active, forms); - DialogResult result = dialog.ShowDialog(); - if (result == DialogResult.OK) - { - dialog.ActiveChildForm.Activate(); - if (dialog.ActiveChildForm.ActiveControl != null && !dialog.ActiveChildForm.ActiveControl.Focused) - { - dialog.ActiveChildForm.ActiveControl.Focus(); - } - } - } - } - } - } - } -} - diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/NotifyIcon.cs b/src/System.Windows.Forms/src/System/Windows/Forms/NotifyIcon.cs index 54f92ca08c0..c4fe3ba3188 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/NotifyIcon.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/NotifyIcon.cs @@ -44,7 +44,6 @@ public sealed class NotifyIcon : Component private readonly int id = 0; private bool added = false; private NotifyIconNativeWindow window = null; - private ContextMenu contextMenu = null; private ContextMenuStrip contextMenuStrip = null; private ToolTipIcon balloonTipIcon; private string balloonTipText = string.Empty; @@ -193,29 +192,6 @@ public string BalloonTipTitle remove => Events.RemoveHandler(EVENT_BALLOONTIPSHOWN, value); } - /// - /// Gets or sets context menu - /// for the tray icon. - /// - [ - Browsable(false), - DefaultValue(null), - SRCategory(nameof(SR.CatBehavior)), - SRDescription(nameof(SR.NotifyIconMenuDescr)) - ] - public ContextMenu ContextMenu - { - get - { - return contextMenu; - } - - set - { - contextMenu = value; - } - } - [ DefaultValue(null), SRCategory(nameof(SR.CatBehavior)), @@ -437,7 +413,6 @@ protected override void Dispose(bool disposing) UpdateIcon(false); window.DestroyHandle(); window = null; - contextMenu = null; contextMenuStrip = null; } } @@ -647,7 +622,7 @@ public void ShowBalloonTip(int timeout, string tipTitle, string tipText, ToolTip ///
private void ShowContextMenu() { - if (contextMenu != null || contextMenuStrip != null) + if (contextMenuStrip != null) { UnsafeNativeMethods.GetCursorPos(out Point pt); @@ -656,26 +631,9 @@ private void ShowContextMenu() // forced after the call. UnsafeNativeMethods.SetForegroundWindow(new HandleRef(window, window.Handle)); - if (contextMenu != null) - { - contextMenu.OnPopup(EventArgs.Empty); - - SafeNativeMethods.TrackPopupMenuEx(new HandleRef(contextMenu, contextMenu.Handle), - NativeMethods.TPM_VERTICAL | NativeMethods.TPM_RIGHTALIGN, - pt.X, - pt.Y, - new HandleRef(window, window.Handle), - null); - - // Force task switch (see above) - UnsafeNativeMethods.PostMessage(new HandleRef(window, window.Handle), WindowMessages.WM_NULL, IntPtr.Zero, IntPtr.Zero); - } - else if (contextMenuStrip != null) - { - // this will set the context menu strip to be toplevel - // and will allow us to overlap the system tray - contextMenuStrip.ShowInTaskbar(pt.X, pt.Y); - } + // this will set the context menu strip to be toplevel + // and will allow us to overlap the system tray + contextMenuStrip.ShowInTaskbar(pt.X, pt.Y); } } @@ -818,7 +776,7 @@ private void WndProc(ref Message msg) WmMouseDown(ref msg, MouseButtons.Right, 1); break; case WindowMessages.WM_RBUTTONUP: - if (contextMenu != null || contextMenuStrip != null) + if (contextMenuStrip != null) { ShowContextMenu(); } @@ -851,91 +809,24 @@ private void WndProc(ref Message msg) window.DefWndProc(ref msg); } break; - case WindowMessages.WM_DRAWITEM: - // If the wparam is zero, then the message was sent by a menu. - // See WM_DRAWITEM in MSDN. - if (msg.WParam == IntPtr.Zero) - { - WmDrawItemMenuItem(ref msg); - } - break; - case WindowMessages.WM_MEASUREITEM: - // If the wparam is zero, then the message was sent by a menu. - if (msg.WParam == IntPtr.Zero) - { - WmMeasureMenuItem(ref msg); - } - break; - - case WindowMessages.WM_INITMENUPOPUP: - WmInitMenuPopup(ref msg); - break; case WindowMessages.WM_DESTROY: // Remove the icon from the taskbar UpdateIcon(false); break; + case WindowMessages.WM_INITMENUPOPUP: default: if (msg.Msg == WM_TASKBARCREATED) { WmTaskbarCreated(ref msg); } + window.DefWndProc(ref msg); break; } } - private void WmInitMenuPopup(ref Message m) - { - if (contextMenu != null) - { - if (contextMenu.ProcessInitMenuPopup(m.WParam)) - { - return; - } - } - - window.DefWndProc(ref m); - } - - private void WmMeasureMenuItem(ref Message m) - { - // Obtain the menu item object - NativeMethods.MEASUREITEMSTRUCT mis = (NativeMethods.MEASUREITEMSTRUCT)m.GetLParam(typeof(NativeMethods.MEASUREITEMSTRUCT)); - - Debug.Assert(m.LParam != IntPtr.Zero, "m.lparam is null"); - - // A pointer to the correct MenuItem is stored in the measure item - // information sent with the message. - // (See MenuItem.CreateMenuItemInfo) - MenuItem menuItem = MenuItem.GetMenuItemFromItemData(mis.itemData); - Debug.Assert(menuItem != null, "UniqueID is not associated with a menu item"); - - // Delegate this message to the menu item - if (menuItem != null) - { - menuItem.WmMeasureItem(ref m); - } - } - - private void WmDrawItemMenuItem(ref Message m) - { - // Obtain the menu item object - NativeMethods.DRAWITEMSTRUCT dis = (NativeMethods.DRAWITEMSTRUCT)m.GetLParam(typeof(NativeMethods.DRAWITEMSTRUCT)); - - // A pointer to the correct MenuItem is stored in the draw item - // information sent with the message. - // (See MenuItem.CreateMenuItemInfo) - MenuItem menuItem = MenuItem.GetMenuItemFromItemData(dis.itemData); - - // Delegate this message to the menu item - if (menuItem != null) - { - menuItem.WmDrawItem(ref m); - } - } - /// /// Defines a placeholder window that the NotifyIcon is attached to. /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintPreviewDialog.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintPreviewDialog.cs index 3bc0de94e8e..e7e668d5b8f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintPreviewDialog.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintPreviewDialog.cs @@ -49,7 +49,7 @@ public class PrintPreviewDialog : Form private ToolStripSeparator separatorToolStripSeparator1; private ToolStripButton closeToolStripButton; private ToolStripLabel pageToolStripLabel; - + readonly ImageList imageList; /// @@ -391,23 +391,6 @@ public override ContextMenuStrip ContextMenuStrip remove => base.MarginChanged -= value; } - /// - /// Gets or sets the - /// that is displayed in the form. - /// - [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public MainMenu Menu - { - get - { - return base.Menu; - } - set - { - base.Menu = value; - } - } - /// /// Gets the minimum size the form can be resized to. /// @@ -541,7 +524,7 @@ public override ContextMenuStrip ContextMenuStrip /// /// Gets or sets the form's window state. - /// + /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public FormWindowState WindowState { @@ -1038,29 +1021,6 @@ public override Font Font remove => base.FontChanged -= value; } - /// - /// The contextMenu associated with this control. The contextMenu - /// will be shown when the user right clicks the mouse on the control. - /// - [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override ContextMenu ContextMenu - { - get - { - return base.ContextMenu; - } - set - { - base.ContextMenu = value; - } - } - [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event EventHandler ContextMenuChanged - { - add => base.ContextMenuChanged += value; - remove => base.ContextMenuChanged -= value; - } - // DockPadding is not relevant to UpDownBase [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public DockPaddingEdges DockPadding diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/RichTextBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/RichTextBox.cs index f7dc666d642..f48352227ac 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/RichTextBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/RichTextBox.cs @@ -11,9 +11,9 @@ using System.Text; using System.Windows.Forms.Layout; using Microsoft.Win32; +using static Interop; using IComDataObject = System.Runtime.InteropServices.ComTypes.IDataObject; using Util = System.Windows.Forms.NativeMethods.Util; -using static Interop; namespace System.Windows.Forms { @@ -2602,12 +2602,6 @@ protected override void OnBackColorChanged(EventArgs e) base.OnBackColorChanged(e); } - protected override void OnContextMenuChanged(EventArgs e) - { - base.OnContextMenuChanged(e); - UpdateOleCallback(); - } - protected override void OnRightToLeftChanged(EventArgs e) { base.OnRightToLeftChanged(e); @@ -4157,51 +4151,9 @@ public HRESULT GetDragDropEffect(BOOL fDrag, int grfKeyState, ref int pdwEffect) public HRESULT GetContextMenu(short seltype, IntPtr lpoleobj, ref Richedit.CHARRANGE lpchrg, out IntPtr hmenu) { Debug.WriteLineIf(RichTextDbg.TraceVerbose, "IRichEditOleCallback::GetContextMenu"); - ContextMenu cm = owner.ContextMenu; - if (cm == null || owner.ShortcutsEnabled == false) - { - hmenu = IntPtr.Zero; - } - else - { - cm.sourceControl = owner; - cm.OnPopup(EventArgs.Empty); - // RichEd calls DestroyMenu after displaying the context menu - IntPtr handle = cm.Handle; - // if another control shares the same context menu - // then we have to mark the context menu's handles empty because - // RichTextBox will delete the menu handles once the popup menu is dismissed. - Menu menu = cm; - while (true) - { - int i = 0; - int count = menu.ItemCount; - for (; i < count; i++) - { - if (menu.items[i].handle != IntPtr.Zero) - { - menu = menu.items[i]; - break; - } - } - if (i == count) - { - menu.handle = IntPtr.Zero; - menu.created = false; - if (menu == cm) - { - break; - } - else - { - menu = ((MenuItem)menu).Parent; - } - } - } - - hmenu = handle; - } + // do nothing, we don't have ContextMenu any longer + hmenu = IntPtr.Zero; return HRESULT.S_OK; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TextBoxBase.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TextBoxBase.cs index 5769d10337c..eb5d47f93d4 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TextBoxBase.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TextBoxBase.cs @@ -2241,7 +2241,7 @@ void WmGetDlgCode(ref Message m) ///
private void WmTextBoxContextMenu(ref Message m) { - if (ContextMenu != null || ContextMenuStrip != null) + if (ContextMenuStrip != null) { int x = NativeMethods.Util.SignedLOWORD(m.LParam); int y = NativeMethods.Util.SignedHIWORD(m.LParam); @@ -2265,11 +2265,7 @@ private void WmTextBoxContextMenu(ref Message m) // VisualStudio7 # 156, only show the context menu when clicked in the client area if (ClientRectangle.Contains(client)) { - if (ContextMenu != null) - { - ContextMenu.Show(this, client); - } - else if (ContextMenuStrip != null) + if (ContextMenuStrip != null) { ContextMenuStrip.ShowInternal(this, client, keyboardActivated); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolBar.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolBar.cs deleted file mode 100644 index 8356ae0c4cf..00000000000 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolBar.cs +++ /dev/null @@ -1,2226 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Collections; -using System.ComponentModel; -using System.Drawing; -using System.Globalization; -using System.Runtime.InteropServices; -using static Interop; - -namespace System.Windows.Forms -{ - /// - /// Represents a Windows toolbar. - /// - [ - ComVisible(true), - ClassInterface(ClassInterfaceType.AutoDispatch), - DefaultEvent(nameof(ButtonClick)), - Designer("System.Windows.Forms.Design.ToolBarDesigner, " + AssemblyRef.SystemDesign), - DefaultProperty(nameof(Buttons)) - ] - public class ToolBar : Control - { - private readonly ToolBarButtonCollection buttonsCollection; - - /// - /// The size of a button in the ToolBar - /// - internal Size buttonSize = System.Drawing.Size.Empty; - - /// - /// This is used by our autoSizing support. - /// - private int requestedSize; - /// - /// This represents the width of the drop down arrow we have if the - /// DropDownArrows property is true. this value is used by the ToolBarButton - /// objects to compute their size - /// - internal const int DDARROW_WIDTH = 15; - - /// - /// Indicates what our appearance will be. This will either be normal - /// or flat. - /// - private ToolBarAppearance appearance = ToolBarAppearance.Normal; - - /// - /// Indicates whether or not we have a border - /// - private BorderStyle borderStyle = System.Windows.Forms.BorderStyle.None; - - /// - /// The array of buttons we're working with. - /// - private ToolBarButton[] buttons; - - /// - /// The number of buttons we're working with - /// - private int buttonCount = 0; - - /// - /// Indicates if text captions should go underneath images in buttons or - /// to the right of them - /// - private ToolBarTextAlign textAlign = ToolBarTextAlign.Underneath; - - /// - /// The ImageList object that contains the main images for our control. - /// - private ImageList imageList = null; - - /// - /// The maximum width of buttons currently being displayed. This is needed - /// by our autoSizing code. If this value is -1, it needs to be recomputed. - /// - private int maxWidth = -1; - private int hotItem = -1; - - // Track the current scale factor so we can scale our buttons - private float currentScaleDX = 1.0F; - private float currentScaleDY = 1.0F; - - private const int TOOLBARSTATE_wrappable = 0x00000001; - private const int TOOLBARSTATE_dropDownArrows = 0x00000002; - private const int TOOLBARSTATE_divider = 0x00000004; - private const int TOOLBARSTATE_showToolTips = 0x00000008; - private const int TOOLBARSTATE_autoSize = 0x00000010; - - // PERF: take all the bools and put them into a state variable - private Collections.Specialized.BitVector32 toolBarState; // see TOOLBARSTATE_ consts above - - // event handlers - // - private ToolBarButtonClickEventHandler onButtonClick = null; - private ToolBarButtonClickEventHandler onButtonDropDown = null; - - /// - /// Initializes a new instance of the class. - /// - public ToolBar() - : base() - { - // Set this BEFORE calling any other methods so that these defaults will be propagated - toolBarState = new Collections.Specialized.BitVector32(TOOLBARSTATE_autoSize | - TOOLBARSTATE_showToolTips | - TOOLBARSTATE_divider | - TOOLBARSTATE_dropDownArrows | - TOOLBARSTATE_wrappable); - - SetStyle(ControlStyles.UserPaint, false); - SetStyle(ControlStyles.FixedHeight, AutoSize); - SetStyle(ControlStyles.FixedWidth, false); - TabStop = false; - Dock = DockStyle.Top; - buttonsCollection = new ToolBarButtonCollection(this); - } - - /// - /// Gets or sets the appearance of the toolbar - /// control and its buttons. - /// - [ - SRCategory(nameof(SR.CatBehavior)), - DefaultValue(ToolBarAppearance.Normal), - Localizable(true), - SRDescription(nameof(SR.ToolBarAppearanceDescr)) - ] - public ToolBarAppearance Appearance - { - get - { - return appearance; - } - - set - { - //valid values are 0x0 to 0x1 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)ToolBarAppearance.Normal, (int)ToolBarAppearance.Flat)) - { - throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ToolBarAppearance)); - } - - if (value != appearance) - { - appearance = value; - RecreateHandle(); - } - } - } - - /// - /// Indicates whether the toolbar - /// adjusts its size automatically based on the size of the buttons and the - /// dock style. - /// - [ - SRCategory(nameof(SR.CatBehavior)), - DefaultValue(true), - Localizable(true), - SRDescription(nameof(SR.ToolBarAutoSizeDescr)), - Browsable(true), - EditorBrowsable(EditorBrowsableState.Always), - DesignerSerializationVisibility(DesignerSerializationVisibility.Visible) - ] - public override bool AutoSize - { - get - { - return toolBarState[TOOLBARSTATE_autoSize]; - } - - set - { - // Note that we intentionally do not call base. Toolbars size themselves by - // overriding SetBoundsCore (old RTM code). We let CommonProperties.GetAutoSize - // continue to return false to keep our LayoutEngines from messing with TextBoxes. - // This is done for backwards compatibility since the new AutoSize behavior differs. - if (AutoSize != value) - { - toolBarState[TOOLBARSTATE_autoSize] = value; - if (Dock == DockStyle.Left || Dock == DockStyle.Right) - { - SetStyle(ControlStyles.FixedWidth, AutoSize); - SetStyle(ControlStyles.FixedHeight, false); - } - else - { - SetStyle(ControlStyles.FixedHeight, AutoSize); - SetStyle(ControlStyles.FixedWidth, false); - } - AdjustSize(Dock); - OnAutoSizeChanged(EventArgs.Empty); - } - } - } - - [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.ControlOnAutoSizeChangedDescr))] - [Browsable(true), EditorBrowsable(EditorBrowsableState.Always)] - new public event EventHandler AutoSizeChanged - { - add => base.AutoSizeChanged += value; - remove => base.AutoSizeChanged -= value; - } - - [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override Color BackColor - { - get - { - return base.BackColor; - } - set - { - base.BackColor = value; - } - } - - [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler BackColorChanged - { - add => base.BackColorChanged += value; - remove => base.BackColorChanged -= value; - } - - [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override Image BackgroundImage - { - get - { - return base.BackgroundImage; - } - set - { - base.BackgroundImage = value; - } - } - - [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler BackgroundImageChanged - { - add => base.BackgroundImageChanged += value; - remove => base.BackgroundImageChanged -= value; - } - - [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override ImageLayout BackgroundImageLayout - { - get - { - return base.BackgroundImageLayout; - } - set - { - base.BackgroundImageLayout = value; - } - } - - [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler BackgroundImageLayoutChanged - { - add => base.BackgroundImageLayoutChanged += value; - remove => base.BackgroundImageLayoutChanged -= value; - } - - /// - /// Gets or sets - /// the border style of the toolbar control. - /// - [ - SRCategory(nameof(SR.CatAppearance)), - DefaultValue(BorderStyle.None), - DispId(NativeMethods.ActiveX.DISPID_BORDERSTYLE), - SRDescription(nameof(SR.ToolBarBorderStyleDescr)) - ] - public BorderStyle BorderStyle - { - get - { - return borderStyle; - } - - set - { - //valid values are 0x0 to 0x2 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)BorderStyle.None, (int)BorderStyle.Fixed3D)) - { - throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(BorderStyle)); - } - - if (borderStyle != value) - { - borderStyle = value; - - //UpdateStyles(); - RecreateHandle(); // Looks like we need to recreate the handle to avoid painting glitches - } - } - } - - /// - /// A collection of controls assigned to the - /// toolbar control. The property is read-only. - /// - [ - SRCategory(nameof(SR.CatBehavior)), - DesignerSerializationVisibility(DesignerSerializationVisibility.Content), - Localizable(true), - SRDescription(nameof(SR.ToolBarButtonsDescr)), - MergableProperty(false) - ] - public ToolBarButtonCollection Buttons - { - get - { - return buttonsCollection; - } - } - - /// - /// Gets or sets - /// the size of the buttons on the toolbar control. - /// - [ - SRCategory(nameof(SR.CatAppearance)), - RefreshProperties(RefreshProperties.All), - Localizable(true), - SRDescription(nameof(SR.ToolBarButtonSizeDescr)) - ] - public Size ButtonSize - { - get - { - if (buttonSize.IsEmpty) - { - - // Obtain the current buttonsize of the first button from the winctl control - // - if (IsHandleCreated && buttons != null && buttonCount > 0) - { - int result = unchecked((int)(long)SendMessage(NativeMethods.TB_GETBUTTONSIZE, 0, 0)); - if (result > 0) - { - return new Size(NativeMethods.Util.LOWORD(result), NativeMethods.Util.HIWORD(result)); - } - } - if (TextAlign == ToolBarTextAlign.Underneath) - { - return new Size(39, 36); // Default button size - } - else - { - return new Size(23, 22); // Default button size - } - } - else - { - return buttonSize; - } - } - - set - { - - if (value.Width < 0 || value.Height < 0) - { - throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidArgument, nameof(ButtonSize), value)); - } - - if (buttonSize != value) - { - buttonSize = value; - maxWidth = -1; // Force recompute of maxWidth - RecreateHandle(); - AdjustSize(Dock); - } - } - } - - /// - /// Returns the parameters needed to create the handle. Inheriting classes - /// can override this to provide extra functionality. They should not, - /// however, forget to get base.CreateParams first to get the struct - /// filled up with the basic info. - /// - protected override CreateParams CreateParams - { - get - { - CreateParams cp = base.CreateParams; - cp.ClassName = NativeMethods.WC_TOOLBAR; - - // windows forms has it's own docking code. - // - cp.Style |= NativeMethods.CCS_NOPARENTALIGN - | NativeMethods.CCS_NORESIZE; - // | NativeMethods.WS_CHILD was commented out since setTopLevel should be able to work. - - if (!Divider) - { - cp.Style |= NativeMethods.CCS_NODIVIDER; - } - - if (Wrappable) - { - cp.Style |= NativeMethods.TBSTYLE_WRAPPABLE; - } - - if (ShowToolTips && !DesignMode) - { - cp.Style |= NativeMethods.TBSTYLE_TOOLTIPS; - } - - cp.ExStyle &= (~NativeMethods.WS_EX_CLIENTEDGE); - cp.Style &= (~NativeMethods.WS_BORDER); - switch (borderStyle) - { - case BorderStyle.Fixed3D: - cp.ExStyle |= NativeMethods.WS_EX_CLIENTEDGE; - break; - case BorderStyle.FixedSingle: - cp.Style |= NativeMethods.WS_BORDER; - break; - } - - switch (appearance) - { - case ToolBarAppearance.Normal: - break; - case ToolBarAppearance.Flat: - cp.Style |= NativeMethods.TBSTYLE_FLAT; - break; - } - - switch (textAlign) - { - case ToolBarTextAlign.Underneath: - break; - case ToolBarTextAlign.Right: - cp.Style |= NativeMethods.TBSTYLE_LIST; - break; - } - - return cp; - } - } - - protected override ImeMode DefaultImeMode - { - get - { - return ImeMode.Disable; - } - } - - /// - /// Deriving classes can override this to configure a default size for their control. - /// This is more efficient than setting the size in the control's constructor. - /// - protected override Size DefaultSize - { - get - { - return new Size(100, 22); - } - } - - /// - /// Gets or sets a value indicating - /// whether the toolbar displays a divider. - /// - [ - SRCategory(nameof(SR.CatAppearance)), - DefaultValue(true), - SRDescription(nameof(SR.ToolBarDividerDescr)) - ] - public bool Divider - { - get - { - return toolBarState[TOOLBARSTATE_divider]; - } - - set - { - if (Divider != value) - { - - toolBarState[TOOLBARSTATE_divider] = value; - RecreateHandle(); - } - } - } - - /// - /// Sets the way in which this ToolBar is docked to its parent. We need to - /// override this to ensure autoSizing works correctly - /// - [ - Localizable(true), - DefaultValue(DockStyle.Top) - ] - public override DockStyle Dock - { - get { return base.Dock; } - - set - { - //valid values are 0x0 to 0x5 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)DockStyle.None, (int)DockStyle.Fill)) - { - throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DockStyle)); - } - - if (Dock != value) - { - if (value == DockStyle.Left || value == DockStyle.Right) - { - SetStyle(ControlStyles.FixedWidth, AutoSize); - SetStyle(ControlStyles.FixedHeight, false); - } - else - { - SetStyle(ControlStyles.FixedHeight, AutoSize); - SetStyle(ControlStyles.FixedWidth, false); - } - AdjustSize(value); - base.Dock = value; - } - } - } - - /// - /// This property is overridden and hidden from statement completion - /// on controls that are based on Win32 Native Controls. - /// - [EditorBrowsable(EditorBrowsableState.Never)] - protected override bool DoubleBuffered - { - get - { - return base.DoubleBuffered; - } - set - { - base.DoubleBuffered = value; - } - } - - /// - /// Gets or sets a value indicating whether drop-down buttons on a - /// toolbar display down arrows. - /// - [ - DefaultValue(false), - SRCategory(nameof(SR.CatAppearance)), - Localizable(true), - SRDescription(nameof(SR.ToolBarDropDownArrowsDescr)) - ] - public bool DropDownArrows - { - get - { - return toolBarState[TOOLBARSTATE_dropDownArrows]; - } - - set - { - - if (DropDownArrows != value) - { - toolBarState[TOOLBARSTATE_dropDownArrows] = value; - RecreateHandle(); - } - } - } - - [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override Color ForeColor - { - get - { - return base.ForeColor; - } - set - { - base.ForeColor = value; - } - } - - [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler ForeColorChanged - { - add => base.ForeColorChanged += value; - remove => base.ForeColorChanged -= value; - } - - /// - /// Gets or sets the collection of images available to the toolbar button - /// controls. - /// - [ - SRCategory(nameof(SR.CatBehavior)), - DefaultValue(null), - SRDescription(nameof(SR.ToolBarImageListDescr)) - ] - public ImageList ImageList - { - get - { - return imageList; - } - set - { - if (value != imageList) - { - EventHandler recreateHandler = new EventHandler(ImageListRecreateHandle); - EventHandler disposedHandler = new EventHandler(DetachImageList); - - if (imageList != null) - { - imageList.Disposed -= disposedHandler; - imageList.RecreateHandle -= recreateHandler; - } - - imageList = value; - - if (value != null) - { - value.Disposed += disposedHandler; - value.RecreateHandle += recreateHandler; - } - - if (IsHandleCreated) - { - RecreateHandle(); - } - } - } - } - - /// - /// Gets the size of the images in the image list assigned to the - /// toolbar. - /// - [ - SRCategory(nameof(SR.CatBehavior)), - Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced), - DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), - SRDescription(nameof(SR.ToolBarImageSizeDescr)) - ] - public Size ImageSize - { - get - { - if (imageList != null) - { - return imageList.ImageSize; - } - else - { - return new Size(0, 0); - } - } - } - - [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public ImeMode ImeMode - { - get - { - return base.ImeMode; - } - set - { - base.ImeMode = value; - } - } - - [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event EventHandler ImeModeChanged - { - add => base.ImeModeChanged += value; - remove => base.ImeModeChanged -= value; - } - - /// - /// The preferred height for this ToolBar control. This is - /// used by the AutoSizing code. - /// - internal int PreferredHeight - { - get - { - int height = 0; - - if (buttons == null || buttonCount == 0 || !IsHandleCreated) - { - height = ButtonSize.Height; - } - else - { - // get the first visible button and get it's height - // - RECT rect = new RECT(); - int firstVisible; - - for (firstVisible = 0; firstVisible < buttons.Length; firstVisible++) - { - if (buttons[firstVisible] != null && buttons[firstVisible].Visible) - { - break; - } - } - if (firstVisible == buttons.Length) - { - firstVisible = 0; - } - - SendMessage(NativeMethods.TB_GETRECT, firstVisible, ref rect); - - // height is the button's height plus some extra goo - // - height = rect.bottom - rect.top; - } - - // if the ToolBar is wrappable, and there is more than one row, make - // sure the height is correctly adjusted - // - if (Wrappable && IsHandleCreated) - { - height *= unchecked((int)(long)SendMessage(NativeMethods.TB_GETROWS, 0, 0)); - } - - height = (height > 0) ? height : 1; - - switch (borderStyle) - { - case BorderStyle.FixedSingle: - height += SystemInformation.BorderSize.Height; - break; - case BorderStyle.Fixed3D: - height += SystemInformation.Border3DSize.Height; - break; - } - - if (Divider) - { - height += 2; - } - - height += 4; - - return height; - } - - } - - /// - /// The preferred width for this ToolBar control. This is - /// used by AutoSizing code. - /// NOTE!!!!!!!!! This function assumes it's only going to get called - /// if the control is docked left or right [ie, it really - /// just returns a max width] - /// - internal int PreferredWidth - { - get - { - int width; - - // fortunately, we compute this value sometimes, so we can just - // use it if we have it. - // - if (maxWidth == -1) - { - // don't have it, have to recompute - // - if (!IsHandleCreated || buttons == null) - { - maxWidth = ButtonSize.Width; - } - else - { - - RECT rect = new RECT(); - - for (int x = 0; x < buttonCount; x++) - { - SendMessage(NativeMethods.TB_GETRECT, 0, ref rect); - if ((rect.right - rect.left) > maxWidth) - { - maxWidth = rect.right - rect.left; - } - } - } - } - - width = maxWidth; - - if (borderStyle != BorderStyle.None) - { - width += SystemInformation.BorderSize.Height * 4 + 3; - } - - return width; - } - } - - [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override RightToLeft RightToLeft - { - get - { - return base.RightToLeft; - } - set - { - base.RightToLeft = value; - } - } - - [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event EventHandler RightToLeftChanged - { - add => base.RightToLeftChanged += value; - remove => base.RightToLeftChanged -= value; - } - - /// - /// We need to track the current scale factor so that we can tell the - /// unmanaged control how to scale its buttons. - /// - [EditorBrowsable(EditorBrowsableState.Never)] - protected override void ScaleCore(float dx, float dy) - { - currentScaleDX = dx; - currentScaleDY = dy; - base.ScaleCore(dx, dy); - UpdateButtons(); - } - - /// - /// We need to track the current scale factor so that we can tell the - /// unmanaged control how to scale its buttons. - /// - protected override void ScaleControl(SizeF factor, BoundsSpecified specified) - { - currentScaleDX = factor.Width; - currentScaleDY = factor.Height; - base.ScaleControl(factor, specified); - } - - /// - /// Gets or sets a value indicating whether the toolbar displays a - /// tool tip for each button. - /// - [ - SRCategory(nameof(SR.CatBehavior)), - DefaultValue(false), - Localizable(true), - SRDescription(nameof(SR.ToolBarShowToolTipsDescr)) - ] - public bool ShowToolTips - { - get - { - return toolBarState[TOOLBARSTATE_showToolTips]; - } - set - { - if (ShowToolTips != value) - { - - toolBarState[TOOLBARSTATE_showToolTips] = value; - RecreateHandle(); - } - } - } - - [DefaultValue(false)] - new public bool TabStop - { - get - { - return base.TabStop; - } - set - { - base.TabStop = value; - } - } - - [ - Browsable(false), EditorBrowsable(EditorBrowsableState.Never), - Bindable(false), - DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) - ] - public override string Text - { - get - { - return base.Text; - } - set - { - base.Text = value; - } - } - - [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler TextChanged - { - add => base.TextChanged += value; - remove => base.TextChanged -= value; - } - - /// - /// Gets or sets the alignment of text in relation to each - /// image displayed on - /// the toolbar button controls. - /// - [ - SRCategory(nameof(SR.CatAppearance)), - DefaultValue(ToolBarTextAlign.Underneath), - Localizable(true), - SRDescription(nameof(SR.ToolBarTextAlignDescr)) - ] - public ToolBarTextAlign TextAlign - { - get - { - return textAlign; - } - set - { - //valid values are 0x0 to 0x1 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)ToolBarTextAlign.Underneath, (int)ToolBarTextAlign.Right)) - { - throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ToolBarTextAlign)); - } - - if (textAlign == value) - { - return; - } - - textAlign = value; - RecreateHandle(); - } - } - - /// - /// Gets - /// or sets a value - /// indicating whether the toolbar buttons wrap to the next line if the - /// toolbar becomes too small to display all the buttons - /// on the same line. - /// - [ - SRCategory(nameof(SR.CatBehavior)), - DefaultValue(true), - Localizable(true), - SRDescription(nameof(SR.ToolBarWrappableDescr)) - ] - public bool Wrappable - { - get - { - return toolBarState[TOOLBARSTATE_wrappable]; - } - set - { - if (Wrappable != value) - { - toolBarState[TOOLBARSTATE_wrappable] = value; - RecreateHandle(); - } - } - } - - /// - /// Occurs when a on the is clicked. - /// - [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.ToolBarButtonClickDescr))] - public event ToolBarButtonClickEventHandler ButtonClick - { - add => onButtonClick += value; - remove => onButtonClick -= value; - } - - /// - /// Occurs when a drop-down style or its down arrow is clicked. - /// - [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.ToolBarButtonDropDownDescr))] - public event ToolBarButtonClickEventHandler ButtonDropDown - { - add => onButtonDropDown += value; - remove => onButtonDropDown -= value; - } - - /// - /// ToolBar Onpaint. - /// - /// - [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event PaintEventHandler Paint - { - add => base.Paint += value; - remove => base.Paint -= value; - } - - /// - /// Adjusts the height or width of the ToolBar to make sure we have enough - /// room to show the buttons. - /// - // we pass in a value for dock rather than calling Dock ourselves - // because we can't change Dock until the size has been properly adjusted. - private void AdjustSize(DockStyle dock) - { - int saveSize = requestedSize; - try - { - if (dock == DockStyle.Left || dock == DockStyle.Right) - { - Width = AutoSize ? PreferredWidth : saveSize; - } - else - { - Height = AutoSize ? PreferredHeight : saveSize; - } - } - finally - { - requestedSize = saveSize; - } - } - - /// - /// This routine lets us change a bunch of things about the toolbar without - /// having each operation wait for the paint to complete. This must be - /// matched up with a call to endUpdate(). - /// - internal void BeginUpdate() - { - BeginUpdateInternal(); - } - - protected override void CreateHandle() - { - if (!RecreatingHandle) - { - IntPtr userCookie = UnsafeNativeMethods.ThemingScope.Activate(); - try - { - NativeMethods.INITCOMMONCONTROLSEX icc = new NativeMethods.INITCOMMONCONTROLSEX - { - dwICC = NativeMethods.ICC_BAR_CLASSES - }; - SafeNativeMethods.InitCommonControlsEx(icc); - } - finally - { - UnsafeNativeMethods.ThemingScope.Deactivate(userCookie); - } - } - base.CreateHandle(); - } - - /// - /// Resets the imageList to null. We wire this method up to the imageList's - /// Dispose event, so that we don't hang onto an imageList that's gone away. - /// - private void DetachImageList(object sender, EventArgs e) - { - ImageList = null; - } - - protected override void Dispose(bool disposing) - { - if (disposing) - { - // - lock (this) - { - // We need to mark the Disposing state here so buttonsCollection won't attempt to update - // the buttons. - bool currentDisposing = GetState(STATE_DISPOSING); - - try - { - SetState(STATE_DISPOSING, true); - - if (imageList != null) - { - imageList.Disposed -= new EventHandler(DetachImageList); - imageList = null; - } - - if (buttonsCollection != null) - { - ToolBarButton[] buttonCopy = new ToolBarButton[buttonsCollection.Count]; - ((ICollection)buttonsCollection).CopyTo(buttonCopy, 0); - buttonsCollection.Clear(); - - foreach (ToolBarButton b in buttonCopy) - { - b.Dispose(); - } - } - } - finally - { - SetState(STATE_DISPOSING, currentDisposing); - } - } - } - - base.Dispose(disposing); - } - - /// - /// This routine lets us change a bunch of things about the toolbar without - /// having each operation wait for the paint to complete. This must be - /// matched up with a call to beginUpdate(). - /// - internal void EndUpdate() - { - EndUpdateInternal(); - } - - /// - /// Forces the button sizes based on various different things. The default - /// ToolBar button sizing rules are pretty primitive and this tends to be - /// a little better, and lets us actually show things like DropDown Arrows - /// for ToolBars - /// - private void ForceButtonWidths() - { - if (buttons != null && buttonSize.IsEmpty && IsHandleCreated) - { - - // force ourselves to re-compute this each time - // - maxWidth = -1; - - for (int x = 0; x < buttonCount; x++) - { - - NativeMethods.TBBUTTONINFO tbbi = new NativeMethods.TBBUTTONINFO - { - cbSize = Marshal.SizeOf(), - cx = buttons[x].Width - }; - - if (tbbi.cx > maxWidth) - { - maxWidth = tbbi.cx; - } - - tbbi.dwMask = NativeMethods.TBIF_SIZE; - UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TB_SETBUTTONINFO, x, ref tbbi); - } - } - } - - private void ImageListRecreateHandle(object sender, EventArgs e) - { - if (IsHandleCreated) - { - RecreateHandle(); - } - } - - private void Insert(int index, ToolBarButton button) - { - button.parent = this; - - if (buttons == null) - { - buttons = new ToolBarButton[4]; - } - else if (buttons.Length == buttonCount) - { - ToolBarButton[] newButtons = new ToolBarButton[buttonCount + 4]; - System.Array.Copy(buttons, 0, newButtons, 0, buttonCount); - buttons = newButtons; - } - - if (index < buttonCount) - { - System.Array.Copy(buttons, index, buttons, index + 1, buttonCount - index); - } - - buttons[index] = button; - buttonCount++; - } - - /// - /// Inserts a button at a given location on the toolbar control. - /// - private void InsertButton(int index, ToolBarButton value) - { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - - if (index < 0 || ((buttons != null) && (index > buttonCount))) - { - throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); - } - - // insert the button into our local array, and then into the - // real windows ToolBar control - // - Insert(index, value); - if (IsHandleCreated) - { - NativeMethods.TBBUTTON tbbutton = value.GetTBBUTTON(index); - UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TB_INSERTBUTTON, index, ref tbbutton); - } - UpdateButtons(); - } - - /// - /// Adds a button to the ToolBar - /// - private int InternalAddButton(ToolBarButton button) - { - if (button == null) - { - throw new ArgumentNullException(nameof(button)); - } - - int index = buttonCount; - Insert(index, button); - return index; - } - - /// - /// Changes the data for a button in the ToolBar, and then does the appropriate - /// work to update the ToolBar control. - /// - internal void InternalSetButton(int index, ToolBarButton value, bool recreate, bool updateText) - { - // tragically, there doesn't appear to be a way to remove the - // string for the button if it has one, so we just have to leave - // it in there. - // - buttons[index].parent = null; - buttons[index].stringIndex = (IntPtr)(-1); - buttons[index] = value; - buttons[index].parent = this; - - if (IsHandleCreated) - { - NativeMethods.TBBUTTONINFO tbbi = value.GetTBBUTTONINFO(updateText, index); - UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TB_SETBUTTONINFO, index, ref tbbi); - - if (tbbi.pszText != IntPtr.Zero) - { - Marshal.FreeHGlobal(tbbi.pszText); - } - - if (recreate) - { - UpdateButtons(); - } - else - { - // after doing anything with the comctl ToolBar control, this - // appears to be a good idea. - // - SendMessage(NativeMethods.TB_AUTOSIZE, 0, 0); - - ForceButtonWidths(); - Invalidate(); - } - } - } - - /// - /// Raises the - /// event. - /// - protected virtual void OnButtonClick(ToolBarButtonClickEventArgs e) - { - onButtonClick?.Invoke(this, e); - } - - /// - /// Raises the - /// event. - /// - protected virtual void OnButtonDropDown(ToolBarButtonClickEventArgs e) - { - onButtonDropDown?.Invoke(this, e); - } - - /// - /// Overridden from the control class so we can add all the buttons - /// and do whatever work needs to be done. - /// Don't forget to call base.OnHandleCreated. - /// - protected override void OnHandleCreated(EventArgs e) - { - base.OnHandleCreated(e); - - // we have to set the button struct size, because they don't. - // - SendMessage(NativeMethods.TB_BUTTONSTRUCTSIZE, Marshal.SizeOf(), 0); - - // set up some extra goo - // - if (DropDownArrows) - { - SendMessage(NativeMethods.TB_SETEXTENDEDSTYLE, 0, NativeMethods.TBSTYLE_EX_DRAWDDARROWS); - } - - // if we have an imagelist, add it in now. - // - if (imageList != null) - { - SendMessage(NativeMethods.TB_SETIMAGELIST, 0, imageList.Handle); - } - - RealizeButtons(); - - // Force a repaint, as occasionally the ToolBar border does not paint properly - // (comctl ToolBar is flaky) - // - BeginUpdate(); - try - { - Size size = Size; - Size = new Size(size.Width + 1, size.Height); - Size = size; - } - finally - { - EndUpdate(); - } - } - - /// - /// The control is being resized. Make sure the width/height are correct. - /// - protected override void OnResize(EventArgs e) - { - base.OnResize(e); - if (Wrappable) - { - AdjustSize(Dock); - } - } - - /// - /// Overridden to ensure that the buttons and the control resize properly - /// whenever the font changes. - /// - protected override void OnFontChanged(EventArgs e) - { - base.OnFontChanged(e); - if (IsHandleCreated) - { - if (!buttonSize.IsEmpty) - { - SendToolbarButtonSizeMessage(); - } - else - { - AdjustSize(Dock); - ForceButtonWidths(); - } - } - } - - /// - /// Sets all the button data into the ToolBar control - /// - private void RealizeButtons() - { - if (buttons != null) - { - IntPtr ptbbuttons = IntPtr.Zero; - try - { - BeginUpdate(); - // go and add in all the strings for all of our buttons - // - for (int x = 0; x < buttonCount; x++) - { - if (buttons[x].Text.Length > 0) - { - string addString = buttons[x].Text + '\0'.ToString(); - buttons[x].stringIndex = SendMessage(NativeMethods.TB_ADDSTRING, 0, addString); - } - else - { - buttons[x].stringIndex = (IntPtr)(-1); - } - } - - // insert the buttons and set their parent pointers - // - int cb = Marshal.SizeOf(); - int count = buttonCount; - ptbbuttons = Marshal.AllocHGlobal(checked(cb * count)); - - for (int x = 0; x < count; x++) - { - - NativeMethods.TBBUTTON tbbutton = buttons[x].GetTBBUTTON(x); - Marshal.StructureToPtr(tbbutton, (IntPtr)(checked((long)ptbbuttons + (cb * x))), true); - buttons[x].parent = this; - } - - SendMessage(NativeMethods.TB_ADDBUTTONS, count, ptbbuttons); - - // after doing anything with the comctl ToolBar control, this - // appears to be a good idea. - // - SendMessage(NativeMethods.TB_AUTOSIZE, 0, 0); - - // The win32 ToolBar control is somewhat unpredictable here. We - // have to set the button size after we've created all the - // buttons. Otherwise, we need to manually set the width of all - // the buttons so they look reasonable - // - if (!buttonSize.IsEmpty) - { - SendToolbarButtonSizeMessage(); - } - else - { - ForceButtonWidths(); - } - AdjustSize(Dock); - } - finally - { - Marshal.FreeHGlobal(ptbbuttons); - EndUpdate(); - } - } - } - - private void RemoveAt(int index) - { - buttons[index].parent = null; - buttons[index].stringIndex = (IntPtr)(-1); - buttonCount--; - - if (index < buttonCount) - { - System.Array.Copy(buttons, index + 1, buttons, index, buttonCount - index); - } - - buttons[buttonCount] = null; - } - - /// - /// Resets the toolbar buttons to the minimum - /// size. - /// - private void ResetButtonSize() - { - buttonSize = Size.Empty; - RecreateHandle(); - } - - /// Sends a TB_SETBUTTONSIZE message to the unmanaged control, with size arguments properly scaled. - private void SendToolbarButtonSizeMessage() - { - SendMessage(NativeMethods.TB_SETBUTTONSIZE, 0, NativeMethods.Util.MAKELPARAM((int)(buttonSize.Width * currentScaleDX), (int)(buttonSize.Height * currentScaleDY))); - } - - /// - /// Overrides Control.setBoundsCore to enforce AutoSize. - /// - protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) - { - int originalHeight = height; - int originalWidth = width; - - base.SetBoundsCore(x, y, width, height, specified); - - Rectangle bounds = Bounds; - if (Dock == DockStyle.Left || Dock == DockStyle.Right) - { - if ((specified & BoundsSpecified.Width) != BoundsSpecified.None) - { - requestedSize = width; - } - - if (AutoSize) - { - width = PreferredWidth; - } - - if (width != originalWidth && Dock == DockStyle.Right) - { - int deltaWidth = originalWidth - width; - x += deltaWidth; - } - - } - else - { - if ((specified & BoundsSpecified.Height) != BoundsSpecified.None) - { - requestedSize = height; - } - - if (AutoSize) - { - height = PreferredHeight; - } - - if (height != originalHeight && Dock == DockStyle.Bottom) - { - int deltaHeight = originalHeight - height; - y += deltaHeight; - } - - } - - base.SetBoundsCore(x, y, width, height, specified); - } - - /// - /// Determines if the property needs to be persisted. - /// - private bool ShouldSerializeButtonSize() - { - return !buttonSize.IsEmpty; - } - - /// - /// Called by ToolTip to poke in that Tooltip into this ComCtl so that the Native ChildToolTip is not exposed. - /// - internal void SetToolTip(ToolTip toolTip) - { - UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TB_SETTOOLTIPS, new HandleRef(toolTip, toolTip.Handle), 0); - - } - - /// - /// Returns a string representation for this control. - /// - public override string ToString() - { - string s = base.ToString(); - s += ", Buttons.Count: " + buttonCount.ToString(CultureInfo.CurrentCulture); - if (buttonCount > 0) - { - s += ", Buttons[0]: " + buttons[0].ToString(); - } - - return s; - } - - /// - /// Updates all the information in the ToolBar. Tragically, the win32 - /// control is pretty flakey, and the only real choice here is to recreate - /// the handle and re-realize all the buttons. - /// - internal void UpdateButtons() - { - if (IsHandleCreated) - { - RecreateHandle(); - } - } - - /// - /// The button clicked was a dropdown button. If it has a menu specified, - /// show it now. Otherwise, fire an onButtonDropDown event. - /// - private void WmNotifyDropDown(ref Message m) - { - NativeMethods.NMTOOLBAR nmTB = (NativeMethods.NMTOOLBAR)m.GetLParam(typeof(NativeMethods.NMTOOLBAR)); - - ToolBarButton tbb = (ToolBarButton)buttons[nmTB.iItem]; - if (tbb == null) - { - throw new InvalidOperationException(SR.ToolBarButtonNotFound); - } - - OnButtonDropDown(new ToolBarButtonClickEventArgs(tbb)); - - Menu menu = tbb.DropDownMenu; - if (menu != null) - { - RECT rc = new RECT(); - NativeMethods.TPMPARAMS tpm = new NativeMethods.TPMPARAMS(); - - SendMessage(NativeMethods.TB_GETRECT, nmTB.iItem, ref rc); - - if ((menu.GetType()).IsAssignableFrom(typeof(ContextMenu))) - { - ((ContextMenu)menu).Show(this, new Point(rc.left, rc.bottom)); - } - else - { - Menu main = menu.GetMainMenu(); - if (main != null) - { - main.ProcessInitMenuPopup(menu.Handle); - } - - UnsafeNativeMethods.MapWindowPoints(new HandleRef(nmTB.hdr, nmTB.hdr.hwndFrom), NativeMethods.NullHandleRef, ref rc, 2); - - tpm.rcExclude_left = rc.left; - tpm.rcExclude_top = rc.top; - tpm.rcExclude_right = rc.right; - tpm.rcExclude_bottom = rc.bottom; - - SafeNativeMethods.TrackPopupMenuEx( - new HandleRef(menu, menu.Handle), - NativeMethods.TPM_LEFTALIGN | - NativeMethods.TPM_LEFTBUTTON | - NativeMethods.TPM_VERTICAL, - rc.left, rc.bottom, - new HandleRef(this, Handle), tpm); - } - } - } - - private void WmNotifyNeedText(ref Message m) - { - NativeMethods.TOOLTIPTEXT ttt = (NativeMethods.TOOLTIPTEXT)m.GetLParam(typeof(NativeMethods.TOOLTIPTEXT)); - int commandID = (int)ttt.hdr.idFrom; - ToolBarButton tbb = buttons[commandID]; - - if (tbb != null && tbb.ToolTipText != null) - { - ttt.lpszText = tbb.ToolTipText; - } - else - { - ttt.lpszText = null; - } - - ttt.hinst = IntPtr.Zero; - - // RightToLeft reading order - // - if (RightToLeft == RightToLeft.Yes) - { - ttt.uFlags |= (int)ComCtl32.TTF.RTLREADING; - } - - Marshal.StructureToPtr(ttt, m.LParam, false); - } - - // Track the currently hot item since the user might be using the tab and - // arrow keys to navigate the toolbar and if that's the case, we'll need to know where to re- - // position the tooltip window when the underlying toolbar control attempts to display it. - private void WmNotifyHotItemChange(ref Message m) - { - // Should we set the hot item? - NativeMethods.NMTBHOTITEM nmTbHotItem = (NativeMethods.NMTBHOTITEM)m.GetLParam(typeof(NativeMethods.NMTBHOTITEM)); - if (NativeMethods.HICF_ENTERING == (nmTbHotItem.dwFlags & NativeMethods.HICF_ENTERING)) - { - hotItem = nmTbHotItem.idNew; - } - else if (NativeMethods.HICF_LEAVING == (nmTbHotItem.dwFlags & NativeMethods.HICF_LEAVING)) - { - hotItem = -1; - } - else if (NativeMethods.HICF_MOUSE == (nmTbHotItem.dwFlags & NativeMethods.HICF_MOUSE)) - { - hotItem = nmTbHotItem.idNew; - } - else if (NativeMethods.HICF_ARROWKEYS == (nmTbHotItem.dwFlags & NativeMethods.HICF_ARROWKEYS)) - { - hotItem = nmTbHotItem.idNew; - } - else if (NativeMethods.HICF_ACCELERATOR == (nmTbHotItem.dwFlags & NativeMethods.HICF_ACCELERATOR)) - { - hotItem = nmTbHotItem.idNew; - } - else if (NativeMethods.HICF_DUPACCEL == (nmTbHotItem.dwFlags & NativeMethods.HICF_DUPACCEL)) - { - hotItem = nmTbHotItem.idNew; - } - else if (NativeMethods.HICF_RESELECT == (nmTbHotItem.dwFlags & NativeMethods.HICF_RESELECT)) - { - hotItem = nmTbHotItem.idNew; - } - else if (NativeMethods.HICF_LMOUSE == (nmTbHotItem.dwFlags & NativeMethods.HICF_LMOUSE)) - { - hotItem = nmTbHotItem.idNew; - } - else if (NativeMethods.HICF_TOGGLEDROPDOWN == (nmTbHotItem.dwFlags & NativeMethods.HICF_TOGGLEDROPDOWN)) - { - hotItem = nmTbHotItem.idNew; - } - } - - private void WmReflectCommand(ref Message m) - { - int id = NativeMethods.Util.LOWORD(m.WParam); - ToolBarButton tbb = buttons[id]; - - if (tbb != null) - { - ToolBarButtonClickEventArgs e = new ToolBarButtonClickEventArgs(tbb); - OnButtonClick(e); - } - - base.WndProc(ref m); - - ResetMouseEventArgs(); - } - - protected override void WndProc(ref Message m) - { - switch (m.Msg) - { - case WindowMessages.WM_COMMAND + WindowMessages.WM_REFLECT: - WmReflectCommand(ref m); - break; - - case WindowMessages.WM_NOTIFY: - case WindowMessages.WM_NOTIFY + WindowMessages.WM_REFLECT: - NativeMethods.NMHDR note = (NativeMethods.NMHDR)m.GetLParam(typeof(NativeMethods.NMHDR)); - switch (note.code) - { - case NativeMethods.TTN_NEEDTEXT: - WmNotifyNeedText(ref m); - m.Result = (IntPtr)1; - return; - case NativeMethods.TTN_SHOW: - // Prevent the tooltip from displaying in the upper left corner of the - // desktop when the control is nowhere near that location. - NativeMethods.WINDOWPLACEMENT wndPlacement = new NativeMethods.WINDOWPLACEMENT(); - int nRet = UnsafeNativeMethods.GetWindowPlacement(new HandleRef(null, note.hwndFrom), ref wndPlacement); - - // Is this tooltip going to be positioned in the upper left corner of the display, - // but nowhere near the toolbar button? - if (wndPlacement.rcNormalPosition_left == 0 && - wndPlacement.rcNormalPosition_top == 0 && - hotItem != -1) - { - - // Assume that we're going to vertically center the tooltip on the right edge of the current - // hot item. - - // Where is the right edge of the current hot item? - int buttonRight = 0; - for (int idx = 0; idx <= hotItem; idx++) - { - // How wide is the item at this index? (It could be a separator, and therefore a different width.) - buttonRight += buttonsCollection[idx].GetButtonWidth(); - } - - // Where can we place this tooltip so that it will be completely visible on the current display? - int tooltipWidth = wndPlacement.rcNormalPosition_right - wndPlacement.rcNormalPosition_left; - int tooltipHeight = wndPlacement.rcNormalPosition_bottom - wndPlacement.rcNormalPosition_top; - - // We'll need screen coordinates of this position for setting the tooltip's position - int x = Location.X + buttonRight + 1; - int y = Location.Y + (ButtonSize.Height / 2); - var leftTop = new Point(x, y); - UnsafeNativeMethods.ClientToScreen(new HandleRef(this, Handle), ref leftTop); - - // Will the tooltip bleed off the top? - if (leftTop.Y < SystemInformation.WorkingArea.Y) - { - // Reposition the tooltip to be displayed below the button - leftTop.Y += (ButtonSize.Height / 2) + 1; - } - - // Will the tooltip bleed off the bottom? - if (leftTop.Y + tooltipHeight > SystemInformation.WorkingArea.Height) - { - // Reposition the tooltip to be displayed above the button - leftTop.Y -= ((ButtonSize.Height / 2) + tooltipHeight + 1); - } - - // Will the tooltip bleed off the right edge? - if (leftTop.X + tooltipWidth > SystemInformation.WorkingArea.Right) - { - // Move the tooltip far enough left that it will display in the working area - leftTop.X -= (ButtonSize.Width + tooltipWidth + 2); - } - - SafeNativeMethods.SetWindowPos(new HandleRef(null, note.hwndFrom), NativeMethods.NullHandleRef, leftTop.X, leftTop.Y, 0, 0, NativeMethods.SWP_NOSIZE | NativeMethods.SWP_NOZORDER | NativeMethods.SWP_NOACTIVATE); - m.Result = (IntPtr)1; - return; - } - break; - - case NativeMethods.TBN_HOTITEMCHANGE: - WmNotifyHotItemChange(ref m); - break; - - case NativeMethods.TBN_QUERYINSERT: - m.Result = (IntPtr)1; - break; - - case NativeMethods.TBN_DROPDOWN: - WmNotifyDropDown(ref m); - break; - } - break; - - } - base.WndProc(ref m); - } - - /// - /// Encapsulates a collection of controls for use by the - /// class. - /// - public class ToolBarButtonCollection : IList - { - private readonly ToolBar owner; - private bool suspendUpdate; - /// A caching mechanism for key accessor - /// We use an index here rather than control so that we don't have lifetime - /// issues by holding on to extra references. - private int lastAccessedIndex = -1; - - /// - /// Initializes a new instance of the class and assigns it to the specified toolbar. - /// - public ToolBarButtonCollection(ToolBar owner) - { - this.owner = owner; - } - - /// - /// Gets or sets the toolbar button at the specified indexed location in the - /// toolbar button collection. - /// - public virtual ToolBarButton this[int index] - { - get - { - if (index < 0 || ((owner.buttons != null) && (index >= owner.buttonCount))) - { - throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); - } - - return owner.buttons[index]; - } - set - { - - // Sanity check parameters - // - if (index < 0 || ((owner.buttons != null) && index >= owner.buttonCount)) - { - throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); - } - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - - owner.InternalSetButton(index, value, true, true); - } - } - - object IList.this[int index] - { - get - { - return this[index]; - } - set - { - if (value is ToolBarButton) - { - this[index] = (ToolBarButton)value; - } - else - { - throw new ArgumentException(SR.ToolBarBadToolBarButton, "value"); - } - } - } - /// - /// Retrieves the child control with the specified key. - /// - public virtual ToolBarButton this[string key] - { - get - { - // We do not support null and empty string as valid keys. - if (string.IsNullOrEmpty(key)) - { - return null; - } - - // Search for the key in our collection - int index = IndexOfKey(key); - if (IsValidIndex(index)) - { - return this[index]; - } - else - { - return null; - } - - } - } - /// - /// Gets the number of buttons in the toolbar button collection. - /// - [Browsable(false)] - public int Count - { - get - { - return owner.buttonCount; - } - } - - object ICollection.SyncRoot - { - get - { - return this; - } - } - - bool ICollection.IsSynchronized - { - get - { - return false; - } - } - - bool IList.IsFixedSize - { - get - { - return false; - } - } - - public bool IsReadOnly - { - get - { - return false; - } - } - - /// - /// Adds a new toolbar button to - /// the end of the toolbar button collection. - /// - public int Add(ToolBarButton button) - { - - int index = owner.InternalAddButton(button); - - if (!suspendUpdate) - { - owner.UpdateButtons(); - } - - return index; - } - - public int Add(string text) - { - ToolBarButton button = new ToolBarButton(text); - return Add(button); - } - - int IList.Add(object button) - { - if (button is ToolBarButton) - { - return Add((ToolBarButton)button); - } - else - { - throw new ArgumentException(SR.ToolBarBadToolBarButton, "button"); - } - } - - public void AddRange(ToolBarButton[] buttons) - { - if (buttons == null) - { - throw new ArgumentNullException(nameof(buttons)); - } - try - { - suspendUpdate = true; - foreach (ToolBarButton button in buttons) - { - Add(button); - } - } - finally - { - suspendUpdate = false; - owner.UpdateButtons(); - } - } - - /// - /// Removes - /// all buttons from the toolbar button collection. - /// - public void Clear() - { - - if (owner.buttons == null) - { - return; - } - - for (int x = owner.buttonCount; x > 0; x--) - { - if (owner.IsHandleCreated) - { - owner.SendMessage(NativeMethods.TB_DELETEBUTTON, x - 1, 0); - } - owner.RemoveAt(x - 1); - } - - owner.buttons = null; - owner.buttonCount = 0; - if (!owner.Disposing) - { - owner.UpdateButtons(); - } - } - - public bool Contains(ToolBarButton button) - { - return IndexOf(button) != -1; - } - - bool IList.Contains(object button) - { - if (button is ToolBarButton) - { - return Contains((ToolBarButton)button); - } - else - { - return false; - } - } - - /// - /// Returns true if the collection contains an item with the specified key, false otherwise. - /// - public virtual bool ContainsKey(string key) - { - return IsValidIndex(IndexOfKey(key)); - } - - void ICollection.CopyTo(Array dest, int index) - { - if (owner.buttonCount > 0) - { - System.Array.Copy(owner.buttons, 0, dest, index, owner.buttonCount); - } - } - - public int IndexOf(ToolBarButton button) - { - for (int index = 0; index < Count; ++index) - { - if (this[index] == button) - { - return index; - } - } - return -1; - } - - int IList.IndexOf(object button) - { - if (button is ToolBarButton) - { - return IndexOf((ToolBarButton)button); - } - else - { - return -1; - } - } - - /// - /// The zero-based index of the first occurrence of value within the entire CollectionBase, if found; otherwise, -1. - /// - public virtual int IndexOfKey(string key) - { - // Step 0 - Arg validation - if (string.IsNullOrEmpty(key)) - { - return -1; // we dont support empty or null keys. - } - - // step 1 - check the last cached item - if (IsValidIndex(lastAccessedIndex)) - { - if (WindowsFormsUtils.SafeCompareStrings(this[lastAccessedIndex].Name, key, /* ignoreCase = */ true)) - { - return lastAccessedIndex; - } - } - - // step 2 - search for the item - for (int i = 0; i < Count; i++) - { - if (WindowsFormsUtils.SafeCompareStrings(this[i].Name, key, /* ignoreCase = */ true)) - { - lastAccessedIndex = i; - return i; - } - } - - // step 3 - we didn't find it. Invalidate the last accessed index and return -1. - lastAccessedIndex = -1; - return -1; - } - - public void Insert(int index, ToolBarButton button) - { - owner.InsertButton(index, button); - } - - void IList.Insert(int index, object button) - { - if (button is ToolBarButton) - { - Insert(index, (ToolBarButton)button); - } - else - { - throw new ArgumentException(SR.ToolBarBadToolBarButton, "button"); - } - } - - /// - /// Determines if the index is valid for the collection. - /// - private bool IsValidIndex(int index) - { - return ((index >= 0) && (index < Count)); - } - /// - /// Removes - /// a given button from the toolbar button collection. - /// - public void RemoveAt(int index) - { - int count = (owner.buttons == null) ? 0 : owner.buttonCount; - - if (index < 0 || index >= count) - { - throw new ArgumentOutOfRangeException(nameof(index), string.Format(SR.InvalidArgument, "index", index.ToString(CultureInfo.CurrentCulture))); - } - - if (owner.IsHandleCreated) - { - owner.SendMessage(NativeMethods.TB_DELETEBUTTON, index, 0); - } - - owner.RemoveAt(index); - owner.UpdateButtons(); - - } - - /// - /// Removes the child control with the specified key. - /// - public virtual void RemoveByKey(string key) - { - int index = IndexOfKey(key); - if (IsValidIndex(index)) - { - RemoveAt(index); - } - } - - public void Remove(ToolBarButton button) - { - int index = IndexOf(button); - if (index != -1) - { - RemoveAt(index); - } - } - - void IList.Remove(object button) - { - if (button is ToolBarButton) - { - Remove((ToolBarButton)button); - } - } - - /// - /// Returns an enumerator that can be used to iterate - /// through the toolbar button collection. - /// - public IEnumerator GetEnumerator() - { - return new WindowsFormsUtils.ArraySubsetEnumerator(owner.buttons, owner.buttonCount); - } - } - - } -} - - diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolBarAppearance.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolBarAppearance.cs deleted file mode 100644 index 464c456837b..00000000000 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolBarAppearance.cs +++ /dev/null @@ -1,23 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System.Windows.Forms -{ - /// - /// Specifies the type of toolbar to display. - /// - public enum ToolBarAppearance - { - /// - /// The toolbar and buttons appear as standard three dimensional controls. - /// - Normal = 0, - - /// - /// The toolbar and buttons appear flat, but the buttons change to three - /// dimensional as the mouse pointer moves over them. - /// - Flat = 1, - } -} diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolBarButton.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolBarButton.cs deleted file mode 100644 index 07c27b49eb1..00000000000 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolBarButton.cs +++ /dev/null @@ -1,878 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.ComponentModel; -using System.Diagnostics; -using System.Drawing; -using System.Drawing.Design; -using System.Runtime.InteropServices; -using System.Text; -using Marshal = System.Runtime.InteropServices.Marshal; -using static Interop; - -namespace System.Windows.Forms -{ - /// - /// Represents a Windows toolbar button. - /// - [ - Designer("System.Windows.Forms.Design.ToolBarButtonDesigner, " + AssemblyRef.SystemDesign), - DefaultProperty(nameof(Text)), - ToolboxItem(false), - DesignTimeVisible(false), - ] - public class ToolBarButton : Component - { - string text; - string name = null; - string tooltipText; - bool enabled = true; - bool visible = true; - bool pushed = false; - bool partialPush = false; - private int commandId = -1; // the cached command id of the button. - private ToolBarButtonImageIndexer imageIndexer; - - ToolBarButtonStyle style = ToolBarButtonStyle.PushButton; - - object userData; - - // These variables below are used by the ToolBar control to help - // it manage some information about us. - - /// - /// If this button has a string, what it's index is in the ToolBar's - /// internal list of strings. Needs to be package protected. - /// - internal IntPtr stringIndex = (IntPtr)(-1); - - /// - /// Our parent ToolBar control. - /// - internal ToolBar parent; - - /// - /// For DropDown buttons, we can optionally show a - /// context menu when the button is dropped down. - /// - internal Menu dropDownMenu = null; - - /// - /// Initializes a new instance of the class. - /// - public ToolBarButton() - { - } - - public ToolBarButton(string text) : base() - { - Text = text; - } - - // We need a special way to defer to the ToolBar's image - // list for indexing purposes. - internal class ToolBarButtonImageIndexer : ImageList.Indexer - { - private readonly ToolBarButton owner; - - public ToolBarButtonImageIndexer(ToolBarButton button) - { - owner = button; - } - - public override ImageList ImageList - { - get - { - if ((owner != null) && (owner.parent != null)) - { - return owner.parent.ImageList; - } - return null; - } - set { Debug.Assert(false, "We should never set the image list"); } - } - } - - internal ToolBarButtonImageIndexer ImageIndexer - { - get - { - if (imageIndexer == null) - { - imageIndexer = new ToolBarButtonImageIndexer(this); - } - - return imageIndexer; - } - } - - /// - /// - /// Indicates the menu to be displayed in - /// the drop-down toolbar button. - /// - [ - DefaultValue(null), - TypeConverter(typeof(ReferenceConverter)), - SRDescription(nameof(SR.ToolBarButtonMenuDescr)) - ] - public Menu DropDownMenu - { - get - { - return dropDownMenu; - } - - set - { - //The dropdownmenu must be of type ContextMenu, Main & Items are invalid. - // - if (value != null && !(value is ContextMenu)) - { - throw new ArgumentException(SR.ToolBarButtonInvalidDropDownMenuType); - } - dropDownMenu = value; - } - } - - /// - /// Indicates whether the button is enabled or not. - /// - [ - DefaultValue(true), - Localizable(true), - SRDescription(nameof(SR.ToolBarButtonEnabledDescr)) - ] - public bool Enabled - { - get - { - return enabled; - } - - set - { - if (enabled != value) - { - - enabled = value; - - if (parent != null && parent.IsHandleCreated) - { - parent.SendMessage(NativeMethods.TB_ENABLEBUTTON, FindButtonIndex(), - enabled ? 1 : 0); - } - } - } - } - - /// - /// Indicates the index - /// value of the image assigned to the button. - /// - [ - TypeConverter(typeof(ImageIndexConverter)), - Editor("System.Windows.Forms.Design.ImageIndexEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)), - DefaultValue(-1), - RefreshProperties(RefreshProperties.Repaint), - Localizable(true), - SRDescription(nameof(SR.ToolBarButtonImageIndexDescr)) - ] - public int ImageIndex - { - get - { - return ImageIndexer.Index; - } - set - { - if (ImageIndexer.Index != value) - { - if (value < -1) - { - throw new ArgumentOutOfRangeException(nameof(ImageIndex), string.Format(SR.InvalidLowBoundArgumentEx, nameof(ImageIndex), value, -1)); - } - - ImageIndexer.Index = value; - UpdateButton(false); - } - } - } - - /// - /// Indicates the index - /// value of the image assigned to the button. - /// - [ - TypeConverter(typeof(ImageKeyConverter)), - Editor("System.Windows.Forms.Design.ImageIndexEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)), - DefaultValue(""), - Localizable(true), - RefreshProperties(RefreshProperties.Repaint), - SRDescription(nameof(SR.ToolBarButtonImageIndexDescr)) - ] - public string ImageKey - { - get - { - return ImageIndexer.Key; - } - set - { - if (ImageIndexer.Key != value) - { - ImageIndexer.Key = value; - UpdateButton(false); - } - } - } - /// - /// Name of this control. The designer will set this to the same - /// as the programatic Id "(name)" of the control - however this - /// property has no bearing on the runtime aspects of this control. - /// - [Browsable(false)] - public string Name - { - get - { - return WindowsFormsUtils.GetComponentName(this, name); - } - set - { - if (value == null || value.Length == 0) - { - name = null; - } - else - { - name = value; - } - if (Site != null) - { - Site.Name = name; - } - } - } - - /// - /// Indicates the toolbar control that the toolbar button is assigned to. This property is - /// read-only. - /// - [ - Browsable(false), - ] - public ToolBar Parent - { - get - { - return parent; - } - } - - /// - /// - /// Indicates whether a toggle-style toolbar button - /// is partially pushed. - /// - [ - DefaultValue(false), - SRDescription(nameof(SR.ToolBarButtonPartialPushDescr)) - ] - public bool PartialPush - { - get - { - if (parent == null || !parent.IsHandleCreated) - { - return partialPush; - } - else - { - if ((int)parent.SendMessage(NativeMethods.TB_ISBUTTONINDETERMINATE, FindButtonIndex(), 0) != 0) - { - partialPush = true; - } - else - { - partialPush = false; - } - - return partialPush; - } - } - set - { - if (partialPush != value) - { - partialPush = value; - UpdateButton(false); - } - } - } - - /// - /// Indicates whether a toggle-style toolbar button is currently in the pushed state. - /// - [ - DefaultValue(false), - SRDescription(nameof(SR.ToolBarButtonPushedDescr)) - ] - public bool Pushed - { - get - { - if (parent == null || !parent.IsHandleCreated) - { - return pushed; - } - else - { - return GetPushedState(); - } - } - set - { - if (value != Pushed) - { // Getting property Pushed updates pushed member variable - pushed = value; - UpdateButton(false, false, false); - } - } - } - - /// - /// Indicates the bounding rectangle for a toolbar button. This property is - /// read-only. - /// - public Rectangle Rectangle - { - get - { - if (parent != null) - { - RECT rc = new RECT(); - UnsafeNativeMethods.SendMessage(new HandleRef(parent, parent.Handle), NativeMethods.TB_GETRECT, FindButtonIndex(), ref rc); - return Rectangle.FromLTRB(rc.left, rc.top, rc.right, rc.bottom); - } - return Rectangle.Empty; - } - } - - /// - /// Indicates the style of the - /// toolbar button. - /// - [ - DefaultValue(ToolBarButtonStyle.PushButton), - SRDescription(nameof(SR.ToolBarButtonStyleDescr)), - RefreshProperties(RefreshProperties.Repaint) - ] - public ToolBarButtonStyle Style - { - get - { - return style; - } - set - { - //valid values are 0x1 to 0x4 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)ToolBarButtonStyle.PushButton, (int)ToolBarButtonStyle.DropDownButton)) - { - throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ToolBarButtonStyle)); - } - if (style == value) - { - return; - } - - style = value; - UpdateButton(true); - } - } - - [ - SRCategory(nameof(SR.CatData)), - Localizable(false), - Bindable(true), - SRDescription(nameof(SR.ControlTagDescr)), - DefaultValue(null), - TypeConverter(typeof(StringConverter)), - ] - public object Tag - { - get - { - return userData; - } - set - { - userData = value; - } - } - - /// - /// Indicates the text that is displayed on the toolbar button. - /// - [ - Localizable(true), - DefaultValue(""), - SRDescription(nameof(SR.ToolBarButtonTextDescr)) - ] - public string Text - { - get - { - return text ?? ""; - } - set - { - if (string.IsNullOrEmpty(value)) - { - value = null; - } - - if ((value == null && text != null) || - (value != null && (text == null || !text.Equals(value)))) - { - text = value; - // Adding a mnemonic requires a handle recreate. - UpdateButton(WindowsFormsUtils.ContainsMnemonic(text), true, true); - } - } - } - - /// - /// - /// Indicates - /// the text that appears as a tool tip for a control. - /// - [ - Localizable(true), - DefaultValue(""), - SRDescription(nameof(SR.ToolBarButtonToolTipTextDescr)) - ] - public string ToolTipText - { - get - { - return tooltipText ?? ""; - } - set - { - tooltipText = value; - } - } - - /// - /// - /// Indicates whether the toolbar button - /// is visible. - /// - [ - DefaultValue(true), - Localizable(true), - SRDescription(nameof(SR.ToolBarButtonVisibleDescr)) - ] - public bool Visible - { - get - { - return visible; - } - set - { - if (visible != value) - { - visible = value; - UpdateButton(false); - } - } - } - - /// - /// This is somewhat nasty -- by default, the windows ToolBar isn't very - /// clever about setting the width of buttons, and has a very primitive - /// algorithm that doesn't include for things like drop down arrows, etc. - /// We need to do a bunch of work here to get all the widths correct. Ugh. - /// - internal short Width - { - get - { - Debug.Assert(parent != null, "Parent should be non-null when button width is requested"); - - int width = 0; - ToolBarButtonStyle style = Style; - - Size edge = SystemInformation.Border3DSize; - if (style != ToolBarButtonStyle.Separator) - { - - // COMPAT: this will force handle creation. - // we could use the measurement graphics, but it looks like this has been like this since Everett. - using (Graphics g = parent.CreateGraphicsInternal()) - { - - Size buttonSize = parent.buttonSize; - if (!(buttonSize.IsEmpty)) - { - width = buttonSize.Width; - } - else - { - if (parent.ImageList != null || !string.IsNullOrEmpty(Text)) - { - Size imageSize = parent.ImageSize; - Size textSize = Size.Ceiling(g.MeasureString(Text, parent.Font)); - if (parent.TextAlign == ToolBarTextAlign.Right) - { - if (textSize.Width == 0) - { - width = imageSize.Width + edge.Width * 4; - } - else - { - width = imageSize.Width + textSize.Width + edge.Width * 6; - } - } - else - { - if (imageSize.Width > textSize.Width) - { - width = imageSize.Width + edge.Width * 4; - } - else - { - width = textSize.Width + edge.Width * 4; - } - } - if (style == ToolBarButtonStyle.DropDownButton && parent.DropDownArrows) - { - width += ToolBar.DDARROW_WIDTH; - } - } - else - { - width = parent.ButtonSize.Width; - } - } - } - } - else - { - width = edge.Width * 2; - } - - return (short)width; - } - - } - - protected override void Dispose(bool disposing) - { - if (disposing) - { - if (parent != null) - { - int index = FindButtonIndex(); - if (index != -1) - { - parent.Buttons.RemoveAt(index); - } - } - } - base.Dispose(disposing); - } - - /// - /// Finds out index in the parent. - /// - private int FindButtonIndex() - { - for (int x = 0; x < parent.Buttons.Count; x++) - { - if (parent.Buttons[x] == this) - { - return x; - } - } - return -1; - } - - // This is necessary to get the width of the buttons in the toolbar, - // including the width of separators, so that we can accurately position the tooltip adjacent - // to the currently hot button when the user uses keyboard navigation to access the toolbar. - internal int GetButtonWidth() - { - // Assume that this button is the same width as the parent's ButtonSize's Width - int buttonWidth = Parent.ButtonSize.Width; - - NativeMethods.TBBUTTONINFO button = new NativeMethods.TBBUTTONINFO - { - cbSize = Marshal.SizeOf(), - dwMask = NativeMethods.TBIF_SIZE - }; - - int buttonID = (int)UnsafeNativeMethods.SendMessage(new HandleRef(Parent, Parent.Handle), NativeMethods.TB_GETBUTTONINFO, commandId, ref button); - if (buttonID != -1) - { - buttonWidth = button.cx; - } - - return buttonWidth; - } - - private bool GetPushedState() - { - if ((int)parent.SendMessage(NativeMethods.TB_ISBUTTONCHECKED, FindButtonIndex(), 0) != 0) - { - pushed = true; - } - else - { - pushed = false; - } - - return pushed; - } - - /// - /// Returns a TBBUTTON object that represents this ToolBarButton. - /// - internal NativeMethods.TBBUTTON GetTBBUTTON(int commandId) - { - NativeMethods.TBBUTTON button = new NativeMethods.TBBUTTON - { - iBitmap = ImageIndexer.ActualIndex, - - // set up the state of the button - // - fsState = 0 - }; - if (enabled) - { - button.fsState |= NativeMethods.TBSTATE_ENABLED; - } - - if (partialPush && style == ToolBarButtonStyle.ToggleButton) - { - button.fsState |= NativeMethods.TBSTATE_INDETERMINATE; - } - - if (pushed) - { - button.fsState |= NativeMethods.TBSTATE_CHECKED; - } - - if (!visible) - { - button.fsState |= NativeMethods.TBSTATE_HIDDEN; - } - - // set the button style - // - switch (style) - { - case ToolBarButtonStyle.PushButton: - button.fsStyle = NativeMethods.TBSTYLE_BUTTON; - break; - case ToolBarButtonStyle.ToggleButton: - button.fsStyle = NativeMethods.TBSTYLE_CHECK; - break; - case ToolBarButtonStyle.Separator: - button.fsStyle = NativeMethods.TBSTYLE_SEP; - break; - case ToolBarButtonStyle.DropDownButton: - button.fsStyle = NativeMethods.TBSTYLE_DROPDOWN; - break; - - } - - button.dwData = (IntPtr)0; - button.iString = stringIndex; - this.commandId = commandId; - button.idCommand = commandId; - - return button; - } - - /// - /// Returns a TBBUTTONINFO object that represents this ToolBarButton. - /// - internal NativeMethods.TBBUTTONINFO GetTBBUTTONINFO(bool updateText, int newCommandId) - { - NativeMethods.TBBUTTONINFO button = new NativeMethods.TBBUTTONINFO - { - cbSize = Marshal.SizeOf(), - dwMask = NativeMethods.TBIF_IMAGE - | NativeMethods.TBIF_STATE | NativeMethods.TBIF_STYLE - }; - - // Older platforms interpret null strings as empty, which forces the button to - // leave space for text. - // The only workaround is to avoid having comctl update the text. - if (updateText) - { - button.dwMask |= NativeMethods.TBIF_TEXT; - } - - button.iImage = ImageIndexer.ActualIndex; - - if (newCommandId != commandId) - { - commandId = newCommandId; - button.idCommand = newCommandId; - button.dwMask |= NativeMethods.TBIF_COMMAND; - } - - // set up the state of the button - // - button.fsState = 0; - if (enabled) - { - button.fsState |= NativeMethods.TBSTATE_ENABLED; - } - - if (partialPush && style == ToolBarButtonStyle.ToggleButton) - { - button.fsState |= NativeMethods.TBSTATE_INDETERMINATE; - } - - if (pushed) - { - button.fsState |= NativeMethods.TBSTATE_CHECKED; - } - - if (!visible) - { - button.fsState |= NativeMethods.TBSTATE_HIDDEN; - } - - // set the button style - // - switch (style) - { - case ToolBarButtonStyle.PushButton: - button.fsStyle = NativeMethods.TBSTYLE_BUTTON; - break; - case ToolBarButtonStyle.ToggleButton: - button.fsStyle = NativeMethods.TBSTYLE_CHECK; - break; - case ToolBarButtonStyle.Separator: - button.fsStyle = NativeMethods.TBSTYLE_SEP; - break; - } - - if (text == null) - { - button.pszText = Marshal.StringToHGlobalAuto("\0\0"); - } - else - { - string textValue = text; - PrefixAmpersands(ref textValue); - button.pszText = Marshal.StringToHGlobalAuto(textValue); - } - - return button; - } - - private void PrefixAmpersands(ref string value) - { - // Due to a comctl32 problem, ampersands underline the next letter in the - // text string, but the accelerators don't work. - // So in this function, we prefix ampersands with another ampersand - // so that they actually appear as ampersands. - // - - // Sanity check parameter - // - if (value == null || value.Length == 0) - { - return; - } - - // If there are no ampersands, we don't need to do anything here - // - if (value.IndexOf('&') < 0) - { - return; - } - - // Insert extra ampersands - // - StringBuilder newString = new StringBuilder(); - for (int i = 0; i < value.Length; ++i) - { - if (value[i] == '&') - { - if (i < value.Length - 1 && value[i + 1] == '&') - { - ++i; // Skip the second ampersand - } - newString.Append("&&"); - } - else - { - newString.Append(value[i]); - } - } - - value = newString.ToString(); - } - - public override string ToString() - { - return "ToolBarButton: " + Text + ", Style: " + Style.ToString("G"); - } - - /// - /// When a button property changes and the parent control is created, - /// we need to make sure it gets the new button information. - /// If Text was changed, call the next overload. - /// - internal void UpdateButton(bool recreate) - { - UpdateButton(recreate, false, true); - } - - /// - /// When a button property changes and the parent control is created, - /// we need to make sure it gets the new button information. - /// - private void UpdateButton(bool recreate, bool updateText, bool updatePushedState) - { - // It looks like ToolBarButtons with a DropDownButton tend to - // lose the DropDownButton very easily - so we need to recreate - // the button each time it changes just to be sure. - // - if (style == ToolBarButtonStyle.DropDownButton && parent != null && parent.DropDownArrows) - { - recreate = true; - } - - // we just need to get the Pushed state : this asks the Button its states and sets - // the private member "pushed" to right value.. - - // this member is used in "InternalSetButton" which calls GetTBBUTTONINFO(bool updateText) - // the GetButtonInfo method uses the "pushed" variable.. - - //rather than setting it ourselves .... we asks the button to set it for us.. - if (updatePushedState && parent != null && parent.IsHandleCreated) - { - GetPushedState(); - } - if (parent != null) - { - int index = FindButtonIndex(); - if (index != -1) - { - parent.InternalSetButton(index, this, recreate, updateText); - } - } - } - } -} diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolBarButtonClickEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolBarButtonClickEventArgs.cs deleted file mode 100644 index 0256dfba763..00000000000 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolBarButtonClickEventArgs.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System.Windows.Forms -{ - /// - /// Provides data for the - /// event. - /// - public class ToolBarButtonClickEventArgs : EventArgs - { - /// - /// Initializes a new instance of the - /// class. - /// - public ToolBarButtonClickEventArgs(ToolBarButton button) - { - Button = button; - } - - /// - /// Specifies the - /// that was clicked. - /// - public ToolBarButton Button { get; set; } - } -} diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolBarButtonClickEventHandler.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolBarButtonClickEventHandler.cs deleted file mode 100644 index e41f8559afa..00000000000 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolBarButtonClickEventHandler.cs +++ /dev/null @@ -1,12 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System.Windows.Forms -{ - /// - /// Represents a method that will handle the - /// event of a . - /// - public delegate void ToolBarButtonClickEventHandler(object sender, ToolBarButtonClickEventArgs e); -} diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolBarButtonStyle.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolBarButtonStyle.cs deleted file mode 100644 index ea4872efb30..00000000000 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolBarButtonStyle.cs +++ /dev/null @@ -1,33 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System.Windows.Forms -{ - public enum ToolBarButtonStyle - { - /// - /// A standard, three-dimensional button. - /// - PushButton = 1, - - /// - /// A toggle button that appears sunken when clicked and retains the - /// sunken appearance until clicked again. - /// - ToggleButton = 2, - - /// - /// A space or line between toolbar buttons. The appearance depends on - /// the value of the - /// property. - /// - Separator = 3, - - /// - /// A drop down control that displays a menu or other window when - /// clicked. - /// - DropDownButton = 4, - } -} diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolBarTextAlign.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolBarTextAlign.cs deleted file mode 100644 index 72dcf8156c9..00000000000 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolBarTextAlign.cs +++ /dev/null @@ -1,22 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System.Windows.Forms -{ - /// - /// Specifies the alignment of text on the toolbar button control. - /// - public enum ToolBarTextAlign - { - /// - /// The text is aligned underneath the toolbar button image. - /// - Underneath = 0, - - /// - /// The text is aligned to the right of the toolbar button image. - /// - Right = 1, - } -} diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDown.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDown.cs index b3b6d6c41b6..8b545988434 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDown.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDown.cs @@ -240,22 +240,6 @@ public new bool CanOverflow remove => base.ChangeUICues -= value; } - [Browsable(false)] - [EditorBrowsable(EditorBrowsableState.Never)] - public new ContextMenu ContextMenu - { - get { return base.ContextMenu; } - set { base.ContextMenu = value; } - } - - [Browsable(false)] - [EditorBrowsable(EditorBrowsableState.Never)] - public new event EventHandler ContextMenuChanged - { - add => base.ContextMenuChanged += value; - remove => base.ContextMenuChanged -= value; - } - [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public new ContextMenuStrip ContextMenuStrip @@ -273,11 +257,11 @@ public new ContextMenuStrip ContextMenuStrip } /// - /// This is called when creating a window. Inheriting classes can overide + /// This is called when creating a window. Inheriting classes can overide /// this to add extra functionality, but should not forget to first call /// base.CreateParams() to make sure the control continues to work /// correctly. - /// + ///
protected override CreateParams CreateParams { get diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolTip.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolTip.cs index 283c9ad5909..4339403935b 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolTip.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolTip.cs @@ -659,11 +659,6 @@ private void CheckNativeToolTip(Control associatedControl) treeView.SetToolTip(this, GetToolTip(associatedControl)); } - if (associatedControl is ToolBar toolBar) - { - toolBar.SetToolTip(this); - } - if (associatedControl is TabControl tabControl && tabControl.ShowToolTips) { tabControl.SetToolTip(this, GetToolTip(associatedControl)); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TreeNode.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TreeNode.cs index 8b8a840b514..fdfd26b67c0 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TreeNode.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TreeNode.cs @@ -52,7 +52,6 @@ public class TreeNode : MarshalByRefObject, ICloneable, ISerializable private TreeNodeImageIndexer stateImageIndexer; private string toolTipText = string.Empty; - private ContextMenu contextMenu = null; private ContextMenuStrip contextMenuStrip = null; internal bool nodesCleared = false; @@ -423,23 +422,6 @@ public bool Checked /// The contextMenu associated with this tree node. The contextMenu /// will be shown when the user right clicks the mouse on the control. ///
- [ - SRCategory(nameof(SR.CatBehavior)), - DefaultValue(null), - SRDescription(nameof(SR.ControlContextMenuDescr)) - ] - public virtual ContextMenu ContextMenu - { - get - { - return contextMenu; - } - set - { - contextMenu = value; - } - } - [ SRCategory(nameof(SR.CatBehavior)), DefaultValue(null), @@ -1461,7 +1443,6 @@ public virtual object Clone() node.StateImageIndexer.Index = StateImageIndexer.Index; node.ToolTipText = toolTipText; - node.ContextMenu = contextMenu; node.ContextMenuStrip = contextMenuStrip; // only set the key if it's set to something useful diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TreeView.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TreeView.cs index a4e18f708a5..51aeccc9f6c 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TreeView.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TreeView.cs @@ -995,8 +995,8 @@ public TreeNodeCollection Nodes } /// - /// Indicates the drawing mode for the tree view. - /// + /// Indicates the drawing mode for the tree view. + /// [ SRCategory(nameof(SR.CatBehavior)), DefaultValue(TreeViewDrawMode.Normal), @@ -1711,13 +1711,6 @@ protected override void Dispose(bool disposing) { if (disposing) { - - foreach (TreeNode node in Nodes) - { - node.ContextMenu = null; - } - - // lock (this) { DetachImageListHandlers(); @@ -3115,7 +3108,7 @@ private unsafe void WmNotify(ref Message m) if (nmtv->nmhdr.code == NativeMethods.NM_RCLICK) { TreeNode treeNode = NodeFromHandle(hnode); - if (treeNode != null && (treeNode.ContextMenu != null || treeNode.ContextMenuStrip != null)) + if (treeNode != null && treeNode.ContextMenuStrip != null) { ShowContextMenu(treeNode); } @@ -3151,41 +3144,14 @@ private unsafe void WmNotify(ref Message m) /// private void ShowContextMenu(TreeNode treeNode) { - if (treeNode.ContextMenu != null || treeNode.ContextMenuStrip != null) + if (treeNode.ContextMenuStrip != null) { - - ContextMenu contextMenu = treeNode.ContextMenu; ContextMenuStrip menu = treeNode.ContextMenuStrip; - if (contextMenu != null) - { - UnsafeNativeMethods.GetCursorPos(out Point pt); - - // Summary: the current window must be made the foreground window - // before calling TrackPopupMenuEx, and a task switch must be - // forced after the call. - - UnsafeNativeMethods.SetForegroundWindow(new HandleRef(this, Handle)); - - contextMenu.OnPopup(EventArgs.Empty); - - SafeNativeMethods.TrackPopupMenuEx(new HandleRef(contextMenu, contextMenu.Handle), - NativeMethods.TPM_VERTICAL, - pt.X, - pt.Y, - new HandleRef(this, Handle), - null); - - // Force task switch (see above) - UnsafeNativeMethods.PostMessage(new HandleRef(this, Handle), WindowMessages.WM_NULL, IntPtr.Zero, IntPtr.Zero); - } // Need to send TVM_SELECTITEM to highlight the node while the contextMenuStrip is being shown. - else if (menu != null) - { - UnsafeNativeMethods.PostMessage(new HandleRef(this, Handle), NativeMethods.TVM_SELECTITEM, NativeMethods.TVGN_DROPHILITE, treeNode.Handle); - menu.ShowInternal(this, PointToClient(MousePosition),/*keyboardActivated*/false); - menu.Closing += new ToolStripDropDownClosingEventHandler(ContextMenuStripClosing); - } + UnsafeNativeMethods.PostMessage(new HandleRef(this, Handle), NativeMethods.TVM_SELECTITEM, NativeMethods.TVGN_DROPHILITE, treeNode.Handle); + menu.ShowInternal(this, PointToClient(MousePosition),/*keyboardActivated*/false); + menu.Closing += new ToolStripDropDownClosingEventHandler(ContextMenuStripClosing); } } @@ -3469,22 +3435,15 @@ protected override void WndProc(ref Message m) { // this is the Shift + F10 Case.... TreeNode treeNode = SelectedNode; - if (treeNode != null && (treeNode.ContextMenu != null || treeNode.ContextMenuStrip != null)) + if (treeNode != null && treeNode.ContextMenuStrip != null) { Point client; client = new Point(treeNode.Bounds.X, treeNode.Bounds.Y + treeNode.Bounds.Height / 2); // VisualStudio7 # 156, only show the context menu when clicked in the client area - if (ClientRectangle.Contains(client)) + if (ClientRectangle.Contains(client) && treeNode.ContextMenuStrip != null) { - if (treeNode.ContextMenu != null) - { - treeNode.ContextMenu.Show(this, client); - } - else if (treeNode.ContextMenuStrip != null) - { - bool keyboardActivated = (unchecked((int)(long)m.LParam) == -1); - treeNode.ContextMenuStrip.ShowInternal(this, client, keyboardActivated); - } + bool keyboardActivated = (unchecked((int)(long)m.LParam) == -1); + treeNode.ContextMenuStrip.ShowInternal(this, client, keyboardActivated); } } else diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/UpDownBase.cs b/src/System.Windows.Forms/src/System/Windows/Forms/UpDownBase.cs index 42345a1261b..5885bdd3c40 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/UpDownBase.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/UpDownBase.cs @@ -283,19 +283,6 @@ protected bool ChangingText } } - public override ContextMenu ContextMenu - { - get - { - return base.ContextMenu; - } - set - { - base.ContextMenu = value; - upDownEdit.ContextMenu = value; - } - } - public override ContextMenuStrip ContextMenuStrip { get @@ -1298,7 +1285,7 @@ protected override void OnMouseUp(MouseEventArgs e) internal override void WmContextMenu(ref Message m) { // Want to make the SourceControl to be the UpDownBase, not the Edit. - if (ContextMenu == null && ContextMenuStrip != null) + if (ContextMenuStrip != null) { WmContextMenu(ref m, parent); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowser.cs b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowser.cs index efc23f0153a..5c700919ef7 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowser.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowser.cs @@ -8,9 +8,9 @@ using System.IO; using System.Runtime.InteropServices; using System.Text; -using IComDataObject = System.Runtime.InteropServices.ComTypes.IDataObject; using static Interop; using static Interop.Mshtml; +using IComDataObject = System.Runtime.InteropServices.ComTypes.IDataObject; namespace System.Windows.Forms { @@ -70,10 +70,10 @@ public WebBrowser() : base("8856f961-340a-11d0-a96b-00c04fd705a2") // /// - /// Specifies whether the WebBrowser control may navigate to another page once + /// Specifies whether the WebBrowser control may navigate to another page once /// it has been loaded. NOTE: it will always be able to navigate before being loaded. /// "Loaded" here means setting Url, DocumentText, or DocumentStream. - /// + /// [SRDescription(nameof(SR.WebBrowserAllowNavigationDescr)), SRCategory(nameof(SR.CatBehavior)), DefaultValue(true)] public bool AllowNavigation @@ -93,12 +93,12 @@ public bool AllowNavigation } /// - /// Specifies whether the WebBrowser control will receive drop notifcations. + /// Specifies whether the WebBrowser control will receive drop notifcations. /// Maps to IWebBrowser2:RegisterAsDropTarget. /// Note that this does not mean that the WebBrowser control integrates with /// Windows Forms drag/drop i.e. the DragDrop event does not fire. It does /// control whether you can drag new documents into the browser control. - /// + /// [SRDescription(nameof(SR.WebBrowserAllowWebBrowserDropDescr)), SRCategory(nameof(SR.CatBehavior)), DefaultValue(true)] public bool AllowWebBrowserDrop @@ -120,9 +120,9 @@ public bool AllowWebBrowserDrop } /// - /// Specifies whether the browser control shows script errors in dialogs or not. + /// Specifies whether the browser control shows script errors in dialogs or not. /// Maps to IWebBrowser2:Silent. - /// + /// [SRDescription(nameof(SR.WebBrowserScriptErrorsSuppressedDescr)), SRCategory(nameof(SR.CatBehavior)), DefaultValue(false)] public bool ScriptErrorsSuppressed @@ -141,9 +141,9 @@ public bool ScriptErrorsSuppressed } /// - /// Specifies whether the browser control Shortcuts are enabled. + /// Specifies whether the browser control Shortcuts are enabled. /// Maps to IDocHostUIHandler:TranslateAccelerator event. - /// + /// [SRDescription(nameof(SR.WebBrowserWebBrowserShortcutsEnabledDescr)), SRCategory(nameof(SR.CatBehavior)), DefaultValue(true)] public bool WebBrowserShortcutsEnabled @@ -159,10 +159,10 @@ public bool WebBrowserShortcutsEnabled } /// - /// If true, there is navigation history such that calling GoBack() will succeed. + /// If true, there is navigation history such that calling GoBack() will succeed. /// Defaults to false. After that it's value is kept up to date by hooking the /// DWebBrowserEvents2:CommandStateChange. - /// + /// [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool CanGoBack { @@ -193,10 +193,10 @@ internal bool CanGoBackInternal } /// - /// If true, there is navigation history such that calling GoForward() will succeed. + /// If true, there is navigation history such that calling GoForward() will succeed. /// Defaults to false. After that it's value is kept up to date by hooking the /// DWebBrowserEvents2:CommandStateChange. - /// + /// [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool CanGoForward { @@ -227,9 +227,9 @@ internal bool CanGoForwardInternal } /// - /// The HtmlDocument for page hosted in the html page. If no page is loaded, it returns null. + /// The HtmlDocument for page hosted in the html page. If no page is loaded, it returns null. /// Maps to IWebBrowser2:Document. - /// + /// [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public HtmlDocument Document { @@ -266,9 +266,9 @@ public HtmlDocument Document } /// - /// Get/sets the stream for the html document. + /// Get/sets the stream for the html document. /// Uses the IPersisteStreamInit interface on the HtmlDocument to set/retrieve the html stream. - /// + /// [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Stream DocumentStream { @@ -313,8 +313,8 @@ public Stream DocumentStream } /// - /// Sets/sets the text of the contained html page. - /// + /// Sets/sets the text of the contained html page. + /// [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string DocumentText { @@ -347,9 +347,9 @@ public string DocumentText } /// - /// The title of the html page currently loaded. If none are loaded, returns empty string. + /// The title of the html page currently loaded. If none are loaded, returns empty string. /// Maps to IWebBrowser2:LocationName. - /// + /// [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string DocumentTitle { @@ -380,9 +380,9 @@ public string DocumentTitle } /// - /// A string containing the MIME type of the document hosted in the browser control. + /// A string containing the MIME type of the document hosted in the browser control. /// If none are loaded, returns empty string. Maps to IHTMLDocument2:mimeType. - /// + /// [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string DocumentType { @@ -408,9 +408,9 @@ public string DocumentType } /// - /// Initially set to WebBrowserEncryptionLevel.Insecure. + /// Initially set to WebBrowserEncryptionLevel.Insecure. /// After that it's kept up to date by hooking the DWebBrowserEvents2:SetSecureLockIcon. - /// + /// [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public WebBrowserEncryptionLevel EncryptionLevel { @@ -425,8 +425,8 @@ public WebBrowserEncryptionLevel EncryptionLevel } /// - /// True if the browser is engaged in navigation or download. Maps to IWebBrowser2:Busy. - /// + /// True if the browser is engaged in navigation or download. Maps to IWebBrowser2:Busy. + /// [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool IsBusy { @@ -444,8 +444,8 @@ public bool IsBusy } /// - /// Gets the offline state of the browser control. Maps to IWebBrowser2:Offline. - /// + /// Gets the offline state of the browser control. Maps to IWebBrowser2:Offline. + /// [SRDescription(nameof(SR.WebBrowserIsOfflineDescr)), Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool IsOffline { @@ -456,12 +456,12 @@ public bool IsOffline } /// - /// Indicates whether to use the WebBrowser context menu. + /// Indicates whether to use the WebBrowser context menu. /// It's technically possible to have both the WebBrowser & Windows Forms context /// menu enabled, but making this property effect the behavior of the Windows Form /// context menu does not lead to a clean OM. Maps to sinking the /// IDocHostUIHandler:ShowContextMenu - /// + /// [SRDescription(nameof(SR.WebBrowserIsWebBrowserContextMenuEnabledDescr)), SRCategory(nameof(SR.CatBehavior)), DefaultValue(true)] public bool IsWebBrowserContextMenuEnabled @@ -477,11 +477,11 @@ public bool IsWebBrowserContextMenuEnabled } /// - /// Allows the host application to provide an object that the contained html + /// Allows the host application to provide an object that the contained html /// pages can access programatically in script. The object specified here /// will be accessible in script as the "window.external" object via IDispatch /// COM interop. Maps to an implementation of the IDocUIHandler.GetExternal event. - /// + /// [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public object ObjectForScripting { @@ -529,9 +529,9 @@ public new Padding Padding } /// - /// Gets the ReadyState of the browser control. (ex.. document loading vs. load complete). + /// Gets the ReadyState of the browser control. (ex.. document loading vs. load complete). /// Maps to IWebBrowser2:ReadyState. - /// + /// [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public WebBrowserReadyState ReadyState { @@ -549,11 +549,11 @@ public WebBrowserReadyState ReadyState } /// - /// The text that would be displayed in the IE status bar. + /// The text that would be displayed in the IE status bar. /// There is no direct WebBrowser property that maps to this. This property is /// initially an empty string. After that the value is kept up to date via the /// DWebBrowserEvents2:StatusTextChange event. - /// + /// [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public virtual string StatusText { @@ -568,11 +568,11 @@ public virtual string StatusText } /// - /// The url of the HtmlDocument for page hosted in the html page. + /// The url of the HtmlDocument for page hosted in the html page. /// Get Maps to IWebBrowser2:LocationUrl. Set is the equivalent of calling Navigate(Url). /// Note this means that setting the Url property & then reading it immediately may not /// return the result that you just set (since the get always returns the url you are currently at). - /// + /// [ SRDescription(nameof(SR.WebBrowserUrlDescr)), Bindable(true), @@ -610,9 +610,9 @@ public Uri Url } /// - /// Returns the version property of IE. + /// Returns the version property of IE. /// Determined by reading the file version of mshtml.dll in the %system% directory. - /// + /// [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Version Version { @@ -629,11 +629,11 @@ public Version Version // /// - /// Navigates the browser to the previous page in the navigation history list. + /// Navigates the browser to the previous page in the navigation history list. /// Maps to IWebBrowser2:GoBack. /// Returns true if the operation succeeds, else returns false. It will return /// false if there is no page in the navigation history to go back to. - /// + /// public bool GoBack() { bool retVal = true; @@ -653,11 +653,11 @@ public bool GoBack() } /// - /// Navigates the browser to the next page in the navigation history list. + /// Navigates the browser to the next page in the navigation history list. /// Maps to IWebBrowser2:GoForward. /// Returns true if the operation succeeds, else returns false. It will return /// false if there is no page in the navigation history to go forward to. - /// + /// public bool GoForward() { bool retVal = true; @@ -677,32 +677,32 @@ public bool GoForward() } /// - /// Navigates the browser to user's homepage. Maps to IWebBrowser2:GoHome. - /// + /// Navigates the browser to user's homepage. Maps to IWebBrowser2:GoHome. + /// public void GoHome() { AxIWebBrowser2.GoHome(); } /// - /// Navigates the browser to user's default search page. Maps to IWebBrowser2:GoSearch. - /// + /// Navigates the browser to user's default search page. Maps to IWebBrowser2:GoSearch. + /// public void GoSearch() { AxIWebBrowser2.GoSearch(); } /// - /// Navigates to the specified Uri's AbsolutePath - /// + /// Navigates to the specified Uri's AbsolutePath + /// public void Navigate(Uri url) { Url = url; // Does null check in PerformNavigate2 } /// - /// String overload for Navigate(Uri) - /// + /// String overload for Navigate(Uri) + /// /// Note: We intentionally have a string overload (apparently Mort wants one). We don't have /// string overloads call Uri overloads because that breaks Uris that aren't fully qualified /// (things like "www.microsoft.com") that the underlying objects support and we don't want to @@ -713,18 +713,18 @@ public void Navigate(string urlString) } /// - /// Navigates the specified frame to the specified URL. + /// Navigates the specified frame to the specified URL. /// If the frame name is invalid, it opens a new window (not ideal, but it's the current behavior). /// Maps to IWebBrowser2:Navigate. - /// + /// public void Navigate(Uri url, string targetFrameName) { PerformNavigateHelper(ReadyNavigateToUrl(url), false, targetFrameName, null, null); } /// - /// String overload for Navigate(Uri, string) - /// + /// String overload for Navigate(Uri, string) + /// /// Note: We intentionally have a string overload (apparently Mort wants one). We don't have /// string overloads call Uri overloads because that breaks Uris that aren't fully qualified /// (things like "www.microsoft.com") that the underlying objects support and we don't want to @@ -735,16 +735,16 @@ public void Navigate(string urlString, string targetFrameName) } /// - /// Opens a new window if newWindow is true, navigating it to the specified URL. Maps to IWebBrowser2:Navigate. - /// + /// Opens a new window if newWindow is true, navigating it to the specified URL. Maps to IWebBrowser2:Navigate. + /// public void Navigate(Uri url, bool newWindow) { PerformNavigateHelper(ReadyNavigateToUrl(url), newWindow, null, null, null); } /// - /// String overload for Navigate(Uri, bool) - /// + /// String overload for Navigate(Uri, bool) + /// /// Note: We intentionally have a string overload (apparently Mort wants one). We don't have /// string overloads call Uri overloads because that breaks Uris that aren't fully qualified /// (things like "www.microsoft.com") that the underlying objects support and we don't want to @@ -755,16 +755,16 @@ public void Navigate(string urlString, bool newWindow) } /// - /// Navigates to the specified Uri's AbsolutePath with specified args - /// + /// Navigates to the specified Uri's AbsolutePath with specified args + /// public void Navigate(Uri url, string targetFrameName, byte[] postData, string additionalHeaders) { PerformNavigateHelper(ReadyNavigateToUrl(url), false, targetFrameName, postData, additionalHeaders); } /// - /// String overload for Navigate(Uri, string, byte[], string) - /// + /// String overload for Navigate(Uri, string, byte[], string) + /// /// Note: We intentionally have a string overload (apparently Mort wants one). We don't have /// string overloads call Uri overloads because that breaks Uris that aren't fully qualified /// (things like "www.microsoft.com") that the underlying objects support and we don't want to @@ -775,9 +775,9 @@ public void Navigate(string urlString, string targetFrameName, byte[] postData, } /// - /// Prints the html document to the default printer w/ no print dialog. + /// Prints the html document to the default printer w/ no print dialog. /// Maps to IWebBrowser2:ExecWB w/ IDM_PRINT flag & LECMDEXECOPT_DONTPROMPTUSER. - /// + /// public void Print() { object nullObjectArray = null; @@ -795,8 +795,8 @@ public void Print() } /// - /// Refreshes the current page. Maps to IWebBrowser2:Refresh. - /// + /// Refreshes the current page. Maps to IWebBrowser2:Refresh. + /// public override void Refresh() { try @@ -822,10 +822,10 @@ public override void Refresh() } /// - /// Refreshes the current page w/ the specified refresh option. The refresh option + /// Refreshes the current page w/ the specified refresh option. The refresh option /// controls how much is loaded out of the browser cache vs. rechecking the server for. /// Maps to IWebBrowser2:Refresh2 - /// + /// public void Refresh(WebBrowserRefreshOption opt) { object level = (object)opt; @@ -852,8 +852,8 @@ public void Refresh(WebBrowserRefreshOption opt) } /// - /// Enables/disables the webbrowser's scrollbars. - /// + /// Enables/disables the webbrowser's scrollbars. + /// [SRDescription(nameof(SR.WebBrowserScrollBarsEnabledDescr)), SRCategory(nameof(SR.CatBehavior)), DefaultValue(true)] public bool ScrollBarsEnabled @@ -873,9 +873,9 @@ public bool ScrollBarsEnabled } /// - /// Opens the IE page setup dialog for the current page. + /// Opens the IE page setup dialog for the current page. /// Maps to IWebBrowser2:ExecWebBrowser w/ IDM_PAGESETUP flag & LECMDEXECOPT_PROMPTUSER. - /// + /// public void ShowPageSetupDialog() { object nullObjectArray = null; @@ -893,9 +893,9 @@ public void ShowPageSetupDialog() } /// - /// Opens the IE print dialog. + /// Opens the IE print dialog. /// Maps to IWebBrowser2:ExecWebBrowser w/ IDM_PRINT flag & OLECMDEXECOPT_PROMPTUSER. - /// + /// public void ShowPrintDialog() { object nullObjectArray = null; @@ -914,8 +914,8 @@ public void ShowPrintDialog() } /// - /// Opens the IE print preview dialog. Maps to IWebBrowser2:ExecWebBrowser w/ IDM_PRINTPREVIEW flag. - /// + /// Opens the IE print preview dialog. Maps to IWebBrowser2:ExecWebBrowser w/ IDM_PRINTPREVIEW flag. + /// public void ShowPrintPreviewDialog() { object nullObjectArray = null; @@ -934,9 +934,9 @@ public void ShowPrintPreviewDialog() } /// - /// Opens the properties dialog for the current html page. + /// Opens the properties dialog for the current html page. /// Maps to IWebBrowser2:ExecWebBrowser w/ IDM_PROPERTIES flag & LECMDEXECOPT_PROMPTUSER. - /// + /// public void ShowPropertiesDialog() { object nullObjectArray = null; @@ -955,9 +955,9 @@ public void ShowPropertiesDialog() } /// - /// Opens the IE File-Save dialog. + /// Opens the IE File-Save dialog. /// Maps to IWebBrowser2:ExecWebBrowser w/ IDM_SAVEAS flag & LECMDEXECOPT_PROMPTUSER. - /// + /// public void ShowSaveAsDialog() { object nullObjectArray = null; @@ -976,8 +976,8 @@ public void ShowSaveAsDialog() } /// - /// Stops the current navigation. Maps to IWebBrowser2:Stop. - /// + /// Stops the current navigation. Maps to IWebBrowser2:Stop. + /// public void Stop() { try @@ -997,78 +997,78 @@ public void Stop() // Public events: // /// - /// Occurs when the IE back button would change from enabled to disabled or vice versa. + /// Occurs when the IE back button would change from enabled to disabled or vice versa. /// Maps to DWebBrowserEvents2:CommandStateChange w/ CSC_NAVIGATEBACK. - /// + /// [Browsable(false), SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.WebBrowserCanGoBackChangedDescr))] public event EventHandler CanGoBackChanged; /// - /// Occurs when the IE forward button would change from enabled to disabled or vice versa. + /// Occurs when the IE forward button would change from enabled to disabled or vice versa. /// Maps to DWebBrowserEvents2:CommandStateChange w/ CSC_NAVIGATEFORWARD. - /// + /// [Browsable(false), SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.WebBrowserCanGoForwardChangedDescr))] public event EventHandler CanGoForwardChanged; /// - /// Occurs when the document hosted in the web browser control is fully loaded. + /// Occurs when the document hosted in the web browser control is fully loaded. /// This is conceptially similar to Form.Load(). You need to wait until this event fires /// before doing anything that manipulates the html page, ex. reading the Document /// property of the webbrowser control. Maps to DWebBrowserEvents2:DocumentComplete. - /// + /// [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.WebBrowserDocumentCompletedDescr))] public event WebBrowserDocumentCompletedEventHandler DocumentCompleted; /// - /// Occurs whenever the title text changes. The Title is the html page title + /// Occurs whenever the title text changes. The Title is the html page title /// or the file path/url if not title is available. This is the text you see as /// the title of the IE window preceeding "Microsoft Internet Explorer". /// Maps to DWebBrowserEvents2:TitleChange. - /// + /// [Browsable(false), SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.WebBrowserDocumentTitleChangedDescr))] public event EventHandler DocumentTitleChanged; /// - /// Occurs whenever encryption level changes. + /// Occurs whenever encryption level changes. /// Can be used to set a custom security lock icon similar to what IE shows when /// you go to an https site. Maps to DWebBrowserEvents2:SetSecureLockIcon. - /// + /// [Browsable(false), SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.WebBrowserEncryptionLevelChangedDescr))] public event EventHandler EncryptionLevelChanged; /// - /// Occurs when a file download occurs. + /// Occurs when a file download occurs. /// Can be used to cancel file downloads. Maps to DWebBrowserEvents2:FileDownload. - /// + /// [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.WebBrowserFileDownloadDescr))] public event EventHandler FileDownload; /// - /// Occurs after browser control navigation occurs. + /// Occurs after browser control navigation occurs. /// Fires after browser navigation is complete. Maps to DWebBrowserEvents2:NavigateComplete. - /// + /// [SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.WebBrowserNavigatedDescr))] public event WebBrowserNavigatedEventHandler Navigated; /// - /// Occurs before browser control navigation occurs. + /// Occurs before browser control navigation occurs. /// Fires before browser navigation occurs. Allows navigation to be canceled if /// NavigatingEventArgs.Cancel is set to false. Maps to DWebBrowserEvents2:BeforeNavigate2. - /// + /// [SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.WebBrowserNavigatingDescr))] public event WebBrowserNavigatingEventHandler Navigating; /// - /// Occurs when a new browser window is created. + /// Occurs when a new browser window is created. /// Can be used to cancel the creation of the new browser window. Maps to DWebBrowserEvents2:NewWindow2. - /// + /// [SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.WebBrowserNewWindowDescr))] public event CancelEventHandler NewWindow; /// - /// Occurs when an update to the progress of a download occurs. + /// Occurs when an update to the progress of a download occurs. /// Fires whenever the browser control has updated info on the download. Can be /// used to provide a download status bar and display the number of bytes downloaded. /// Maps to DWebBrowserEvents2:ProgressChange. - /// + /// [SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.WebBrowserProgressChangedDescr))] public event WebBrowserProgressChangedEventHandler ProgressChanged; /// - /// Occurs whenever the status text changes. + /// Occurs whenever the status text changes. /// Can be used to keep a status bar populated with uptodate text. /// Maps to DWebBrowserEvents2:StatusTextChange. - /// + /// [Browsable(false), SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.WebBrowserStatusTextChangedDescr))] public event EventHandler StatusTextChanged; @@ -1113,8 +1113,8 @@ protected override void Dispose(bool disposing) } /// - /// Overrides the default size property of Control to specify a bigger default size of 250 x 250. - /// + /// Overrides the default size property of Control to specify a bigger default size of 250 x 250. + /// protected override Size DefaultSize { get @@ -1124,32 +1124,32 @@ protected override Size DefaultSize } /// - /// Retrieves IWebBrowser2 from the native object. Overriding classes should first call base.AttachInterfaces. - /// + /// Retrieves IWebBrowser2 from the native object. Overriding classes should first call base.AttachInterfaces. + /// protected override void AttachInterfaces(object nativeActiveXObject) { axIWebBrowser2 = (UnsafeNativeMethods.IWebBrowser2)nativeActiveXObject; } /// - /// Discards the IWebBrowser2 reference. Overriding classes should call base.DetachInterfaces. - /// + /// Discards the IWebBrowser2 reference. Overriding classes should call base.DetachInterfaces. + /// protected override void DetachInterfaces() { axIWebBrowser2 = null; } /// - /// Returns a WebBrowserSite object. - /// + /// Returns a WebBrowserSite object. + /// protected override WebBrowserSiteBase CreateWebBrowserSiteBase() { return new WebBrowserSite(this); } /// - /// Attaches to the DWebBrowserEvents2 connection point. - /// + /// Attaches to the DWebBrowserEvents2 connection point. + /// protected override void CreateSink() { object ax = activeXInstance; @@ -1165,8 +1165,8 @@ protected override void CreateSink() } /// - /// Releases the DWebBrowserEvents2 connection point. - /// + /// Releases the DWebBrowserEvents2 connection point. + /// protected override void DetachSink() { //If we have a cookie get rid of it @@ -1423,9 +1423,7 @@ private bool ShouldSerializeUrl() private bool ShowContextMenu(int x, int y) { ContextMenuStrip contextMenuStrip = ContextMenuStrip; - ContextMenu contextMenu = contextMenuStrip != null ? null : ContextMenu; - - if (contextMenuStrip != null || contextMenu != null) + if (contextMenuStrip != null) { Point client; bool keyboardActivated = false; @@ -1447,10 +1445,6 @@ private bool ShowContextMenu(int x, int y) { contextMenuStrip.ShowInternal(this, client, keyboardActivated); } - else if (contextMenu != null) - { - contextMenu.Show(this, client); - } return true; } @@ -1513,9 +1507,9 @@ private UnsafeNativeMethods.IWebBrowser2 AxIWebBrowser2 // WebBrowserSite class: // /// - /// Provides a default WebBrowserSite implementation for use in the CreateWebBrowserSite + /// Provides a default WebBrowserSite implementation for use in the CreateWebBrowserSite /// method in the WebBrowser class. - /// + /// [ComVisible(false)] protected class WebBrowserSite : WebBrowserSiteBase, UnsafeNativeMethods.IDocHostUIHandler { diff --git a/src/System.Windows.Forms/tests/UnitTests/AccessibleObjects/DataGridColumnHeaderAccessibleObjectTests.cs b/src/System.Windows.Forms/tests/UnitTests/AccessibleObjects/DataGridColumnHeaderAccessibleObjectTests.cs deleted file mode 100644 index bc224d7f282..00000000000 --- a/src/System.Windows.Forms/tests/UnitTests/AccessibleObjects/DataGridColumnHeaderAccessibleObjectTests.cs +++ /dev/null @@ -1,61 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.ComponentModel; -using System.Drawing; -using WinForms.Common.Tests; -using Xunit; - -namespace System.Windows.Forms.Tests -{ - public class DataGridColumnHeaderAccessibleObjectTests : DataGridColumnStyle - { - [Fact] - public void Ctor_Default() - { - var accessibleObject = new DataGridColumnHeaderAccessibleObject(); - Assert.Equal(AccessibleRole.ColumnHeader, accessibleObject.Role); - } - - protected internal override void Abort(int rowNum) - { - throw new NotImplementedException(); - } - - protected internal override bool Commit(CurrencyManager dataSource, int rowNum) - { - throw new NotImplementedException(); - } - - protected internal override void Edit(CurrencyManager source, int rowNum, Rectangle bounds, bool readOnly, string displayText, bool cellIsVisible) - { - throw new NotImplementedException(); - } - - protected internal override Size GetPreferredSize(Graphics g, object value) - { - throw new NotImplementedException(); - } - - protected internal override int GetMinimumHeight() - { - throw new NotImplementedException(); - } - - protected internal override int GetPreferredHeight(Graphics g, object value) - { - throw new NotImplementedException(); - } - - protected internal override void Paint(Graphics g, Rectangle bounds, CurrencyManager source, int rowNum) - { - throw new NotImplementedException(); - } - - protected internal override void Paint(Graphics g, Rectangle bounds, CurrencyManager source, int rowNum, bool alignToRight) - { - throw new NotImplementedException(); - } - } -} diff --git a/src/System.Windows.Forms/tests/UnitTests/ContextMenuTests.cs b/src/System.Windows.Forms/tests/UnitTests/ContextMenuTests.cs deleted file mode 100644 index 3c2485b2bff..00000000000 --- a/src/System.Windows.Forms/tests/UnitTests/ContextMenuTests.cs +++ /dev/null @@ -1,304 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Collections.Generic; -using System.ComponentModel; -using System.Drawing; -using System.Linq; -using WinForms.Common.Tests; -using Xunit; - -namespace System.Windows.Forms.Tests -{ - public class ContextMenuTests - { - [Fact] - public void ContextMenu_Ctor_Default() - { - var menu = new ContextMenu(); - Assert.Empty(menu.MenuItems); - Assert.False(menu.IsParent); - Assert.Equal(RightToLeft.No, menu.RightToLeft); - Assert.Null(menu.SourceControl); - Assert.Empty(menu.Name); - Assert.Null(menu.Site); - Assert.Null(menu.Container); - Assert.Null(menu.Tag); - } - - public static IEnumerable Ctor_MenuItemArray_TestData() - { - yield return new object[] { null, false }; - yield return new object[] { Array.Empty(), false }; - yield return new object[] { new MenuItem[] { new MenuItem() }, true }; - } - - [Theory] - [MemberData(nameof(Ctor_MenuItemArray_TestData))] - public void ContextMenu_Ctor_MenuItemArray(MenuItem[] items, bool expectedIsParent) - { - var menu = new ContextMenu(items); - Assert.Equal(items ?? Array.Empty(), menu.MenuItems.Cast()); - for (int i = 0; i < (items?.Length ?? 0); i++) - { - Assert.Equal(i, menu.MenuItems[i].Index); - Assert.Equal(menu, menu.MenuItems[i].Parent); - } - Assert.Equal(expectedIsParent, menu.IsParent); - Assert.Equal(RightToLeft.No, menu.RightToLeft); - Assert.Null(menu.SourceControl); - Assert.Empty(menu.Name); - Assert.Null(menu.Site); - Assert.Null(menu.Container); - Assert.Null(menu.Tag); - } - - [Fact] - public void ContextMenu_Ctor_NullItemInMenuItemArray_ThrowsArgumentNullException() - { - Assert.Throws("item", () => new ContextMenu(new MenuItem[] { null })); - } - - [Fact] - public void ContextMenu_SourceControl_GetProcessingKeyMessage_Succes() - { - var control = new Control - { - ContextMenu = new ContextMenu() - }; - - ContextMenu menu = control.ContextMenu; - Assert.Null(menu.SourceControl); - - var message = new Message - { - Msg = 0x0100 // WM_KEYDOWN - }; - control.PreProcessMessage(ref message); - Assert.Same(control, menu.SourceControl); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetRightToLeftTheoryData))] - public void ContextMenu_RightToLeft_SetWithoutSourceControl_GetReturnsExpected(RightToLeft value, RightToLeft expectedValue) - { - var menu = new ContextMenu - { - RightToLeft = value - }; - Assert.Equal(expectedValue, menu.RightToLeft); - } - - [Theory] - [InlineData(RightToLeft.Yes, RightToLeft.Yes)] - [InlineData(RightToLeft.No, RightToLeft.No)] - [InlineData(RightToLeft.Inherit, RightToLeft.Yes)] - public void ContextMenu_RightToLeft_SetWithSourceControl_GetReturnsExpected(RightToLeft value, RightToLeft expectedValue) - { - var control = new Control - { - ContextMenu = new ContextMenu(), - RightToLeft = RightToLeft.Yes - }; - - ContextMenu menu = control.ContextMenu; - var message = new Message - { - Msg = 0x0100 // WM_KEYDOWN - }; - control.PreProcessMessage(ref message); - - menu.RightToLeft = value; - Assert.Equal(expectedValue, menu.RightToLeft); - } - - [Fact] - public void ContextMenu_RightToLeft_SetCreated_GetReturnsExpected() - { - using (var menu = new ContextMenu(new MenuItem[] { new MenuItem("text") })) - { - Assert.NotEqual(IntPtr.Zero, menu.Handle); - menu.RightToLeft = RightToLeft.Yes; - menu.RightToLeft = RightToLeft.No; - Assert.Equal(RightToLeft.No, menu.RightToLeft); - } - } - - [Theory] - [MemberData(nameof(CommonTestHelper.GetEnumTypeTheoryDataInvalid), typeof(RightToLeft), MemberType = typeof(CommonTestHelper))] - public void ContextMenu_RightToLeft_SetInvalid_ThrowsInvalidEnumArgumentException(RightToLeft value) - { - var menu = new ContextMenu(); - Assert.Throws("RightToLeft", () => menu.RightToLeft = value); - } - - public static IEnumerable ProcessCmdKey_TestData() - { - yield return new object[] { new MenuItem { Shortcut = Shortcut.CtrlA }, true, 1, 0 }; - yield return new object[] { new MenuItem { Shortcut = Shortcut.CtrlA, Enabled = false }, false, 0, 0 }; - yield return new object[] { new MenuItem("text", new MenuItem[] { new MenuItem() }) { Shortcut = Shortcut.CtrlA }, true, 0, 1 }; - yield return new object[] { new MenuItem("text", new MenuItem[] { new MenuItem() }) { Shortcut = Shortcut.CtrlA, Enabled = false }, false, 0, 0 }; - } - - [Theory] - [MemberData(nameof(ProcessCmdKey_TestData))] - public void ContextMenu_ProcessCmdKey_HasItemWithShoutcutKey_ReturnsExpected(MenuItem menuItem, bool expectedResult, int expectedOnClickCallCount, int expectedOnPopupCallCount) - { - var control = new Control(); - int onClickCallCount = 0; - menuItem.Click += (sender, e) => - { - onClickCallCount++; - Assert.Same(menuItem, sender); - Assert.Equal(EventArgs.Empty, e); - }; - - int onPopupCallCount = 0; - menuItem.Popup += (sender, e) => - { - onPopupCallCount++; - Assert.Same(menuItem, sender); - Assert.Equal(EventArgs.Empty, e); - }; - - var menu = new ContextMenu(new MenuItem[] { menuItem }); - var message = new Message(); - Assert.Equal(expectedResult, menu.ProcessCmdKey(ref message, Keys.Control | Keys.A, control)); - Assert.Same(control, menu.SourceControl); - Assert.Equal(expectedOnClickCallCount, onClickCallCount); - Assert.Equal(expectedOnPopupCallCount, onPopupCallCount); - } - - [Fact] - public void ContextMenu_Show_ControlPoint_Success() - { - var menu = new ContextMenu(); - var control = new Control - { - Visible = true - }; - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Equal(menu, sender); - callCount++; - }; - menu.Popup += handler; - - Assert.NotEqual(IntPtr.Zero, control.Handle); - menu.Show(control, new Point(1, 2)); - Assert.Equal(1, callCount); - Assert.Same(control, menu.SourceControl); - } - - [Theory] - [MemberData(nameof(CommonTestHelper.GetEnumTypeTheoryData), typeof(LeftRightAlignment), MemberType = typeof(CommonTestHelper))] - [MemberData(nameof(CommonTestHelper.GetEnumTypeTheoryDataInvalid), typeof(LeftRightAlignment), MemberType = typeof(CommonTestHelper))] - public void ContextMenu_Show_ControlPointLeftRightAlignment_Success(LeftRightAlignment alignment) - { - var menu = new ContextMenu(); - var control = new Control - { - Visible = true - }; - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Equal(menu, sender); - callCount++; - }; - menu.Popup += handler; - - Assert.NotEqual(IntPtr.Zero, control.Handle); - menu.Show(control, new Point(1, 2), alignment); - Assert.Equal(1, callCount); - Assert.Same(control, menu.SourceControl); - } - - [Fact] - public void ContextMenu_Show_NullControl_ThrowsArgumentNullException() - { - var menu = new ContextMenu(); - Assert.Throws("control", () => menu.Show(null, new Point(1, 2))); - Assert.Throws("control", () => menu.Show(null, new Point(1, 2), LeftRightAlignment.Left)); - } - - [Fact] - public void ContextMenu_Show_NotVisibleControl_ThrowsArgumentException() - { - var menu = new ContextMenu(); - var control = new Control - { - Visible = false - }; - Assert.NotEqual(IntPtr.Zero, control.Handle); - Assert.Throws("control", () => menu.Show(control, new Point(1, 2))); - Assert.Throws("control", () => menu.Show(control, new Point(1, 2), LeftRightAlignment.Left)); - } - - [Fact] - public void ContextMenu_Show_ControlHasNoHandle_ThrowsArgumentException() - { - var menu = new ContextMenu(); - var control = new Control - { - Visible = true - }; - Assert.Throws("control", () => menu.Show(control, new Point(1, 2))); - Assert.Throws("control", () => menu.Show(control, new Point(1, 2), LeftRightAlignment.Left)); - } - - [Fact] - public void ContextMenu_OnCollapse_Invoke_Success() - { - var menu = new ContextMenu(); - - // No handler. - menu.OnCollapse(null); - - // Handler. - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Equal(menu, sender); - callCount++; - }; - - menu.Collapse += handler; - menu.OnCollapse(null); - Assert.Equal(1, callCount); - - // Should not call if the handler is removed. - menu.Collapse -= handler; - menu.OnCollapse(null); - Assert.Equal(1, callCount); - } - - [Fact] - public void ContextMenu_OnPopup_Invoke_Success() - { - var menu = new ContextMenu(); - - // No handler. - menu.OnPopup(null); - - // Handler. - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Equal(menu, sender); - callCount++; - }; - - menu.Popup += handler; - menu.OnPopup(null); - Assert.Equal(1, callCount); - - // Should not call if the handler is removed. - menu.Popup -= handler; - menu.OnPopup(null); - Assert.Equal(1, callCount); - } - } -} diff --git a/src/System.Windows.Forms/tests/UnitTests/MainMenuTestsTests.cs b/src/System.Windows.Forms/tests/UnitTests/MainMenuTestsTests.cs deleted file mode 100644 index 6c18df30787..00000000000 --- a/src/System.Windows.Forms/tests/UnitTests/MainMenuTestsTests.cs +++ /dev/null @@ -1,232 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Collections.Generic; -using System.ComponentModel; -using System.Drawing; -using System.Linq; -using WinForms.Common.Tests; -using Xunit; - -namespace System.Windows.Forms.Tests -{ - public class MainMenuTestsTests - { - [Fact] - public void MainMenu_Ctor_Default() - { - var menu = new MainMenu(); - Assert.Empty(menu.MenuItems); - Assert.False(menu.IsParent); - Assert.Equal(RightToLeft.Inherit, menu.RightToLeft); - Assert.Null(menu.GetForm()); - Assert.Empty(menu.Name); - Assert.Null(menu.Site); - Assert.Null(menu.Container); - Assert.Null(menu.Tag); - } - - [Fact] - public void MainMenu_Ctor_IContainer() - { - var container = new Container(); - var menu = new MainMenu(container); - Assert.Empty(menu.MenuItems); - Assert.False(menu.IsParent); - Assert.Equal(RightToLeft.Inherit, menu.RightToLeft); - Assert.Null(menu.GetForm()); - Assert.Empty(menu.Name); - Assert.NotNull(menu.Site); - Assert.Equal(container, menu.Container); - Assert.Null(menu.Tag); - } - - [Fact] - public void MainMenu_Ctor_NullContainer_ThrowsArgumentNullException() - { - Assert.Throws("container", () => new MainMenu((IContainer)null)); - } - - public static IEnumerable Ctor_MenuItemArray_TestData() - { - yield return new object[] { null, false }; - yield return new object[] { Array.Empty(), false }; - yield return new object[] { new MenuItem[] { new MenuItem() }, true }; - } - - [Theory] - [MemberData(nameof(Ctor_MenuItemArray_TestData))] - public void MainMenu_Ctor_MenuItemArray(MenuItem[] items, bool expectedIsParent) - { - var menu = new MainMenu(items); - Assert.Equal(items ?? Array.Empty(), menu.MenuItems.Cast()); - for (int i = 0; i < (items?.Length ?? 0); i++) - { - Assert.Equal(i, menu.MenuItems[i].Index); - Assert.Equal(menu, menu.MenuItems[i].Parent); - } - Assert.Equal(expectedIsParent, menu.IsParent); - Assert.Equal(RightToLeft.Inherit, menu.RightToLeft); - Assert.Null(menu.GetForm()); - Assert.Empty(menu.Name); - Assert.Null(menu.Site); - Assert.Null(menu.Container); - Assert.Null(menu.Tag); - } - - [Fact] - public void MainMenu_Ctor_NullItemInMenuItemArray_ThrowsArgumentNullException() - { - Assert.Throws("item", () => new MainMenu(new MenuItem[] { null })); - } - - [Fact] - public void MainMenu_GetForm_AddedToForm_ReturnsExpected() - { - var form = new Form - { - Menu = new MainMenu() - }; - - MainMenu menu = form.Menu; - Assert.Equal(form, menu.GetForm()); - Assert.Equal(form, menu.GetFormUnsafe()); - } - - [Theory] - [MemberData(nameof(CommonTestHelper.GetEnumTypeTheoryData), typeof(RightToLeft), MemberType = typeof(CommonTestHelper))] - public void MainMenu_RightToLeft_SetWithoutForm_GetReturnsExpected(RightToLeft value) - { - var menu = new MainMenu - { - RightToLeft = value - }; - Assert.Equal(value, menu.RightToLeft); - } - - [Theory] - [InlineData(RightToLeft.Yes, RightToLeft.Yes)] - [InlineData(RightToLeft.No, RightToLeft.No)] - [InlineData(RightToLeft.Inherit, RightToLeft.Yes)] - public void MainMenu_RightToLeft_SetWithSourceControl_GetReturnsExpected(RightToLeft value, RightToLeft expectedValue) - { - var form = new Form - { - Menu = new MainMenu(), - RightToLeft = RightToLeft.Yes - }; - MainMenu menu = form.Menu; - - menu.RightToLeft = value; - Assert.Equal(expectedValue, menu.RightToLeft); - } - - [Fact] - public void MainMenu_RightToLeft_SetCreated_GetReturnsExpected() - { - using (var menu = new MainMenu(new MenuItem[] { new MenuItem("text") })) - { - Assert.NotEqual(IntPtr.Zero, menu.Handle); - menu.RightToLeft = RightToLeft.Yes; - menu.RightToLeft = RightToLeft.No; - Assert.Equal(RightToLeft.No, menu.RightToLeft); - } - } - - [Theory] - [MemberData(nameof(CommonTestHelper.GetEnumTypeTheoryDataInvalid), typeof(RightToLeft), MemberType = typeof(CommonTestHelper))] - public void MainMenu_RightToLeft_SetInvalid_ThrowsInvalidEnumArgumentException(RightToLeft value) - { - var menu = new MainMenu(); - Assert.Throws("RightToLeft", () => menu.RightToLeft = value); - } - - [Fact] - public void MainMenu_OnCollapse_Invoke_Success() - { - var menu = new MainMenu(); - - // No handler. - menu.OnCollapse(null); - - // Handler. - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Equal(menu, sender); - callCount++; - }; - - menu.Collapse += handler; - menu.OnCollapse(null); - Assert.Equal(1, callCount); - - // Should not call if the handler is removed. - menu.Collapse -= handler; - menu.OnCollapse(null); - Assert.Equal(1, callCount); - } - - public static IEnumerable CloneMenu_TestData() - { - yield return new object[] { Array.Empty() }; - yield return new object[] { new MenuItem[] { new MenuItem("text") } }; - } - - [Theory] - [MemberData(nameof(CloneMenu_TestData))] - public void MainMenu_CloneMenu_Invoke_Success(MenuItem[] items) - { - var source = new MainMenu(items) - { - RightToLeft = RightToLeft.No - }; - MainMenu menu = source.CloneMenu(); - Assert.NotSame(source, menu); - Assert.Equal(items.Select(m => m.Name), menu.MenuItems.Cast().Select(m => m.Name)); - Assert.Equal(source.IsParent, menu.IsParent); - Assert.Equal(RightToLeft.Inherit, menu.RightToLeft); - Assert.Null(menu.GetForm()); - Assert.Empty(menu.Name); - Assert.Null(menu.Site); - Assert.Null(menu.Container); - Assert.Null(menu.Tag); - } - - [Fact] - public void MainMenu_Dispose_HasForm_Success() - { - var form = new Form - { - Menu = new MainMenu() - }; - - MainMenu menu = form.Menu; - menu.Dispose(); - Assert.Null(menu.GetForm()); - Assert.Null(form.Menu); - } - - [Fact] - public void MainMenu_Dispose_HasOwnerForm_Success() - { - var parentForm = new Form { IsMdiContainer = true }; - var form = new Form - { - Menu = new MainMenu(), - MdiParent = parentForm - }; - - MainMenu menu = form.MergedMenu; - menu.Dispose(); - Assert.Null(menu.GetForm()); - Assert.Null(form.Menu); - } - - private class SubContextMenu : MainMenu - { - public new void OnCollapse(EventArgs e) => base.OnCollapse(e); - } - } -} diff --git a/src/System.Windows.Forms/tests/UnitTests/MenuItemCollectionTests.cs b/src/System.Windows.Forms/tests/UnitTests/MenuItemCollectionTests.cs deleted file mode 100644 index 521a3aa9bde..00000000000 --- a/src/System.Windows.Forms/tests/UnitTests/MenuItemCollectionTests.cs +++ /dev/null @@ -1,760 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Collections; -using System.Collections.Generic; -using System.ComponentModel; -using System.Linq; -using WinForms.Common.Tests; -using Xunit; - -namespace System.Windows.Forms.Tests -{ - public class MenuItemCollectionTests - { - [Fact] - public void MenuItemCollection_Ctor_Menu() - { - var menu = new SubMenu(new MenuItem[] { new MenuItem() }); - var collection = new Menu.MenuItemCollection(menu); - Assert.Single(collection); - } - - [Fact] - public void MenuItemCollection_IList_Properties_ReturnsExpected() - { - var menu = new SubMenu(Array.Empty()); - IList collection = new Menu.MenuItemCollection(menu); - Assert.False(collection.IsFixedSize); - Assert.False(collection.IsReadOnly); - Assert.False(collection.IsSynchronized); - Assert.Same(collection, collection.SyncRoot); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetStringNormalizedTheoryData))] - public void MenuItemCollection_Add_String_Success(string caption, string expectedText) - { - var menu = new SubMenu(Array.Empty()); - var collection = new Menu.MenuItemCollection(menu); - MenuItem menuItem = collection.Add(caption); - Assert.Same(menuItem, Assert.Single(collection)); - Assert.Equal(expectedText, menuItem.Text); - Assert.Empty(menuItem.MenuItems); - Assert.Equal(menu, menuItem.Parent); - Assert.Equal(0, menuItem.Index); - } - - public static IEnumerable Add_StringEventHandler_TestData() - { - EventHandler onClick = (sender, e) => { }; - yield return new object[] { null, null, string.Empty }; - yield return new object[] { string.Empty, onClick, string.Empty }; - yield return new object[] { "caption", onClick, "caption" }; - } - - [Theory] - [MemberData(nameof(Add_StringEventHandler_TestData))] - public void MenuItemCollection_Add_StringEventHandler_Success(string caption, EventHandler onClick, string expectedText) - { - var menu = new SubMenu(Array.Empty()); - var collection = new Menu.MenuItemCollection(menu); - MenuItem menuItem = collection.Add(caption, onClick); - Assert.Same(menuItem, Assert.Single(collection)); - Assert.Same(expectedText, menuItem.Text); - Assert.Empty(menuItem.MenuItems); - Assert.Equal(menu, menuItem.Parent); - Assert.Equal(0, menuItem.Index); - } - - public static IEnumerable Add_StringMenuItemArray_TestData() - { - yield return new object[] { null, null, string.Empty }; - yield return new object[] { string.Empty, Array.Empty(), string.Empty }; - yield return new object[] { "caption", new MenuItem[] { new MenuItem() }, "caption" }; - } - - [Theory] - [MemberData(nameof(Add_StringMenuItemArray_TestData))] - public void MenuItemCollection_Add_StringMenuItemArray_Success(string caption, MenuItem[] items, string expectedText) - { - var menu = new SubMenu(Array.Empty()); - var collection = new Menu.MenuItemCollection(menu); - MenuItem menuItem = collection.Add(caption, items); - Assert.Same(menuItem, Assert.Single(collection)); - Assert.Same(expectedText, menuItem.Text); - Assert.Equal(items ?? Array.Empty(), menuItem.MenuItems.Cast()); - Assert.Equal(menu, menuItem.Parent); - Assert.Equal(0, menuItem.Index); - } - - [Fact] - public void MenuItemCollection_Add_MenuItem_Success() - { - var menu = new SubMenu(Array.Empty()); - var collection = new Menu.MenuItemCollection(menu); - - var menuItem1 = new MenuItem("text1"); - Assert.Equal(0, collection.Add(menuItem1)); - Assert.Same(menuItem1, Assert.Single(collection)); - Assert.Equal(menu, menuItem1.Parent); - Assert.Equal(0, menuItem1.Index); - - var menuItem2 = new MenuItem("text2"); - Assert.Equal(1, collection.Add(menuItem2)); - Assert.Equal(2, collection.Count); - Assert.Same(menuItem1, collection[0]); - Assert.Same(menuItem2, collection[1]); - Assert.Equal(menu, menuItem1.Parent); - Assert.Equal(0, menuItem1.Index); - Assert.Equal(menu, menuItem2.Parent); - Assert.Equal(1, menuItem2.Index); - } - - [Fact] - public void MenuItemCollection_Add_IndexMenuItem_Success() - { - var menu = new SubMenu(Array.Empty()); - var collection = new Menu.MenuItemCollection(menu); - - var menuItem1 = new MenuItem("text1"); - Assert.Equal(0, collection.Add(0, menuItem1)); - Assert.Same(menuItem1, Assert.Single(collection)); - Assert.Equal(menu, menuItem1.Parent); - Assert.Equal(0, menuItem1.Index); - - var menuItem2 = new MenuItem("text1"); - Assert.Equal(0, collection.Add(0, menuItem2)); - Assert.Equal(2, collection.Count); - Assert.Same(menuItem2, collection[0]); - Assert.Same(menuItem1, collection[1]); - Assert.Equal(menu, menuItem1.Parent); - Assert.Equal(1, menuItem1.Index); - Assert.Equal(menu, menuItem2.Parent); - Assert.Equal(0, menuItem2.Index); - } - - [Fact] - public void MenuItemCollection_Add_SelfMenuItem_Nop() - { - var menuItem = new MenuItem("text", Array.Empty()); - var collection = new Menu.MenuItemCollection(menuItem); - Assert.Empty(collection); - } - - [Fact] - public void MenuItemCollection_Add_AlreadyInSameCollection_Success() - { - var menuItem1 = new MenuItem(); - var menuItem2 = new MenuItem(); - var parent = new MenuItem("text", Array.Empty()); - var collection = new Menu.MenuItemCollection(parent) - { - menuItem1, - menuItem2 - }; - - Assert.Equal(0, collection.Add(0, menuItem2)); - Assert.Equal(2, collection.Count); - Assert.Same(menuItem2, collection[0]); - Assert.Same(menuItem1, collection[1]); - Assert.Equal(parent, menuItem1.Parent); - Assert.Equal(1, menuItem1.Index); - Assert.Equal(parent, menuItem2.Parent); - Assert.Equal(0, menuItem2.Index); - - Assert.Equal(1, collection.Add(2, menuItem2)); - Assert.Equal(2, collection.Count); - Assert.Same(menuItem1, collection[0]); - Assert.Same(menuItem2, collection[1]); - Assert.Equal(parent, menuItem1.Parent); - Assert.Equal(0, menuItem1.Index); - Assert.Equal(parent, menuItem2.Parent); - Assert.Equal(1, menuItem2.Index); - } - - [Fact] - public void MenuItemCollection_Add_AlreadyInDifferentCollection_Success() - { - var oldParent = new MenuItem("text", Array.Empty()); - var oldCollection = new Menu.MenuItemCollection(oldParent); - var newParent = new MenuItem("text", Array.Empty()); - var newCollection = new Menu.MenuItemCollection(newParent); - - var menuItem = new MenuItem(); - oldCollection.Add(menuItem); - - Assert.Equal(0, newCollection.Add(menuItem)); - Assert.Empty(oldCollection); - Assert.Same(menuItem, Assert.Single(newCollection)); - Assert.Equal(newParent, menuItem.Parent); - Assert.Equal(0, menuItem.Index); - } - - [Fact] - public void MenuItemCollection_Add_MenuItemToCreatedMenu_Success() - { - using (var menu = new SubMenu(Array.Empty())) - { - Assert.NotEqual(IntPtr.Zero, menu.Handle); - - var collection = new Menu.MenuItemCollection(menu); - - var menuItem1 = new MenuItem("text1"); - Assert.Equal(0, collection.Add(menuItem1)); - Assert.Same(menuItem1, Assert.Single(collection)); - Assert.Equal(menu, menuItem1.Parent); - Assert.Equal(0, menuItem1.Index); - - var menuItem2 = new MenuItem("text2"); - Assert.Equal(1, collection.Add(menuItem2)); - Assert.Equal(2, collection.Count); - Assert.Same(menuItem1, collection[0]); - Assert.Same(menuItem2, collection[1]); - Assert.Equal(menu, menuItem1.Parent); - Assert.Equal(0, menuItem1.Index); - Assert.Equal(menu, menuItem2.Parent); - Assert.Equal(1, menuItem2.Index); - } - } - - [Fact] - public void MenuItemCollection_Add_CreatedMenuItemToMenu_Success() - { - var menuItem = new MenuItem("text1"); - using (var otherMenu = new SubMenu(new MenuItem[] { menuItem })) - { - Assert.NotEqual(IntPtr.Zero, otherMenu.Handle); - - var menu = new SubMenu(Array.Empty()); - var collection = new Menu.MenuItemCollection(menu); - - Assert.Equal(0, collection.Add(menuItem)); - Assert.Same(menuItem, Assert.Single(collection)); - Assert.Equal(menu, menuItem.Parent); - Assert.Equal(0, menuItem.Index); - } - } - - [Fact] - public void MenuItemCollection_Add_NullMenuItem_ThrowsArgumentNullException() - { - var menu = new SubMenu(Array.Empty()); - var collection = new Menu.MenuItemCollection(menu); - Assert.Throws("item", () => collection.Add((MenuItem)null)); - Assert.Throws("item", () => collection.Add(0, null)); - } - - [Fact] - public void MenuItemCollection_Add_SelfWithParent_ThrowsArgumentException() - { - var menuItem = new MenuItem("text", Array.Empty()); - var parent = new MenuItem("parent", new MenuItem[] { menuItem }); - var collection = new Menu.MenuItemCollection(menuItem); - Assert.Throws("item", () => collection.Add(menuItem)); - } - - [Fact] - public void MenuItemCollection_Add_ParentWithGrandparent_ThrowsArgumentException() - { - var menuItem = new MenuItem(); - var parent = new MenuItem("parent", new MenuItem[] { menuItem }); - var grandparent = new MenuItem("grandparent", new MenuItem[] { parent }); - - var oldCollection = new Menu.MenuItemCollection(menuItem); - Assert.Throws("item", () => oldCollection.Add(parent)); - } - - [Theory] - [InlineData(-1)] - [InlineData(1)] - public void MenuItemCollection_Add_InvalidIndex_ThrowsArgumentOutOfRangeException(int index) - { - var menu = new SubMenu(Array.Empty()); - var collection = new Menu.MenuItemCollection(menu); - Assert.Throws("index", () => collection.Add(index, new MenuItem())); - } - - [Theory] - [InlineData(-1)] - [InlineData(2)] - public void MenuItemCollection_Add_AlreadyInCollection_InvalidIndex_ThrowsArgumentOutOfRangeException(int index) - { - var menuItem = new MenuItem(); - var parent = new MenuItem("text", Array.Empty()); - var collection = new Menu.MenuItemCollection(parent) - { - menuItem - }; - Assert.Throws("index", () => collection.Add(index, menuItem)); - } - - [Fact] - public void MenuItemCollection_Add_IListMenuItem_Success() - { - var menu = new SubMenu(Array.Empty()); - IList collection = new Menu.MenuItemCollection(menu); - - var menuItem1 = new MenuItem("text1"); - Assert.Equal(0, collection.Add(menuItem1)); - Assert.Same(menuItem1, Assert.Single(collection)); - Assert.Equal(menu, menuItem1.Parent); - Assert.Equal(0, menuItem1.Index); - - var menuItem2 = new MenuItem("text2"); - Assert.Equal(1, collection.Add(menuItem2)); - Assert.Equal(2, collection.Count); - Assert.Same(menuItem1, collection[0]); - Assert.Same(menuItem2, collection[1]); - Assert.Equal(menu, menuItem1.Parent); - Assert.Equal(0, menuItem1.Index); - Assert.Equal(menu, menuItem2.Parent); - Assert.Equal(1, menuItem2.Index); - } - - [Theory] - [InlineData("value")] - [InlineData(null)] - public void MenuItemCollection_Add_IListNotMenuItem_ThrowsArgumentException(object value) - { - var menu = new SubMenu(Array.Empty()); - IList collection = new Menu.MenuItemCollection(menu); - Assert.Throws("value", () => collection.Add(value)); - } - - public static IEnumerable AddRange_TestData() - { - yield return new object[] { Array.Empty() }; - yield return new object[] { new MenuItem[] { new MenuItem(), new MenuItem() } }; - } - - [Theory] - [MemberData(nameof(AddRange_TestData))] - public void MenuItemCollection_AddRange_Invoke_Success(MenuItem[] items) - { - var menu = new SubMenu(Array.Empty()); - var collection = new Menu.MenuItemCollection(menu); - collection.AddRange(items); - Assert.Equal(items.Length, collection.Count); - Assert.Equal(items, collection.Cast()); - } - - [Fact] - public void MenuItemCollection_AddRange_NullItems_ThrowsArgumentNullException() - { - var menu = new SubMenu(Array.Empty()); - var collection = new Menu.MenuItemCollection(menu); - Assert.Throws("items", () => collection.AddRange(null)); - } - - [Fact] - public void MenuItemCollection_AddRange_NullValueInItems_ThrowsArgumentNullException() - { - var menu = new SubMenu(Array.Empty()); - var collection = new Menu.MenuItemCollection(menu); - Assert.Throws("item", () => collection.AddRange(new MenuItem[] { null })); - } - - [Fact] - public void MenuItemCollection_Clear_InvokeOnMenu_Success() - { - var menuItem = new MenuItem(); - var menu = new SubMenu(new MenuItem[] { menuItem }); - var collection = new Menu.MenuItemCollection(menu); - collection.Clear(); - Assert.Empty(collection); - Assert.Null(menuItem.Parent); - Assert.Equal(-1, menuItem.Index); - - collection.Clear(); - Assert.Empty(collection); - } - - [Fact] - public void MenuItemCollection_Clear_InvokeOnMenuItem_Success() - { - var menuItem = new MenuItem(); - var menu = new MenuItem("text", new MenuItem[] { menuItem }); - var collection = new Menu.MenuItemCollection(menu); - collection.Clear(); - Assert.Empty(collection); - Assert.Null(menuItem.Parent); - Assert.Equal(-1, menuItem.Index); - - collection.Clear(); - Assert.Empty(collection); - } - - [Fact] - public void MenuItemCollection_CopyTo_NotEmpty_Success() - { - var menuItem = new MenuItem(); - var menu = new SubMenu(Array.Empty()); - var collection = new Menu.MenuItemCollection(menu) - { - menuItem - }; - var array = new object[] { 1, 2, 3 }; - collection.CopyTo(array, 1); - Assert.Equal(new object[] { 1, menuItem, 3 }, array); - } - - [Fact] - public void MenuItemCollection_CopyTo_Empty_Nop() - { - var menu = new SubMenu(Array.Empty()); - var collection = new Menu.MenuItemCollection(menu); - var array = new object[] { 1, 2, 3 }; - collection.CopyTo(array, 1); - Assert.Equal(new object[] { 1, 2, 3 }, array); - } - - public static IEnumerable Contains_TestData() - { - var menuItem = new MenuItem(); - yield return new object[] { new SubMenu(new MenuItem[] { menuItem }), menuItem, true }; - yield return new object[] { new SubMenu(new MenuItem[] { new MenuItem() }), new MenuItem(), false }; - yield return new object[] { new SubMenu(new MenuItem[] { new MenuItem() }), null, false }; - } - - [Theory] - [MemberData(nameof(Contains_TestData))] - public void MenuItemCollection_Contains_Invoke_ReturnsExpected(Menu menu, MenuItem value, bool expected) - { - var collection = new Menu.MenuItemCollection(menu); - Assert.Equal(expected, collection.Contains(value)); - } - - [Theory] - [MemberData(nameof(Contains_TestData))] - public void MenuItemCollection_Contains_IListInvoke_ReturnsExpected(Menu menu, MenuItem value, bool expected) - { - IList collection = new Menu.MenuItemCollection(menu); - Assert.Equal(expected, collection.Contains(value)); - } - - [Fact] - public void MenuItemCollection_Contains_IListNotMenuItem_ReturnsMinusOne() - { - var menu = new SubMenu(Array.Empty()); - IList collection = new Menu.MenuItemCollection(menu); - Assert.False(collection.Contains("value")); - } - - [Theory] - [InlineData(null, false)] - [InlineData("", false)] - [InlineData("name", true)] - [InlineData("NAME", true)] - [InlineData("noSuchName", false)] - public void MenuItemCollection_ContainsKey_Invoke_ReturnsExpected(string key, bool expected) - { - var menu = new SubMenu(new MenuItem[] { new MenuItem { Name = "name" } }); - var collection = new Menu.MenuItemCollection(menu); - Assert.Equal(expected, collection.ContainsKey(key)); - } - - public static IEnumerable Find_TestData() - { - yield return new object[] { new MenuItem[] { new MenuItem() }, "noSuchKey", false, Array.Empty() }; - yield return new object[] { new MenuItem[] { new MenuItem() }, "noSuchKey", true, Array.Empty() }; - - foreach (bool searchAllChildren in new bool[] { true, false }) - { - var menuItem1 = new MenuItem { Name = "name" }; - var menuItem2 = new MenuItem { Name = "NAME" }; - var menuItem3 = new MenuItem { Name = "otherName" }; - var menuItem4 = new MenuItem { Name = "name" }; - yield return new object[] { new MenuItem[] { menuItem1, menuItem2, menuItem3 }, "name", searchAllChildren, new MenuItem[] { menuItem1, menuItem2 } }; - } - - yield return new object[] { new MenuItem[] { new MenuItem { Name = "name" } }, "noSuchName", true, Array.Empty() }; - yield return new object[] { new MenuItem[] { new MenuItem { Name = "name" } }, "noSuchName", false, Array.Empty() }; - yield return new object[] { new MenuItem[] { new MenuItem("text", new MenuItem[] { new MenuItem { Name = "name2" } }) { Name = "name" }, }, "noSuchName", true, Array.Empty() }; - yield return new object[] { new MenuItem[] { new MenuItem("text", new MenuItem[] { new MenuItem { Name = "name2" } }) { Name = "name" }, }, "noSuchName", false, Array.Empty() }; - - var menuItemChild = new MenuItem { Name = "name" }; - yield return new object[] { new MenuItem[] { new MenuItem("text", new MenuItem[] { menuItemChild }) }, "name", true, new MenuItem[] { menuItemChild } }; - yield return new object[] { new MenuItem[] { new MenuItem("text", new MenuItem[] { new MenuItem { Name = "name" } }) }, "name", false, Array.Empty() }; - } - - [Theory] - [MemberData(nameof(Find_TestData))] - public void MenuItemCollection_Find_Invoke_ReturnsExpected(MenuItem[] items, string key, bool searchAllChildren, MenuItem[] expected) - { - var menu = new SubMenu(items); - var collection = new Menu.MenuItemCollection(menu); - Assert.Equal(expected, collection.Find(key, searchAllChildren)); - } - - [Theory] - [InlineData(null)] - [InlineData("")] - public void MenuItemCollection_Find_NullOrEmptyKey_ThrowsArgumentNullException(string key) - { - var menu = new SubMenu(Array.Empty()); - var collection = new Menu.MenuItemCollection(menu); - Assert.Throws("key", () => collection.Find(key, searchAllChildren: false)); - } - - public static IEnumerable IndexOf_TestData() - { - var menuItem = new MenuItem(); - yield return new object[] { new SubMenu(new MenuItem[] { menuItem }), menuItem, 0 }; - yield return new object[] { new SubMenu(new MenuItem[] { new MenuItem() }), new MenuItem(), -1 }; - yield return new object[] { new SubMenu(new MenuItem[] { new MenuItem() }), null, -1 }; - } - - [Theory] - [MemberData(nameof(IndexOf_TestData))] - public void MenuItemCollection_IndexOf_Invoke_ReturnsExpected(Menu menu, MenuItem value, int expected) - { - var collection = new Menu.MenuItemCollection(menu); - Assert.Equal(expected, collection.IndexOf(value)); - } - - [Theory] - [MemberData(nameof(IndexOf_TestData))] - public void MenuItemCollection_IndexOf_IListInvoke_ReturnsExpected(Menu menu, MenuItem value, int expected) - { - IList collection = new Menu.MenuItemCollection(menu); - Assert.Equal(expected, collection.IndexOf(value)); - } - - [Fact] - public void MenuItemCollection_IndexOf_IListNotMenuItem_ReturnsMinusOne() - { - var menu = new SubMenu(Array.Empty()); - IList collection = new Menu.MenuItemCollection(menu); - Assert.Equal(-1, collection.IndexOf("value")); - } - - [Theory] - [InlineData(null, -1)] - [InlineData("", -1)] - [InlineData("name", 0)] - [InlineData("NAME", 0)] - [InlineData("noSuchName", -1)] - public void MenuItemCollection_IndexOfKey_Invoke_ReturnsExpected(string key, int expected) - { - var menu = new SubMenu(new MenuItem[] { new MenuItem { Name = "name" } }); - var collection = new Menu.MenuItemCollection(menu); - Assert.Equal(expected, collection.IndexOfKey(key)); - - // Call again to validate caching behaviour. - Assert.Equal(expected, collection.IndexOfKey(key)); - Assert.Equal(-1, collection.IndexOfKey("noSuchKey")); - } - - [Fact] - public void MenuItemCollection_Insert_IListInvoke_Success() - { - var menu = new SubMenu(Array.Empty()); - IList collection = new Menu.MenuItemCollection(menu); - - var menuItem1 = new MenuItem("text1"); - collection.Insert(0, menuItem1); - Assert.Same(menuItem1, Assert.Single(collection)); - Assert.Equal(menu, menuItem1.Parent); - Assert.Equal(0, menuItem1.Index); - - var menuItem2 = new MenuItem("text1"); - collection.Insert(0, menuItem2); - Assert.Equal(2, collection.Count); - Assert.Same(menuItem2, collection[0]); - Assert.Same(menuItem1, collection[1]); - Assert.Equal(menu, menuItem1.Parent); - Assert.Equal(1, menuItem1.Index); - Assert.Equal(menu, menuItem2.Parent); - Assert.Equal(0, menuItem2.Index); - } - - [Theory] - [InlineData("value")] - [InlineData(null)] - public void MenuItemCollection_Insert_IListNotMenuItem_ThrowsArgumentException(object value) - { - var menu = new SubMenu(Array.Empty()); - IList collection = new Menu.MenuItemCollection(menu); - Assert.Throws("value", () => collection.Insert(0, value)); - } - - [Fact] - public void MenuItemCollection_Item_GetValidIndex_ReturnsExpected() - { - var menuItem = new MenuItem(); - var menu = new SubMenu(new MenuItem[] { menuItem }); - var collection = new Menu.MenuItemCollection(menu); - Assert.Equal(menuItem, collection[0]); - } - - [Theory] - [InlineData(-1)] - [InlineData(1)] - public void MenuItemCollection_Item_GetInvalidIndex_ThrowsArgumentOutOfRangeException(int index) - { - var menu = new SubMenu(new MenuItem[] { new MenuItem() }); - var collection = new Menu.MenuItemCollection(menu); - Assert.Throws("index", () => collection[index]); - } - - [Fact] - public void MenuItemCollection_Item_IListGetValidIndex_ReturnsExpected() - { - var menuItem = new MenuItem(); - var menu = new SubMenu(new MenuItem[] { menuItem }); - IList collection = new Menu.MenuItemCollection(menu); - Assert.Equal(menuItem, collection[0]); - } - - [Theory] - [InlineData(-1)] - [InlineData(1)] - public void MenuItemCollection_Item_IListGetInvalidIndex_ThrowsArgumentOutOfRangeException(int index) - { - var menu = new SubMenu(new MenuItem[] { new MenuItem() }); - IList collection = new Menu.MenuItemCollection(menu); - Assert.Throws("index", () => collection[index]); - } - - [Theory] - [InlineData(-1)] - [InlineData(0)] - [InlineData(1)] - public void MenuItemCollection_Item_IListSet_ThrowsNotSupportedException(int index) - { - var menu = new SubMenu(new MenuItem[] { new MenuItem() }); - IList collection = new Menu.MenuItemCollection(menu); - Assert.Throws(() => collection[index] = new MenuItem()); - } - - [Theory] - [InlineData(null, false)] - [InlineData("", false)] - [InlineData("name", true)] - [InlineData("NAME", true)] - [InlineData("noSuchName", false)] - public void MenuItemCollection_Item_GetKey_ReturnsExpected(string key, bool expected) - { - var menuItem = new MenuItem { Name = "name" }; - var menu = new SubMenu(new MenuItem[] { menuItem }); - var collection = new Menu.MenuItemCollection(menu); - Assert.Equal(expected ? menuItem : null, collection[key]); - } - - [Fact] - public void MenuItemCollection_Remove_MenuItem_Success() - { - var menuItem = new MenuItem(); - var menu = new SubMenu(new MenuItem[] { menuItem }); - var collection = new Menu.MenuItemCollection(menu); - collection.Remove(menuItem); - Assert.Empty(collection); - Assert.Null(menuItem.Parent); - Assert.Equal(-1, menuItem.Index); - } - - [Fact] - public void MenuItemCollection_Remove_DifferentOwnerMenuMenuItem_Nop() - { - var menuItem = new MenuItem(); - var menu = new SubMenu(new MenuItem[] { menuItem }); - var collection = new Menu.MenuItemCollection(menu); - - var otherMenuItem = new MenuItem(); - var otherMenu = new SubMenu(new MenuItem[] { otherMenuItem }); - collection.Remove(otherMenuItem); - Assert.Equal(menuItem, Assert.Single(collection)); - } - - [Fact] - public void MenuItemCollection_Remove_NoMenuMenuItem_Nop() - { - var menuItem = new MenuItem(); - var menu = new SubMenu(new MenuItem[] { menuItem }); - var collection = new Menu.MenuItemCollection(menu); - collection.Remove(new MenuItem()); - Assert.Equal(menuItem, Assert.Single(collection)); - } - - [Fact] - public void MenuItemCollection_Remove_IListMenuItem_Success() - { - var menuItem = new MenuItem(); - var menu = new SubMenu(new MenuItem[] { menuItem }); - IList collection = new Menu.MenuItemCollection(menu); - collection.Remove(menuItem); - Assert.Empty(collection); - Assert.Null(menuItem.Parent); - Assert.Equal(-1, menuItem.Index); - } - - [Theory] - [InlineData("value")] - [InlineData(null)] - public void MenuItemCollection_Remove_IListNotMenuItem_Nop(object value) - { - var menuItem = new MenuItem(); - var menu = new SubMenu(new MenuItem[] { menuItem }); - IList collection = new Menu.MenuItemCollection(menu); - collection.Remove(value); - Assert.Equal(menuItem, Assert.Single(collection)); - } - - [Fact] - public void MenuItemCollection_RemoveAt_Invoke_Success() - { - var menuItem = new MenuItem(); - var menu = new SubMenu(new MenuItem[] { menuItem }); - var collection = new Menu.MenuItemCollection(menu); - collection.RemoveAt(0); - - Assert.Empty(collection); - Assert.Null(menuItem.Parent); - Assert.Equal(-1, menuItem.Index); - } - - [Theory] - [InlineData(-1)] - [InlineData(1)] - public void MenuItemCollection_RemoveAt_InvalidIndex_ThrowsArgumentOutOfRangeException(int index) - { - var menu = new SubMenu(new MenuItem[] { new MenuItem() }); - var collection = new Menu.MenuItemCollection(menu); - Assert.Throws("index", () => collection.RemoveAt(index)); - } - - [Theory] - [InlineData("name")] - [InlineData("NAME")] - public void MenuItemCollection_RemoveByKey_KeyExists_Success(string key) - { - var menuItem = new MenuItem { Name = "name" }; - var menu = new SubMenu(new MenuItem[] { menuItem }); - var collection = new Menu.MenuItemCollection(menu); - collection.RemoveByKey(key); - Assert.Empty(collection); - } - - [Theory] - [InlineData(null)] - [InlineData("")] - [InlineData("noSuchName")] - public void MenuItemCollection_RemoveByKey_NoSuchKey_Nop(string key) - { - var menuItem = new MenuItem { Name = "name" }; - var menu = new SubMenu(new MenuItem[] { menuItem }); - var collection = new Menu.MenuItemCollection(menu); - collection.RemoveByKey(key); - Assert.Equal(menuItem, Assert.Single(collection)); - } - - private class SubMenu : Menu - { - public SubMenu(params MenuItem[] items) : base(items) - { - } - } - } -} diff --git a/src/System.Windows.Forms/tests/UnitTests/MenuItemTests.cs b/src/System.Windows.Forms/tests/UnitTests/MenuItemTests.cs deleted file mode 100644 index 4089c535e6a..00000000000 --- a/src/System.Windows.Forms/tests/UnitTests/MenuItemTests.cs +++ /dev/null @@ -1,1827 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Collections.Generic; -using System.ComponentModel; -using System.Linq; -using Moq; -using WinForms.Common.Tests; -using Xunit; - -namespace System.Windows.Forms.Tests -{ - public class MenuItemTests - { - [Fact] - public void MenuItem_Ctor_Default() - { - var menuItem = new MenuItem(); - Assert.False(menuItem.BarBreak); - Assert.False(menuItem.Break); - Assert.False(menuItem.Checked); - Assert.False(menuItem.DefaultItem); - Assert.True(menuItem.Enabled); - Assert.Equal(-1, menuItem.Index); - Assert.False(menuItem.IsParent); - Assert.False(menuItem.MdiList); - Assert.Empty(menuItem.MenuItems); - Assert.Equal(0, menuItem.MergeOrder); - Assert.Equal(MenuMerge.Add, menuItem.MergeType); - Assert.Equal('\0', menuItem.Mnemonic); - Assert.False(menuItem.OwnerDraw); - Assert.Null(menuItem.Parent); - Assert.False(menuItem.RadioCheck); - Assert.True(menuItem.ShowShortcut); - Assert.Equal(Shortcut.None, menuItem.Shortcut); - Assert.True(menuItem.Visible); - Assert.Empty(menuItem.Name); - Assert.Null(menuItem.Site); - Assert.Null(menuItem.Container); - Assert.Null(menuItem.Tag); - Assert.Empty(menuItem.Text); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetStringNormalizedTheoryData))] - public void MenuItem_Ctor_String(string text, string expectedText) - { - var menuItem = new MenuItem(text); - Assert.False(menuItem.BarBreak); - Assert.False(menuItem.Break); - Assert.False(menuItem.Checked); - Assert.False(menuItem.DefaultItem); - Assert.True(menuItem.Enabled); - Assert.Equal(-1, menuItem.Index); - Assert.False(menuItem.IsParent); - Assert.False(menuItem.MdiList); - Assert.Empty(menuItem.MenuItems); - Assert.Equal(0, menuItem.MergeOrder); - Assert.Equal(MenuMerge.Add, menuItem.MergeType); - Assert.Equal('\0', menuItem.Mnemonic); - Assert.False(menuItem.OwnerDraw); - Assert.Null(menuItem.Parent); - Assert.False(menuItem.RadioCheck); - Assert.True(menuItem.ShowShortcut); - Assert.Equal(Shortcut.None, menuItem.Shortcut); - Assert.True(menuItem.Visible); - Assert.Empty(menuItem.Name); - Assert.Null(menuItem.Site); - Assert.Null(menuItem.Container); - Assert.Null(menuItem.Tag); - Assert.Equal(expectedText, menuItem.Text); - } - - public static IEnumerable Ctor_String_EventHandler_TestData() - { - EventHandler onClick = (sender, e) => { }; - yield return new object[] { null, null, string.Empty }; - yield return new object[] { string.Empty, onClick, string.Empty }; - yield return new object[] { "text", onClick, "text" }; - } - - [Theory] - [MemberData(nameof(Ctor_String_EventHandler_TestData))] - public void MenuItem_Ctor_String_EventHandler(string text, EventHandler onClick, string expectedText) - { - var menuItem = new MenuItem(text, onClick); - Assert.False(menuItem.BarBreak); - Assert.False(menuItem.Break); - Assert.False(menuItem.Checked); - Assert.False(menuItem.DefaultItem); - Assert.True(menuItem.Enabled); - Assert.Equal(-1, menuItem.Index); - Assert.False(menuItem.IsParent); - Assert.False(menuItem.MdiList); - Assert.Empty(menuItem.MenuItems); - Assert.Equal(0, menuItem.MergeOrder); - Assert.Equal(MenuMerge.Add, menuItem.MergeType); - Assert.Equal('\0', menuItem.Mnemonic); - Assert.False(menuItem.OwnerDraw); - Assert.Null(menuItem.Parent); - Assert.False(menuItem.RadioCheck); - Assert.True(menuItem.ShowShortcut); - Assert.Equal(Shortcut.None, menuItem.Shortcut); - Assert.True(menuItem.Visible); - Assert.Empty(menuItem.Name); - Assert.Null(menuItem.Site); - Assert.Null(menuItem.Container); - Assert.Null(menuItem.Tag); - Assert.Same(expectedText, menuItem.Text); - } - - [Fact] - public void MenuItem_Ctor_String_EventHandler_OnClick() - { - SubMenuItem menuItem = null; - int callCount = 0; - EventHandler onClick = (sender, e) => - { - Assert.Same(menuItem, sender); - callCount++; - }; - menuItem = new SubMenuItem("text", onClick); - menuItem.OnClick(null); - Assert.Equal(1, callCount); - } - - public static IEnumerable Ctor_String_EventHandler_Shortcut_TestData() - { - EventHandler onClick = (sender, e) => { }; - yield return new object[] { null, null, Shortcut.None, string.Empty }; - yield return new object[] { string.Empty, onClick, (Shortcut)(Shortcut.None - 1), string.Empty }; - yield return new object[] { "text", onClick, Shortcut.CtrlA, "text" }; - } - - [Theory] - [MemberData(nameof(Ctor_String_EventHandler_Shortcut_TestData))] - public void MenuItem_Ctor_String_EventHandler_Shortcut(string text, EventHandler onClick, Shortcut shortcut, string expectedText) - { - var menuItem = new MenuItem(text, onClick, shortcut); - Assert.False(menuItem.BarBreak); - Assert.False(menuItem.Break); - Assert.False(menuItem.Checked); - Assert.False(menuItem.DefaultItem); - Assert.True(menuItem.Enabled); - Assert.Equal(-1, menuItem.Index); - Assert.False(menuItem.IsParent); - Assert.False(menuItem.MdiList); - Assert.Empty(menuItem.MenuItems); - Assert.Equal(0, menuItem.MergeOrder); - Assert.Equal(MenuMerge.Add, menuItem.MergeType); - Assert.Equal('\0', menuItem.Mnemonic); - Assert.False(menuItem.OwnerDraw); - Assert.Null(menuItem.Parent); - Assert.False(menuItem.RadioCheck); - Assert.True(menuItem.ShowShortcut); - Assert.Equal(shortcut, menuItem.Shortcut); - Assert.True(menuItem.Visible); - Assert.Empty(menuItem.Name); - Assert.Null(menuItem.Site); - Assert.Null(menuItem.Container); - Assert.Null(menuItem.Tag); - Assert.Same(expectedText, menuItem.Text); - } - - [Fact] - public void MenuItem_Ctor_String_EventHandler_Shortcut_OnClick() - { - SubMenuItem menuItem = null; - int callCount = 0; - EventHandler onClick = (sender, e) => - { - Assert.Same(menuItem, sender); - callCount++; - }; - menuItem = new SubMenuItem("text", onClick, Shortcut.None); - menuItem.OnClick(null); - Assert.Equal(1, callCount); - } - - public static IEnumerable Ctor_String_MenuItemArray_TestData() - { - yield return new object[] { null, null, false, string.Empty }; - yield return new object[] { string.Empty, Array.Empty(), false, string.Empty }; - yield return new object[] { "text", new MenuItem[] { new MenuItem() }, true, "text" }; - } - - [Theory] - [MemberData(nameof(Ctor_String_MenuItemArray_TestData))] - public void MenuItem_Ctor_String_MenuItemArray(string text, MenuItem[] items, bool expectedIsParent, string expectedText) - { - var menuItem = new MenuItem(text, items); - Assert.False(menuItem.BarBreak); - Assert.False(menuItem.Break); - Assert.False(menuItem.Checked); - Assert.False(menuItem.DefaultItem); - Assert.True(menuItem.Enabled); - Assert.Equal(-1, menuItem.Index); - Assert.Equal(expectedIsParent, menuItem.IsParent); - Assert.False(menuItem.MdiList); - Assert.Equal(items ?? Array.Empty(), menuItem.MenuItems.Cast()); - Assert.Equal(0, menuItem.MergeOrder); - Assert.Equal(MenuMerge.Add, menuItem.MergeType); - Assert.Equal('\0', menuItem.Mnemonic); - Assert.False(menuItem.OwnerDraw); - Assert.Null(menuItem.Parent); - Assert.False(menuItem.RadioCheck); - Assert.True(menuItem.ShowShortcut); - Assert.Equal(Shortcut.None, menuItem.Shortcut); - Assert.True(menuItem.Visible); - Assert.Empty(menuItem.Name); - Assert.Null(menuItem.Site); - Assert.Null(menuItem.Container); - Assert.Null(menuItem.Tag); - Assert.Same(expectedText, menuItem.Text); - } - - public static IEnumerable Ctor_MergeType_Int_Shortcut_String_EventHandler_EventHandler_EventHandler_MenuItemArray_TestData() - { - EventHandler onClick = (sender, e) => { }; - EventHandler onPopup = (sender, e) => { }; - EventHandler onSelect = (sender, e) => { }; - - yield return new object[] { (MenuMerge)(MenuMerge.Add - 1), -1, (Shortcut)(Shortcut.None - 1), null, null, null, null, null, false, string.Empty }; - yield return new object[] { MenuMerge.Add, 0, Shortcut.None, string.Empty, onClick, onPopup, onSelect, Array.Empty(), false, string.Empty }; - yield return new object[] { MenuMerge.MergeItems, 1, Shortcut.CtrlA, "text", onClick, onPopup, onSelect, new MenuItem[] { new MenuItem() }, true, "text" }; - } - - [Theory] - [MemberData(nameof(Ctor_MergeType_Int_Shortcut_String_EventHandler_EventHandler_EventHandler_MenuItemArray_TestData))] - public void MenuItem_Ctor_MenuMerge_Int_Shortcut_String_EventHandler_EventHandler_EventHandler_MenuItemArray(MenuMerge mergeType, int mergeOrder, Shortcut shortcut, string text, EventHandler onClick, EventHandler onPopup, EventHandler onSelect, MenuItem[] items, bool expectedIsParent, string expectedText) - { - var menuItem = new MenuItem(mergeType, mergeOrder, shortcut, text, onClick, onPopup, onSelect, items); - Assert.False(menuItem.BarBreak); - Assert.False(menuItem.Break); - Assert.False(menuItem.Checked); - Assert.False(menuItem.DefaultItem); - Assert.True(menuItem.Enabled); - Assert.Equal(-1, menuItem.Index); - Assert.Equal(expectedIsParent, menuItem.IsParent); - Assert.False(menuItem.MdiList); - Assert.Equal(items ?? Array.Empty(), menuItem.MenuItems.Cast()); - Assert.Equal(mergeOrder, menuItem.MergeOrder); - Assert.Equal(mergeType, menuItem.MergeType); - Assert.Equal('\0', menuItem.Mnemonic); - Assert.False(menuItem.OwnerDraw); - Assert.Null(menuItem.Parent); - Assert.False(menuItem.RadioCheck); - Assert.True(menuItem.ShowShortcut); - Assert.Equal(shortcut, menuItem.Shortcut); - Assert.True(menuItem.Visible); - Assert.Empty(menuItem.Name); - Assert.Null(menuItem.Site); - Assert.Null(menuItem.Container); - Assert.Null(menuItem.Tag); - Assert.Same(expectedText, menuItem.Text); - } - - [Fact] - public void MenuItem_Ctor_MenuMerge_Int_Shortcut_String_EventHandler_EventHandler_EventHandler_MenuItemArray_OnClick() - { - SubMenuItem menuItem = null; - int callCount = 0; - EventHandler onClick = (sender, e) => - { - Assert.Same(menuItem, sender); - callCount++; - }; - menuItem = new SubMenuItem(MenuMerge.Add, 0, Shortcut.None, string.Empty, onClick, null, null, Array.Empty()); - menuItem.OnClick(null); - Assert.Equal(1, callCount); - } - - [Fact] - public void MenuItem_Ctor_MenuMerge_Int_Shortcut_String_EventHandler_EventHandler_EventHandler_MenuItemArray_OnPopup() - { - SubMenuItem menuItem = null; - int callCount = 0; - EventHandler onPopup = (sender, e) => - { - Assert.Same(menuItem, sender); - callCount++; - }; - menuItem = new SubMenuItem(MenuMerge.Add, 0, Shortcut.None, string.Empty, null, onPopup, null, Array.Empty()); - menuItem.OnPopup(null); - Assert.Equal(1, callCount); - } - - [Fact] - public void MenuItem_Ctor_MenuMerge_Int_Shortcut_String_EventHandler_EventHandler_EventHandler_MenuItemArray_OnSelect() - { - SubMenuItem menuItem = null; - int callCount = 0; - EventHandler onSelect = (sender, e) => - { - Assert.Same(menuItem, sender); - callCount++; - }; - menuItem = new SubMenuItem(MenuMerge.Add, 0, Shortcut.None, string.Empty, null, null, onSelect, Array.Empty()); - menuItem.OnSelect(null); - Assert.Equal(1, callCount); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetBoolTheoryData))] - public void MenuItem_BarBreak_Set_GetReturnsExpected(bool value) - { - var menuItem = new MenuItem - { - BarBreak = value - }; - Assert.Equal(value, menuItem.BarBreak); - } - - [Fact] - public void MenuItem_BarBreak_Disposed_ThrowsObjectDisposedException() - { - var menuItem = new MenuItem(); - menuItem.Dispose(); - Assert.Throws(() => menuItem.BarBreak); - Assert.Throws(() => menuItem.BarBreak = true); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetBoolTheoryData))] - public void MenuItem_Break_Set_GetReturnsExpected(bool value) - { - var menuItem = new MenuItem - { - Break = value - }; - Assert.Equal(value, menuItem.Break); - } - - [Fact] - public void MenuItem_Break_Disposed_ThrowsObjectDisposedException() - { - var menuItem = new MenuItem(); - menuItem.Dispose(); - Assert.Throws(() => menuItem.Break); - Assert.Throws(() => menuItem.Break = true); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetBoolTheoryData))] - public void MenuItem_Checked_Set_GetReturnsExpected(bool value) - { - var menuItem = new MenuItem - { - Checked = value - }; - Assert.Equal(value, menuItem.Checked); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetBoolTheoryData))] - public void MenuItem_Checked_SetWithParent_GetReturnsExpected(bool value) - { - var menuItem = new MenuItem(); - var menu = new SubMenu(new MenuItem[] { menuItem }); - menuItem.Checked = value; - Assert.Equal(value, menuItem.Checked); - } - - [Fact] - public void MenuItem_Checked_SetWithMainMenuParent_ThrowsArgumentException() - { - var menuItem = new MenuItem(); - var menu = new MainMenu(new MenuItem[] { menuItem }); - Assert.Throws("value", () => menuItem.Checked = true); - Assert.False(menuItem.Checked); - - menuItem.Checked = false; - Assert.False(menuItem.Checked); - } - - [Fact] - public void MenuItem_Checked_SetWithChildren_ThrowsArgumentException() - { - var menuItem = new MenuItem("text", new MenuItem[] { new MenuItem() }); - Assert.Throws("value", () => menuItem.Checked = true); - Assert.False(menuItem.Checked); - - menuItem.Checked = false; - Assert.False(menuItem.Checked); - } - - [Fact] - public void MenuItem_Checked_Disposed_ThrowsObjectDisposedException() - { - var menuItem = new MenuItem(); - menuItem.Dispose(); - Assert.Throws(() => menuItem.Checked); - Assert.Throws(() => menuItem.Checked = true); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetBoolTheoryData))] - public void MenuItem_DefaultItem_Set_GetReturnsExpected(bool value) - { - var menuItem = new MenuItem - { - DefaultItem = value - }; - Assert.Equal(value, menuItem.DefaultItem); - } - - [Fact] - public void MenuItem_DefaultItem_SetWithParent_GetReturnsExpected() - { - var menuItem = new MenuItem(); - var menu = new SubMenu(new MenuItem[] { menuItem }); - menuItem.DefaultItem = true; - Assert.True(menuItem.DefaultItem); - - // Set same. - menuItem.DefaultItem = true; - Assert.True(menuItem.DefaultItem); - - menuItem.DefaultItem = false; - Assert.False(menuItem.DefaultItem); - - // Set same. - menuItem.DefaultItem = false; - Assert.False(menuItem.DefaultItem); - } - - [Fact] - public void MenuItem_DefaultItem_Disposed_ThrowsObjectDisposedException() - { - var menuItem = new MenuItem(); - menuItem.Dispose(); - Assert.Throws(() => menuItem.DefaultItem); - Assert.Throws(() => menuItem.DefaultItem = true); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetBoolTheoryData))] - public void MenuItem_Enabled_Set_GetReturnsExpected(bool value) - { - var menuItem = new MenuItem - { - Enabled = value - }; - Assert.Equal(value, menuItem.Enabled); - } - - [Fact] - public void MenuItem_Enabled_Disposed_ThrowsObjectDisposedException() - { - var menuItem = new MenuItem(); - menuItem.Dispose(); - Assert.Throws(() => menuItem.Enabled); - Assert.Throws(() => menuItem.Enabled = true); - } - - [Theory] - [InlineData(0)] - [InlineData(1)] - public void MenuItem_Index_SetWithParent_GetReturnsExpected(int value) - { - var menuItem1 = new MenuItem(); - var menuItem2 = new MenuItem(); - var menu = new SubMenu(new MenuItem[] { menuItem1, menuItem2 }); - menuItem1.Index = value; - Assert.Equal(value, menuItem1.Index); - if (value == 0) - { - Assert.Equal(new MenuItem[] { menuItem1, menuItem2 }, menu.MenuItems.Cast()); - } - else - { - Assert.Equal(new MenuItem[] { menuItem2, menuItem1 }, menu.MenuItems.Cast()); - } - } - - [Theory] - [InlineData(-1)] - [InlineData(1)] - public void MenuItem_Index_SetInvalid_ThrowsArgumentOutOfRangeException(int value) - { - var menuItem = new MenuItem(); - var menu = new SubMenu(new MenuItem[] { menuItem }); - Assert.Throws("value", () => menuItem.Index = value); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetIntTheoryData))] - public void MenuItem_Index_SetWithoutParent_Nop(int value) - { - var menuItem = new MenuItem - { - Index = value - }; - Assert.Equal(-1, menuItem.Index); - } - - public static IEnumerable IsParent_TestData() - { - yield return new object[] { new MenuItem { MdiList = true }, new SubMenu(), true }; - yield return new object[] { new MenuItem { MdiList = true }, null, false }; - yield return new object[] { new MenuItem { MdiList = false }, new SubMenu(), false }; - yield return new object[] { new MenuItem { MdiList = false }, new MenuItem(), false }; - yield return new object[] { new MenuItem { MdiList = false }, null, false }; - - foreach (bool mdiList in new bool[] { true, false }) - { - yield return new object[] { new MenuItem { MdiList = mdiList }, new MenuItem(), false }; - yield return new object[] { new MenuItem { MdiList = mdiList }, null, false }; - yield return new object[] { new MenuItem("text", new MenuItem[] { new MenuItem() }) { MdiList = mdiList }, null, true }; - } - - var disposedItem = new MenuItem("text", Array.Empty()); - disposedItem.Dispose(); - yield return new object[] { disposedItem, new SubMenu(), false }; - - yield return new object[] { new MenuItem { MdiList = true }, new MainMenu(), true }; - - var nonMdiForm = new Form { Menu = new MainMenu() }; - yield return new object[] { new MenuItem { MdiList = true }, nonMdiForm.Menu, true }; - - var formWithNoMdiChildren = new Form { Menu = new MainMenu() }; - formWithNoMdiChildren.Controls.Add(new MdiClient()); - yield return new object[] { new MenuItem { MdiList = true }, formWithNoMdiChildren.Menu, true }; - - var formWithMdiChildren = new Form { Menu = new MainMenu() }; - var client = new MdiClient(); - formWithMdiChildren.Controls.Add(client); - client.Controls.Add(new Form { MdiParent = formWithMdiChildren }); - yield return new object[] { new MenuItem { MdiList = true }, formWithMdiChildren.Menu, true }; - } - - [Theory] - [MemberData(nameof(IsParent_TestData))] - public void MenuItem_IsParent_HasParent_ReturnsExpected(MenuItem menuItem, Menu parent, bool expected) - { - parent?.MenuItems.Add(menuItem); - Assert.Equal(expected, menuItem.IsParent); - } - - [Fact] - public void MenuItem_IsParent_MdiSeparator_ReturnsFalse() - { - var parentForm = new Form { Menu = new MainMenu() }; - var parentFormClient = new MdiClient(); - parentForm.Controls.Add(parentFormClient); - parentFormClient.Controls.Add(new Form { MdiParent = parentForm }); - var menuItem = new SubMenuItem("text", new MenuItem[] { new MenuItem() }) { MdiList = true }; - var parentMenuItem = new MenuItem("parent", new MenuItem[] { menuItem }); - parentForm.Menu.MenuItems.Add(parentMenuItem); - - // Has a normal child and a MDI item. - menuItem.OnPopup(null); - Assert.True(menuItem.IsParent); - - // Has only MDI items. - menuItem.MenuItems.RemoveAt(0); - Assert.Equal("-", Assert.Single(menuItem.MenuItems.Cast()).Text); - Assert.True(menuItem.IsParent); - - // Parent form does not have MDI forms. - parentForm.IsMdiContainer = false; - Assert.Equal("-", Assert.Single(menuItem.MenuItems.Cast()).Text); - Assert.False(menuItem.IsParent); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetBoolTheoryData))] - public void MenuItem_MdiList_Set_GetReturnsExpected(bool value) - { - var menuItem = new MenuItem - { - MdiList = value - }; - Assert.Equal(value, menuItem.MdiList); - } - - [Fact] - public void MenuItem_MdiList_Disposed_ThrowsObjectDisposedException() - { - var menuItem = new MenuItem(); - menuItem.Dispose(); - Assert.Throws(() => menuItem.MdiList); - Assert.Throws(() => menuItem.MdiList = true); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetIntTheoryData))] - public void MenuItem_MergeOrder_Set_GetReturnsExpected(int value) - { - var menuItem = new MenuItem - { - MergeOrder = value - }; - Assert.Equal(value, menuItem.MergeOrder); - } - - [Fact] - public void MenuItem_MergeOrder_Disposed_ThrowsObjectDisposedException() - { - var menuItem = new MenuItem(); - menuItem.Dispose(); - Assert.Throws(() => menuItem.MergeOrder); - Assert.Throws(() => menuItem.MergeOrder = 1); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetEnumTypeTheoryData), typeof(MenuMerge))] - public void MenuItem_MergeType_Set_GetReturnsExpected(MenuMerge value) - { - var menuItem = new MenuItem - { - MergeType = value - }; - Assert.Equal(value, menuItem.MergeType); - } - - [Fact] - public void MenuItem_MergeType_Disposed_ThrowsObjectDisposedException() - { - var menuItem = new MenuItem(); - menuItem.Dispose(); - Assert.Throws(() => menuItem.MergeType); - Assert.Throws(() => menuItem.MergeType = MenuMerge.Add); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetEnumTypeTheoryDataInvalid), typeof(MenuMerge))] - public void MenuItem_MergeType_SetInvalid_ThrowsInvalidEnumArgumentException(MenuMerge value) - { - var menuItem = new MenuItem(); - Assert.Throws("value", () => menuItem.MergeType = value); - } - - [Theory] - [InlineData("", '\0')] - [InlineData("text", '\0')] - [InlineData("&&abc", '\0')] - [InlineData("&abc", 'A')] - [InlineData("&", '\0')] - [InlineData("&&", '\0')] - public void MenuItem_Mnemonic_Get_ReturnsExpected(string text, char expected) - { - var menuItem = new MenuItem(text); - Assert.Equal(expected, menuItem.Mnemonic); - } - - [Fact] - public void MenuItem_Mneumonic_Disposed_ThrowsObjectDisposedException() - { - var menuItem = new MenuItem(); - menuItem.Dispose(); - Assert.Throws(() => menuItem.Mnemonic); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetBoolTheoryData))] - public void MenuItem_OwnerDraw_Set_GetReturnsExpected(bool value) - { - var menuItem = new MenuItem - { - OwnerDraw = value - }; - Assert.Equal(value, menuItem.OwnerDraw); - } - - [Fact] - public void MenuItem_OwnerDraw_Disposed_ThrowsObjectDisposedException() - { - var menuItem = new MenuItem(); - menuItem.Dispose(); - Assert.Throws(() => menuItem.OwnerDraw); - Assert.Throws(() => menuItem.OwnerDraw = true); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetBoolTheoryData))] - public void MenuItem_RadioCheck_Set_GetReturnsExpected(bool value) - { - var menuItem = new MenuItem - { - RadioCheck = value - }; - Assert.Equal(value, menuItem.RadioCheck); - } - - [Fact] - public void MenuItem_RadioCheck_Disposed_ThrowsObjectDisposedException() - { - var menuItem = new MenuItem(); - menuItem.Dispose(); - Assert.Throws(() => menuItem.RadioCheck); - Assert.Throws(() => menuItem.RadioCheck = true); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetBoolTheoryData))] - public void MenuItem_ShowShortcut_Set_GetReturnsExpected(bool value) - { - var menuItem = new MenuItem - { - ShowShortcut = value - }; - Assert.Equal(value, menuItem.ShowShortcut); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetBoolTheoryData))] - public void MenuItem_ShowShortcut_SetCreated_GetReturnsExpected(bool value) - { - var menuItem = new MenuItem(); - using (var menu = new SubMenu(new MenuItem[] { menuItem })) - { - menuItem.ShowShortcut = value; - Assert.Equal(value, menuItem.ShowShortcut); - } - } - - [Fact] - public void MenuItem_ShowShortcut_Disposed_ThrowsObjectDisposedException() - { - var menuItem = new MenuItem(); - menuItem.Dispose(); - Assert.Throws(() => menuItem.ShowShortcut); - Assert.Throws(() => menuItem.ShowShortcut = true); - } - - [Theory] - [InlineData(Shortcut.None)] - [InlineData(Shortcut.Ctrl0)] - public void MenuItem_Shortcut_Set_GetReturnsExpected(Shortcut value) - { - var menuItem = new MenuItem - { - Shortcut = value - }; - Assert.Equal(value, menuItem.Shortcut); - } - - [Theory] - [InlineData(Shortcut.None)] - [InlineData(Shortcut.Ctrl0)] - public void MenuItem_Shortcut_SetCreated_GetReturnsExpected(Shortcut value) - { - var menuItem = new MenuItem(); - using (var menu = new SubMenu(new MenuItem[] { menuItem })) - { - menuItem.Shortcut = value; - Assert.Equal(value, menuItem.Shortcut); - } - } - - [Theory] - [InlineData((Shortcut)(Shortcut.None - 1))] - public void MenuItem_Shortcut_SetInvalid_ThrowsInvalidEnumArgumentException(Shortcut value) - { - var menuItem = new MenuItem(); - Assert.Throws("value", () => menuItem.Shortcut = value); - } - - [Fact] - public void MenuItem_Shortcut_Disposed_ThrowsObjectDisposedException() - { - var menuItem = new MenuItem(); - menuItem.Dispose(); - Assert.Throws(() => menuItem.Shortcut); - Assert.Throws(() => menuItem.Shortcut = Shortcut.None); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetStringNormalizedTheoryData))] - public void MenuItem_Text_Set_GetReturnsExpected(string value, string expected) - { - var menuItem = new MenuItem - { - Text = value - }; - Assert.Equal(expected, menuItem.Text); - - // Set same. - menuItem.Text = value; - Assert.Equal(expected, menuItem.Text); - } - - [Fact] - public void MenuItem_Text_Disposed_ThrowsObjectDisposedException() - { - var menuItem = new MenuItem(); - menuItem.Dispose(); - Assert.Throws(() => menuItem.Text); - Assert.Throws(() => menuItem.Text = string.Empty); - } - - [Fact] - public void MenuItem_Visible_Set_GetReturnsExpected() - { - var menuItem = new MenuItem - { - Visible = false - }; - Assert.False(menuItem.Visible); - - menuItem.Visible = true; - Assert.True(menuItem.Visible); - } - - [Fact] - public void MenuItem_Visible_SetWithMainMenuParent_GetReturnsExpected() - { - var menuItem = new MenuItem(); - var menu = new MainMenu(new MenuItem[] { menuItem }); - menuItem.Visible = false; - Assert.False(menuItem.Visible); - - menuItem.Visible = true; - Assert.True(menuItem.Visible); - } - - [Fact] - public void MenuItem_Visible_SetWithHandle_GetReturnsExpected() - { - var menuItem = new MenuItem(); - using (var menu = new SubMenu(new MenuItem[] { menuItem })) - { - Assert.NotEqual(IntPtr.Zero, menu.Handle); - menuItem.Visible = false; - Assert.False(menuItem.Visible); - - menuItem.Visible = true; - Assert.True(menuItem.Visible); - } - } - - [Fact] - public void MenuItem_Visible_Disposed_ThrowsObjectDisposedException() - { - var menuItem = new MenuItem(); - menuItem.Dispose(); - Assert.Throws(() => menuItem.Visible); - Assert.Throws(() => menuItem.Visible = true); - } - - [Fact] - public void MenuItem_MenuID_Get_ReturnsExpected() - { - var menuItem = new SubMenuItem(); - Assert.NotEqual(0, menuItem.MenuID); - } - - [Fact] - public void MenuItem_MenuID_Disposed_ThrowsObjectDisposedException() - { - var menuItem = new SubMenuItem(); - menuItem.Dispose(); - Assert.Throws(() => menuItem.MenuID); - } - - [Fact] - public void MenuItem_OnClick_Invoke_Success() - { - var menuItem = new SubMenuItem(); - - // No handler. - menuItem.OnClick(null); - - // Handler. - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Equal(menuItem, sender); - callCount++; - }; - - menuItem.Click += handler; - menuItem.OnClick(null); - Assert.Equal(1, callCount); - - // Should not call if the handler is removed. - menuItem.Click -= handler; - menuItem.OnClick(null); - Assert.Equal(1, callCount); - } - - [Fact] - public void MenuItem_OnClick_Disposed_ThrowsObjectDisposedException() - { - var menuItem = new SubMenuItem(); - menuItem.Dispose(); - Assert.Throws(() => menuItem.OnClick(null)); - } - - [Fact] - public void MenuItem_Click_Disposed_ThrowsObjectDisposedException() - { - var menuItem = new SubMenuItem(); - menuItem.Dispose(); - EventHandler handler = (sender, e) => { }; - Assert.Throws(() => menuItem.Click += handler); - Assert.Throws(() => menuItem.Click -= handler); - } - - [Fact] - public void MenuItem_OnDrawItem_Invoke_Success() - { - var menuItem = new SubMenuItem(); - - // No handler. - menuItem.OnDrawItem(null); - - // Handler. - int callCount = 0; - DrawItemEventHandler handler = (sender, e) => - { - Assert.Equal(menuItem, sender); - callCount++; - }; - - menuItem.DrawItem += handler; - menuItem.OnDrawItem(null); - Assert.Equal(1, callCount); - - // Should not call if the handler is removed. - menuItem.DrawItem -= handler; - menuItem.OnDrawItem(null); - Assert.Equal(1, callCount); - } - - [Fact] - public void MenuItem_OnDrawItem_Disposed_ThrowsObjectDisposedException() - { - var menuItem = new SubMenuItem(); - menuItem.Dispose(); - Assert.Throws(() => menuItem.OnDrawItem(null)); - } - - [Fact] - public void MenuItem_DrawItem_Disposed_ThrowsObjectDisposedException() - { - var menuItem = new SubMenuItem(); - menuItem.Dispose(); - DrawItemEventHandler handler = (sender, e) => { }; - Assert.Throws(() => menuItem.DrawItem += handler); - Assert.Throws(() => menuItem.DrawItem -= handler); - } - - [Fact] - public void MenuItem_OnInitMenuPopup_Invoke_Success() - { - var menuItem = new SubMenuItem(); - - // No handler. - menuItem.OnInitMenuPopup(null); - - // Handler. - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Equal(menuItem, sender); - callCount++; - }; - - menuItem.Popup += handler; - menuItem.OnInitMenuPopup(null); - Assert.Equal(1, callCount); - - // Should not call if the handler is removed. - menuItem.Popup -= handler; - menuItem.OnInitMenuPopup(null); - Assert.Equal(1, callCount); - } - - [Fact] - public void MenuItem_OnInitMenuPopup_Disposed_ThrowsObjectDisposedException() - { - var menuItem = new SubMenuItem(); - menuItem.Dispose(); - Assert.Throws(() => menuItem.OnInitMenuPopup(null)); - } - - [Fact] - public void MenuItem_OnMeasureItem_Invoke_Success() - { - var menuItem = new SubMenuItem(); - - // No handler. - menuItem.OnMeasureItem(null); - - // Handler. - int callCount = 0; - MeasureItemEventHandler handler = (sender, e) => - { - Assert.Equal(menuItem, sender); - callCount++; - }; - - menuItem.MeasureItem += handler; - menuItem.OnMeasureItem(null); - Assert.Equal(1, callCount); - - // Should not call if the handler is removed. - menuItem.MeasureItem -= handler; - menuItem.OnMeasureItem(null); - Assert.Equal(1, callCount); - } - - [Fact] - public void MenuItem_OnMeasureItem_Disposed_ThrowsObjectDisposedException() - { - var menuItem = new SubMenuItem(); - menuItem.Dispose(); - Assert.Throws(() => menuItem.OnMeasureItem(null)); - } - - [Fact] - public void MenuItem_MeasureItem_Disposed_ThrowsObjectDisposedException() - { - var menuItem = new SubMenuItem(); - menuItem.Dispose(); - MeasureItemEventHandler handler = (sender, e) => { }; - Assert.Throws(() => menuItem.MeasureItem += handler); - Assert.Throws(() => menuItem.MeasureItem -= handler); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetBoolTheoryData))] - public void MenuItem_OnPopup_Invoke_Success(bool mdiList) - { - var menuItem = new SubMenuItem - { - MdiList = mdiList - }; - - // No handler. - menuItem.OnPopup(null); - - // Handler. - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Equal(menuItem, sender); - callCount++; - }; - - menuItem.Popup += handler; - menuItem.OnPopup(null); - Assert.Equal(1, callCount); - - // Should not call if the handler is removed. - menuItem.Popup -= handler; - menuItem.OnPopup(null); - Assert.Equal(1, callCount); - } - - [Fact] - public void MenuItem_OnPopup_Disposed_ThrowsObjectDisposedException() - { - var menuItem = new SubMenuItem(); - menuItem.Dispose(); - Assert.Throws(() => menuItem.OnPopup(null)); - } - - [Fact] - public void MenuItem_Popup_Disposed_ThrowsObjectDisposedException() - { - var menuItem = new SubMenuItem(); - menuItem.Dispose(); - EventHandler handler = (sender, e) => { }; - Assert.Throws(() => menuItem.Popup += handler); - Assert.Throws(() => menuItem.Popup -= handler); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetBoolTheoryData))] - public void MenuItem_OnPopup_InvokeWithChildren_Success(bool mdiList) - { - var menuItem = new SubMenuItem("text", new MenuItem[] { new MenuItem("text") { MdiList = mdiList } }); - - // No handler. - menuItem.OnPopup(null); - - // Handler. - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Equal(menuItem, sender); - callCount++; - }; - - menuItem.Popup += handler; - menuItem.OnPopup(null); - Assert.Equal(1, callCount); - - // Should not call if the handler is removed. - menuItem.Popup -= handler; - menuItem.OnPopup(null); - Assert.Equal(1, callCount); - } - - [Fact] - public void MenuItem_OnPopup_MdiChildrenWithoutParent_DoesNotAddSeparator() - { - var menuItem = new SubMenuItem("text", new MenuItem[] { new MenuItem("child") }) { MdiList = true }; - - menuItem.OnPopup(null); - Assert.Equal(new string[] { "child" }, menuItem.MenuItems.Cast().Select(m => m.Text)); - - // Calling OnPopup again should not add duplicate items. - menuItem.OnPopup(null); - Assert.Equal(new string[] { "child" }, menuItem.MenuItems.Cast().Select(m => m.Text)); - } - - public static IEnumerable OnPopup_MdiChildren_TestData() - { - var formWithNoMdiChildren = new Form { Menu = new MainMenu() }; - formWithNoMdiChildren.Controls.Add(new MdiClient()); - yield return new object[] { new SubMenuItem("text", new MenuItem[] { new MenuItem("child") }) { MdiList = true }, new MainMenu(), new string[] { "child" } }; - yield return new object[] { new SubMenuItem("text") { MdiList = true }, formWithNoMdiChildren.Menu, Array.Empty() }; - - var formWithNoVisibleMdiChildren = new Form { Menu = new MainMenu() }; - var formWithNoVisibleMdiChildrenClient = new MdiClient(); - formWithNoVisibleMdiChildren.Controls.Add(formWithNoVisibleMdiChildrenClient); - formWithNoVisibleMdiChildrenClient.Controls.Add(new Form { MdiParent = formWithNoVisibleMdiChildren }); - yield return new object[] { new SubMenuItem("text", new MenuItem[] { new MenuItem("child") }) { MdiList = true }, formWithNoVisibleMdiChildren.Menu, new string[] { "child", "-" } }; - yield return new object[] { new SubMenuItem("text"), formWithNoVisibleMdiChildren.Menu, Array.Empty() }; - - var formWithMdiChildren = new Form { Menu = new MainMenu(), Visible = true }; - var formWithMdiChildrenClient = new MdiClient(); - formWithMdiChildren.Controls.Add(formWithMdiChildrenClient); - formWithMdiChildrenClient.Controls.Add(new Form { MdiParent = formWithMdiChildren, Visible = true, Text = "Form" }); - yield return new object[] { new SubMenuItem("text", new MenuItem[] { new MenuItem("child") }) { MdiList = true }, formWithMdiChildren.Menu, new string[] { "child", "-", "&1 Form", "&2 Form" } }; - - var formWithManyMdiChildren = new Form { Menu = new MainMenu(), Visible = true }; - var formWithManyMdiChildrenClient = new MdiClient(); - formWithManyMdiChildren.Controls.Add(formWithManyMdiChildrenClient); - formWithManyMdiChildrenClient.Controls.Add(new Form { MdiParent = formWithManyMdiChildren, Visible = true, Text = "Form1" }); - formWithManyMdiChildrenClient.Controls.Add(new Form { MdiParent = formWithManyMdiChildren, Visible = true, Text = "Form2" }); - formWithManyMdiChildrenClient.Controls.Add(new Form { MdiParent = formWithManyMdiChildren, Visible = true, Text = "Form3" }); - formWithManyMdiChildrenClient.Controls.Add(new Form { MdiParent = formWithManyMdiChildren, Visible = true, Text = "Form4" }); - formWithManyMdiChildrenClient.Controls.Add(new Form { MdiParent = formWithManyMdiChildren, Visible = true, Text = "Form5" }); - formWithManyMdiChildrenClient.Controls.Add(new Form { MdiParent = formWithManyMdiChildren, Visible = true, Text = "Form6" }); - formWithManyMdiChildrenClient.Controls.Add(new Form { MdiParent = formWithManyMdiChildren, Visible = true, Text = "Form7" }); - formWithManyMdiChildrenClient.Controls.Add(new Form { MdiParent = formWithManyMdiChildren, Visible = true, Text = "Form8" }); - formWithManyMdiChildrenClient.Controls.Add(new Form { MdiParent = formWithManyMdiChildren, Visible = true, Text = "Form9" }); - formWithManyMdiChildrenClient.Controls.Add(new Form { MdiParent = formWithManyMdiChildren, Visible = true, Text = "Form10" }); - yield return new object[] { new SubMenuItem("text", new MenuItem[] { new MenuItem("child") }) { MdiList = true }, formWithManyMdiChildren.Menu, new string[] { "child", "-", "&1 Form1", "&2 Form1", "&3 Form2", "&4 Form2", "&5 Form3", "&6 Form3", "&7 Form4", "&8 Form4", "&9 Form10", "&10 Form10", "&More Windows..." } }; - - var formWithActiveMdiChildren = new SubForm { Menu = new MainMenu(), Visible = true }; - var formWithActiveMdiChildrenClient = new MdiClient(); - formWithActiveMdiChildren.Controls.Add(formWithActiveMdiChildrenClient); - var activeForm1 = new Form { MdiParent = formWithActiveMdiChildren, Visible = true, Text = "Form2" }; - formWithActiveMdiChildrenClient.Controls.Add(new Form { MdiParent = formWithActiveMdiChildren, Visible = true, Text = "Form1" }); - formWithActiveMdiChildrenClient.Controls.Add(activeForm1); - formWithActiveMdiChildren.ActivateMdiChild(activeForm1); - yield return new object[] { new SubMenuItem("text", new MenuItem[] { new MenuItem("child") }) { MdiList = true }, formWithActiveMdiChildren.Menu, new string[] { "child", "-", "&1 Form2", "&2 Form1", "&3 Form1", "&4 Form2" } }; - - var formWithActiveManyMdiChildren = new SubForm { Menu = new MainMenu(), Visible = true }; - var formWithActiveManyMdiChildrenClient = new MdiClient(); - formWithActiveManyMdiChildren.Controls.Add(formWithActiveManyMdiChildrenClient); - var activeForm2 = new Form { MdiParent = formWithActiveManyMdiChildren, Visible = true, Text = "Form11" }; - formWithActiveManyMdiChildrenClient.Controls.Add(new Form { MdiParent = formWithActiveManyMdiChildren, Visible = true, Text = "Form1" }); - formWithActiveManyMdiChildrenClient.Controls.Add(new Form { MdiParent = formWithActiveManyMdiChildren, Visible = true, Text = "Form2" }); - formWithActiveManyMdiChildrenClient.Controls.Add(new Form { MdiParent = formWithActiveManyMdiChildren, Visible = true, Text = "Form3" }); - formWithActiveManyMdiChildrenClient.Controls.Add(new Form { MdiParent = formWithActiveManyMdiChildren, Visible = true, Text = "Form4" }); - formWithActiveManyMdiChildrenClient.Controls.Add(new Form { MdiParent = formWithActiveManyMdiChildren, Visible = true, Text = "Form5" }); - formWithActiveManyMdiChildrenClient.Controls.Add(new Form { MdiParent = formWithActiveManyMdiChildren, Visible = true, Text = "Form6" }); - formWithActiveManyMdiChildrenClient.Controls.Add(new Form { MdiParent = formWithActiveManyMdiChildren, Visible = true, Text = "Form7" }); - formWithActiveManyMdiChildrenClient.Controls.Add(new Form { MdiParent = formWithActiveManyMdiChildren, Visible = true, Text = "Form8" }); - formWithActiveManyMdiChildrenClient.Controls.Add(new Form { MdiParent = formWithActiveManyMdiChildren, Visible = true, Text = "Form9" }); - formWithActiveManyMdiChildrenClient.Controls.Add(new Form { MdiParent = formWithActiveManyMdiChildren, Visible = true, Text = "Form10" }); - formWithActiveManyMdiChildrenClient.Controls.Add(activeForm2); - formWithActiveManyMdiChildren.ActivateMdiChild(activeForm2); - yield return new object[] { new SubMenuItem("text", new MenuItem[] { new MenuItem("child") }) { MdiList = true }, formWithActiveManyMdiChildren.Menu, new string[] { "child", "-", "&1 Form11", "&2 Form1", "&3 Form1", "&4 Form2", "&5 Form2", "&6 Form3", "&7 Form3", "&8 Form4", "&9 Form4", "&10 Form11", "&More Windows..." } }; - } - - [Theory] - [MemberData(nameof(OnPopup_MdiChildren_TestData))] - public void MenuItem_OnPopup_MdiChildren_AddsSeparator(SubMenuItem menuItem, Menu parent, string[] expectedItems) - { - try - { - parent.MenuItems.Add(menuItem); - - menuItem.OnPopup(null); - Assert.Equal(expectedItems, menuItem.MenuItems.Cast().Select(m => m.Text)); - - // Calling OnPopup again should not add duplicate items. - menuItem.OnPopup(null); - Assert.Equal(expectedItems, menuItem.MenuItems.Cast().Select(m => m.Text)); - } - catch - { - string expected = "Expected: " + string.Join(", ", expectedItems.Select(i => "\"" + i + "\"")); - string actual = "Actual: " + string.Join(", ", menuItem.MenuItems.Cast().Select(m => m.Text).Select(i => "\"" + i + "\"")); - throw new Exception(expected + Environment.NewLine + actual); - } - } - - [Fact] - public void MenuItem_PerformClick_MdiSeparator_Nop() - { - var parentForm = new Form { Menu = new MainMenu() }; - var parentFormClient = new MdiClient(); - parentForm.Controls.Add(parentFormClient); - parentFormClient.Controls.Add(new Form { MdiParent = parentForm }); - var menuItem = new SubMenuItem("text", new MenuItem[] { new MenuItem() }) { MdiList = true }; - parentForm.Menu.MenuItems.Add(menuItem); - menuItem.OnPopup(null); - - MenuItem separator = menuItem.MenuItems[1]; - Assert.Equal("-", separator.Text); - separator.PerformClick(); - } - - [Fact] - public void MenuItem_OnSelect_Invoke_Success() - { - var menuItem = new SubMenuItem(); - - // No handler. - menuItem.OnSelect(null); - - // Handler. - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Equal(menuItem, sender); - callCount++; - }; - - menuItem.Select += handler; - menuItem.OnSelect(null); - Assert.Equal(1, callCount); - - // Should not call if the handler is removed. - menuItem.Select -= handler; - menuItem.OnSelect(null); - Assert.Equal(1, callCount); - } - - [Fact] - public void MenuItem_OnSelect_Disposed_ThrowsObjectDisposedException() - { - var menuItem = new SubMenuItem(); - menuItem.Dispose(); - Assert.Throws(() => menuItem.OnSelect(null)); - } - - [Fact] - public void MenuItem_Select_Disposed_ThrowsObjectDisposedException() - { - var menuItem = new SubMenuItem(); - menuItem.Dispose(); - EventHandler handler = (sender, e) => { }; - Assert.Throws(() => menuItem.Select += handler); - Assert.Throws(() => menuItem.Select -= handler); - } - - [Fact] - public void MenuItem_PerformClick_Invoke_Success() - { - var menuItem = new SubMenuItem(); - - // No handler. - menuItem.PerformClick(); - - // Handler. - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Equal(EventArgs.Empty, e); - Assert.Equal(menuItem, sender); - callCount++; - }; - - menuItem.Click += handler; - menuItem.PerformClick(); - Assert.Equal(1, callCount); - - // Should not call if the handler is removed. - menuItem.Click -= handler; - menuItem.PerformClick(); - Assert.Equal(1, callCount); - } - - [Fact] - public void MenuItem_PerformSelect_Invoke_Success() - { - var menuItem = new SubMenuItem(); - - // No handler. - menuItem.PerformSelect(); - - // Handler. - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Equal(EventArgs.Empty, e); - Assert.Equal(menuItem, sender); - callCount++; - }; - - menuItem.Select += handler; - menuItem.PerformSelect(); - Assert.Equal(1, callCount); - - // Should not call if the handler is removed. - menuItem.Select -= handler; - menuItem.PerformSelect(); - Assert.Equal(1, callCount); - } - - public static IEnumerable CloneMenu_TestData() - { - yield return new object[] { Array.Empty() }; - yield return new object[] { new MenuItem[] { new MenuItem("text") } }; - } - - [Theory] - [MemberData(nameof(CloneMenu_TestData))] - public void MenuItem_CloneMenu_InvokeNew_Success(MenuItem[] items) - { - var source = new MenuItem("text", items) - { - BarBreak = true, - Break = true, - Checked = items.Length == 0, - Enabled = false, - MdiList = true, - MergeOrder = -1, - MergeType = MenuMerge.Remove, - Name = "name", - OwnerDraw = true, - RadioCheck = true, - ShowShortcut = false, - Shortcut = Shortcut.CtrlA, - Site = Mock.Of(), - Tag = "tag", - Visible = false - }; - var menu = new SubMenu(new MenuItem[] { new MenuItem("parent", new MenuItem[] { source }) }); - MenuItem menuItem = source.CloneMenu(); - Assert.NotSame(source, menuItem); - - Assert.Equal(source.BarBreak, menuItem.BarBreak); - Assert.Equal(source.Break, menuItem.Break); - Assert.Equal(source.Checked, menuItem.Checked); - Assert.Equal(source.DefaultItem, menuItem.DefaultItem); - Assert.Equal(source.Enabled, menuItem.Enabled); - Assert.Equal(-1, menuItem.Index); - Assert.Equal(source.IsParent, menuItem.IsParent); - Assert.Equal(source.MdiList, menuItem.MdiList); - MenuTests.AssertEqualMenuItems(items, menuItem.MenuItems.Cast().ToArray()); - for (int i = 0; i < items.Length; i++) - { - Assert.Equal(i, menuItem.MenuItems[i].Index); - Assert.Equal(menuItem, menuItem.MenuItems[i].Parent); - } - Assert.Equal(source.MergeOrder, menuItem.MergeOrder); - Assert.Equal(source.MergeType, menuItem.MergeType); - Assert.Equal(source.Mnemonic, menuItem.Mnemonic); - Assert.Equal(source.OwnerDraw, menuItem.OwnerDraw); - Assert.Null(menuItem.Parent); - Assert.Equal(source.RadioCheck, menuItem.RadioCheck); - Assert.Equal(source.ShowShortcut, menuItem.ShowShortcut); - Assert.Equal(source.Shortcut, menuItem.Shortcut); - Assert.Equal(source.Visible, menuItem.Visible); - Assert.Empty(menuItem.Name); - Assert.Null(menuItem.Site); - Assert.Null(menuItem.Container); - Assert.Null(menuItem.Tag); - Assert.Equal(source.Text, menuItem.Text); - } - - [Theory] - [MemberData(nameof(CloneMenu_TestData))] - public void MenuItem_CloneMenu_InvokeExisting_Success(MenuItem[] items) - { - var source = new MenuItem("text", items) - { - BarBreak = true, - Break = true, - Checked = items.Length == 0, - Enabled = false, - MdiList = true, - MergeOrder = -1, - MergeType = MenuMerge.Remove, - OwnerDraw = true, - Site = Mock.Of(), - Tag = "tag" - }; - var menu = new SubMenu(new MenuItem[] { new MenuItem("parent", new MenuItem[] { source }) }); - var menuItem = new SubMenuItem(); - menuItem.CloneMenu(source); - - Assert.False(menuItem.BarBreak); - Assert.False(menuItem.Break); - Assert.False(menuItem.Checked); - Assert.False(menuItem.DefaultItem); - Assert.True(menuItem.Enabled); - Assert.Equal(-1, menuItem.Index); - Assert.Equal(source.IsParent, menuItem.IsParent); - Assert.False(menuItem.MdiList); - MenuTests.AssertEqualMenuItems(items, menuItem.MenuItems.Cast().ToArray()); - for (int i = 0; i < items.Length; i++) - { - Assert.Equal(i, menuItem.MenuItems[i].Index); - Assert.Equal(menuItem, menuItem.MenuItems[i].Parent); - } - Assert.Equal(0, menuItem.MergeOrder); - Assert.Equal(MenuMerge.Add, menuItem.MergeType); - Assert.Equal('\0', menuItem.Mnemonic); - Assert.False(menuItem.OwnerDraw); - Assert.Null(menuItem.Parent); - Assert.False(menuItem.RadioCheck); - Assert.True(menuItem.ShowShortcut); - Assert.Equal(Shortcut.None, menuItem.Shortcut); - Assert.True(menuItem.Visible); - Assert.Empty(menuItem.Name); - Assert.Null(menuItem.Site); - Assert.Null(menuItem.Container); - Assert.Null(menuItem.Tag); - Assert.Empty(menuItem.Text); - } - - [Fact] - public void MenuItem_CloneMenu_NullMenuSource_ThrowsArgumentNullException() - { - var menu = new SubMenuItem("text"); - Assert.Throws("menuSrc", () => menu.CloneMenu(null)); - } - - [Theory] - [MemberData(nameof(CloneMenu_TestData))] - public void MenuItem_MergeMenu_InvokeNew_Success(MenuItem[] items) - { - var source = new MenuItem("text", items) - { - BarBreak = true, - Break = true, - Checked = items.Length == 0, - Enabled = false, - MdiList = true, - MergeOrder = -1, - MergeType = MenuMerge.Remove, - Name = "name", - OwnerDraw = true, - RadioCheck = true, - ShowShortcut = false, - Shortcut = Shortcut.CtrlA, - Site = Mock.Of(), - Tag = "tag", - Visible = false - }; - var menu = new SubMenu(new MenuItem[] { new MenuItem("parent", new MenuItem[] { source }) }); - MenuItem menuItem = source.MergeMenu(); - Assert.NotSame(source, menuItem); - - Assert.Equal(source.BarBreak, menuItem.BarBreak); - Assert.Equal(source.Break, menuItem.Break); - Assert.Equal(source.Checked, menuItem.Checked); - Assert.Equal(source.DefaultItem, menuItem.DefaultItem); - Assert.Equal(source.Enabled, menuItem.Enabled); - Assert.Equal(-1, menuItem.Index); - Assert.Equal(source.IsParent, menuItem.IsParent); - Assert.Equal(source.MdiList, menuItem.MdiList); - MenuTests.AssertEqualMenuItems(items, menuItem.MenuItems.Cast().ToArray()); - for (int i = 0; i < items.Length; i++) - { - Assert.Equal(i, menuItem.MenuItems[i].Index); - Assert.Equal(menuItem, menuItem.MenuItems[i].Parent); - } - Assert.Equal(source.MergeOrder, menuItem.MergeOrder); - Assert.Equal(source.MergeType, menuItem.MergeType); - Assert.Equal(source.Mnemonic, menuItem.Mnemonic); - Assert.Equal(source.OwnerDraw, menuItem.OwnerDraw); - Assert.Null(menuItem.Parent); - Assert.Equal(source.RadioCheck, menuItem.RadioCheck); - Assert.Equal(source.ShowShortcut, menuItem.ShowShortcut); - Assert.Equal(source.Shortcut, menuItem.Shortcut); - Assert.Equal(source.Visible, menuItem.Visible); - Assert.Empty(menuItem.Name); - Assert.Null(menuItem.Site); - Assert.Null(menuItem.Container); - Assert.Null(menuItem.Tag); - Assert.Equal(source.Text, menuItem.Text); - } - - [Theory] - [MemberData(nameof(CloneMenu_TestData))] - public void MenuItem_MergeMenu_InvokeExisting_Success(MenuItem[] items) - { - var source = new MenuItem("text", items) - { - BarBreak = true, - Break = true, - Checked = items.Length == 0, - Enabled = false, - MdiList = true, - MergeOrder = -1, - MergeType = MenuMerge.Remove, - Name = "name", - OwnerDraw = true, - RadioCheck = true, - ShowShortcut = false, - Shortcut = Shortcut.CtrlA, - Site = Mock.Of(), - Tag = "tag", - Visible = false - }; - var menu = new SubMenu(new MenuItem[] { new MenuItem("parent", new MenuItem[] { source }) }); - var menuItem = new MenuItem(); - menuItem.MergeMenu(source); - - Assert.Equal(source.BarBreak, menuItem.BarBreak); - Assert.Equal(source.Break, menuItem.Break); - Assert.Equal(source.Checked, menuItem.Checked); - Assert.Equal(source.DefaultItem, menuItem.DefaultItem); - Assert.Equal(source.Enabled, menuItem.Enabled); - Assert.Equal(-1, menuItem.Index); - Assert.Equal(source.IsParent, menuItem.IsParent); - Assert.Equal(source.MdiList, menuItem.MdiList); - MenuTests.AssertEqualMenuItems(items, menuItem.MenuItems.Cast().ToArray()); - for (int i = 0; i < items.Length; i++) - { - Assert.Equal(i, menuItem.MenuItems[i].Index); - Assert.Equal(menuItem, menuItem.MenuItems[i].Parent); - } - Assert.Equal(source.MergeOrder, menuItem.MergeOrder); - Assert.Equal(source.MergeType, menuItem.MergeType); - Assert.Equal(source.Mnemonic, menuItem.Mnemonic); - Assert.Equal(source.OwnerDraw, menuItem.OwnerDraw); - Assert.Null(menuItem.Parent); - Assert.Equal(source.RadioCheck, menuItem.RadioCheck); - Assert.Equal(source.ShowShortcut, menuItem.ShowShortcut); - Assert.Equal(source.Shortcut, menuItem.Shortcut); - Assert.Equal(source.Visible, menuItem.Visible); - Assert.Empty(menuItem.Name); - Assert.Null(menuItem.Site); - Assert.Null(menuItem.Container); - Assert.Null(menuItem.Tag); - Assert.Equal(source.Text, menuItem.Text); - } - - [Fact] - public void MenuItem_MergeMenu_OnClick_Success() - { - var source = new SubMenuItem(); - - int sourceCallCount = 0; - source.Click += (sender, e) => - { - sourceCallCount++; - Assert.Equal(source, sender); - Assert.Equal(EventArgs.Empty, e); - }; - - SubMenuItem destination = Assert.IsType(source.MergeMenu()); - int destinationCallCount = 0; - destination.Click += (sender, e) => - { - destinationCallCount++; - Assert.Equal(source, sender); - Assert.Equal(EventArgs.Empty, e); - }; - - destination.OnClick(EventArgs.Empty); - Assert.Equal(1, sourceCallCount); - Assert.Equal(1, destinationCallCount); - - source.OnClick(EventArgs.Empty); - Assert.Equal(2, sourceCallCount); - Assert.Equal(2, destinationCallCount); - } - - [Fact] - public void MenuItem_MergeMenu_OnDrawItem_Success() - { - var source = new SubMenuItem(); - - int sourceCallCount = 0; - source.DrawItem += (sender, e) => - { - sourceCallCount++; - Assert.Equal(source, sender); - Assert.Null(e); - }; - - SubMenuItem destination = Assert.IsType(source.MergeMenu()); - int destinationCallCount = 0; - destination.DrawItem += (sender, e) => - { - destinationCallCount++; - Assert.Equal(source, sender); - Assert.Null(e); - }; - - destination.OnDrawItem(null); - Assert.Equal(1, sourceCallCount); - Assert.Equal(1, destinationCallCount); - - source.OnDrawItem(null); - Assert.Equal(2, sourceCallCount); - Assert.Equal(2, destinationCallCount); - } - - [Fact] - public void MenuItem_MergeMenu_OnMeasureItem_Success() - { - var source = new SubMenuItem(); - - int sourceCallCount = 0; - source.MeasureItem += (sender, e) => - { - sourceCallCount++; - Assert.Equal(source, sender); - Assert.Null(e); - }; - - SubMenuItem destination = Assert.IsType(source.MergeMenu()); - int destinationCallCount = 0; - destination.MeasureItem += (sender, e) => - { - destinationCallCount++; - Assert.Equal(source, sender); - Assert.Null(e); - }; - - destination.OnMeasureItem(null); - Assert.Equal(1, sourceCallCount); - Assert.Equal(1, destinationCallCount); - - source.OnMeasureItem(null); - Assert.Equal(2, sourceCallCount); - Assert.Equal(2, destinationCallCount); - } - - [Fact] - public void MenuItem_MergeMenu_OnPopup_Success() - { - var source = new SubMenuItem(); - - int sourceCallCount = 0; - source.Popup += (sender, e) => - { - sourceCallCount++; - Assert.Equal(source, sender); - Assert.Equal(EventArgs.Empty, e); - }; - - SubMenuItem destination = Assert.IsType(source.MergeMenu()); - int destinationCallCount = 0; - destination.Popup += (sender, e) => - { - destinationCallCount++; - Assert.Equal(source, sender); - Assert.Equal(EventArgs.Empty, e); - }; - - destination.OnPopup(EventArgs.Empty); - Assert.Equal(1, sourceCallCount); - Assert.Equal(1, destinationCallCount); - - source.OnPopup(EventArgs.Empty); - Assert.Equal(2, sourceCallCount); - Assert.Equal(2, destinationCallCount); - } - - [Fact] - public void MenuItem_MergeMenu_OnSelect_Success() - { - var source = new SubMenuItem(); - - int sourceCallCount = 0; - source.Select += (sender, e) => - { - sourceCallCount++; - Assert.Equal(source, sender); - Assert.Equal(EventArgs.Empty, e); - }; - - SubMenuItem destination = Assert.IsType(source.MergeMenu()); - int destinationCallCount = 0; - destination.Select += (sender, e) => - { - destinationCallCount++; - Assert.Equal(source, sender); - Assert.Equal(EventArgs.Empty, e); - }; - - destination.OnSelect(EventArgs.Empty); - Assert.Equal(1, sourceCallCount); - Assert.Equal(1, destinationCallCount); - - source.OnSelect(EventArgs.Empty); - Assert.Equal(2, sourceCallCount); - Assert.Equal(2, destinationCallCount); - } - - [Fact] - public void MenuItem_MergeMenu_NullMenuSource_ThrowsArgumentNullException() - { - var menu = new MenuItem("text"); - Assert.Throws("menuSrc", () => menu.MergeMenu(null)); - } - - [Fact] - public void MenuItem_MergeMenu_Disposed_ThrowsObjectDisposedException() - { - var menuItem = new MenuItem(); - menuItem.Dispose(); - Assert.Throws(() => menuItem.MergeMenu()); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetStringWithNullTheoryData))] - public void MenuItem_ToString_Invoke_ReturnsExpected(string text) - { - var menuItem = new MenuItem - { - Text = text - }; - Assert.Equal("System.Windows.Forms.MenuItem, Items.Count: 0, Text: " + text, menuItem.ToString()); - } - - [Fact] - public void MenuItem_Dispose_NoParentOrChildren_Success() - { - var menuItem = new MenuItem("text", Array.Empty()); - menuItem.Dispose(); - menuItem.Dispose(); - } - - [Fact] - public void MenuItem_Dispose_NoParent_Success() - { - var childMenuItem = new MenuItem(); - var menuItem = new MenuItem("text", new MenuItem[] { childMenuItem }); - menuItem.Dispose(); - Assert.Null(childMenuItem.Parent); - Assert.Empty(menuItem.MenuItems); - - menuItem.Dispose(); - Assert.Empty(menuItem.MenuItems); - } - - [Fact] - public void MenuItem_Dispose_HasParent_Success() - { - var childMenuItem = new MenuItem(); - var menuItem = new MenuItem("text", new MenuItem[] { childMenuItem }); - childMenuItem.Dispose(); - Assert.Null(childMenuItem.Parent); - Assert.Empty(menuItem.MenuItems); - - childMenuItem.Dispose(); - Assert.Empty(menuItem.MenuItems); - } - - [Fact] - public void MenuItem_Dispose_HasMenuId_Success() - { - var menuItem = new SubMenuItem(); - Assert.NotEqual(0, menuItem.MenuID); - - menuItem.Dispose(); - Assert.Throws(() => menuItem.MenuID); - - menuItem.Dispose(); - Assert.Throws(() => menuItem.MenuID); - } - - public class SubMenuItem : MenuItem - { - public SubMenuItem() - { - } - - public SubMenuItem(string text) : base(text) - { - } - - public SubMenuItem(string text, EventHandler onClick) : base(text, onClick) - { - } - - public SubMenuItem(string text, MenuItem[] items) : base(text, items) - { - } - - public SubMenuItem(string text, EventHandler onClick, Shortcut shortcut) : base(text, onClick, shortcut) - { - } - - public SubMenuItem(MenuMerge mergeType, int mergeOrder, Shortcut shortcut, string text, EventHandler onClick, EventHandler onPopup, EventHandler onSelect, MenuItem[] items) : base(mergeType, mergeOrder, shortcut, text, onClick, onPopup, onSelect, items) - { - } - - public new int MenuID => base.MenuID; - - public new void OnClick(EventArgs e) => base.OnClick(e); - - public new void OnDrawItem(DrawItemEventArgs e) => base.OnDrawItem(e); - - public new void OnInitMenuPopup(EventArgs e) => base.OnInitMenuPopup(e); - - public new void OnMeasureItem(MeasureItemEventArgs e) => base.OnMeasureItem(e); - - public new void OnPopup(EventArgs e) => base.OnPopup(e); - - public new void OnSelect(EventArgs e) => base.OnSelect(e); - - public new void CloneMenu(Menu menuSrc) => base.CloneMenu(menuSrc); - } - - private class SubMenu : Menu - { - public SubMenu(params MenuItem[] items) : base(items) - { - } - } - - private class SubForm : Form - { - public new void ActivateMdiChild(Form form) => base.ActivateMdiChild(form); - } - } -} diff --git a/src/System.Windows.Forms/tests/UnitTests/MenuTests.cs b/src/System.Windows.Forms/tests/UnitTests/MenuTests.cs deleted file mode 100644 index 9eff1938932..00000000000 --- a/src/System.Windows.Forms/tests/UnitTests/MenuTests.cs +++ /dev/null @@ -1,738 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Collections.Generic; -using System.ComponentModel; -using System.Linq; -using Moq; -using WinForms.Common.Tests; -using Xunit; - -namespace System.Windows.Forms.Tests -{ - public class MenuTests - { - public static IEnumerable Ctor_MenuItemArray_TestData() - { - yield return new object[] { null, false }; - yield return new object[] { Array.Empty(), false }; - yield return new object[] { new MenuItem[] { new MenuItem() }, true }; - } - - [Theory] - [MemberData(nameof(Ctor_MenuItemArray_TestData))] - public void Menu_Ctor_MenuItemArray(MenuItem[] items, bool expectedIsParent) - { - var menu = new SubMenu(items); - Assert.Equal(items ?? Array.Empty(), menu.MenuItems.Cast()); - for (int i = 0; i < (items?.Length ?? 0); i++) - { - Assert.Equal(i, menu.MenuItems[i].Index); - Assert.Equal(menu, menu.MenuItems[i].Parent); - } - Assert.Equal(expectedIsParent, menu.IsParent); - Assert.Empty(menu.Name); - Assert.Null(menu.Site); - Assert.Null(menu.Container); - Assert.Null(menu.Tag); - } - - [Fact] - public void Menu_Ctor_NullItemInMenuItemArray_ThrowsArgumentNullException() - { - Assert.Throws("item", () => new SubMenu(new MenuItem[] { null })); - } - - [Fact] - public void Menu_FindHandle_Get_ReturnsExpected() - { - Assert.Equal(0, Menu.FindHandle); - } - - [Fact] - public void Menu_FindShortcut_Get_ReturnsExpected() - { - Assert.Equal(1, Menu.FindShortcut); - } - - public static IEnumerable HandleMenuItems_TestData() - { - yield return new object[] { Array.Empty() }; - yield return new object[] - { - new MenuItem[] - { - // Not visible. - new MenuItem { Visible = false }, - - // Has state. - new MenuItem { BarBreak = true, Break = true, Checked = true, DefaultItem = true, Enabled = false }, - - // Has shortcut. - new MenuItem { Shortcut = Shortcut.CtrlA }, - - // Has no shortcut. - new MenuItem { ShowShortcut = false, Shortcut = Shortcut.CtrlA }, - - // Has owner draw. - new MenuItem("text") { OwnerDraw = true }, - - // Has children. - new MenuItem("text", new MenuItem[] { new MenuItem("child") }), - } - }; - } - - [Theory] - [MemberData(nameof(HandleMenuItems_TestData))] - public void Menu_Handle_Get_ReturnsExpected(MenuItem[] items) - { - using (var menu = new SubMenu(items)) - { - Assert.NotEqual(IntPtr.Zero, menu.Handle); - Assert.Equal(menu.Handle, menu.Handle); - } - } - - [Fact] - public void Menu_Handle_GetWithDashTextInNormalMenu_ReturnsExpected() - { - var menuItem = new MenuItem("-"); - using (var menu = new SubMenu(new MenuItem[] { menuItem })) - { - Assert.NotEqual(IntPtr.Zero, menu.Handle); - Assert.Equal(menu.Handle, menu.Handle); - - // Does not affect the text. - Assert.Equal("-", menuItem.Text); - } - } - - [Fact] - public void Menu_Handle_GetWithDashTextInMainMenu_ReturnsExpected() - { - var menuItem = new MenuItem("-"); - using (var menu = new MainMenu(new MenuItem[] { menuItem })) - { - Assert.NotEqual(IntPtr.Zero, menu.Handle); - Assert.Equal(menu.Handle, menu.Handle); - - // Sets the separator to a space. - Assert.Equal(" ", menuItem.Text); - } - } - - [Fact] - public void Menu_Handle_GetWithRightToLeftItem_ReturnsExpected() - { - using (var menu = new ContextMenu(new MenuItem[] { new MenuItem("text") })) - { - menu.RightToLeft = RightToLeft.Yes; - Assert.NotEqual(IntPtr.Zero, menu.Handle); - Assert.Equal(menu.Handle, menu.Handle); - } - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetStringNormalizedTheoryData))] - public void Menu_Name_GetWithSite_ReturnsExpected(string name, string expected) - { - var menu = new SubMenu(Array.Empty()) - { - Site = Mock.Of(s => s.Name == name) - }; - Assert.Equal(expected, menu.Name); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetStringNormalizedTheoryData))] - public void Menu_Name_SetWithoutSite_GetReturnsExpected(string value, string expected) - { - var menu = new SubMenu(Array.Empty()) - { - Name = value - }; - Assert.Equal(expected, menu.Name); - - // Set same. - menu.Name = value; - Assert.Equal(expected, menu.Name); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetStringNormalizedTheoryData))] - public void Menu_Name_SetWithSite_GetReturnsExpected(string value, string expected) - { - var menu = new SubMenu(Array.Empty()) - { - Site = Mock.Of(), - Name = value - }; - Assert.Equal(expected, menu.Name); - Assert.Equal(value?.Length == 0 ? null : value, menu.Site.Name); - } - - public static IEnumerable MdiListItem_TestData() - { - var listItem1 = new MenuItem { MdiList = true }; - var listItem2 = new MenuItem { MdiList = true }; - - yield return new object[] { Array.Empty(), null }; - yield return new object[] { new MenuItem[] { listItem1 }, listItem1 }; - yield return new object[] { new MenuItem[] { new MenuItem() }, null }; - yield return new object[] { new MenuItem[] { new MenuItem("parent", new MenuItem[] { listItem2 }) }, listItem2 }; - yield return new object[] { new MenuItem[] { new MenuItem("parent", new MenuItem[] { new MenuItem() }) }, null }; - } - - [Theory] - [MemberData(nameof(MdiListItem_TestData))] - public void Menu_MdiListItem_Get_ReturnsExpected(MenuItem[] items, MenuItem expected) - { - var menu = new SubMenu(items); - Assert.Equal(expected, menu.MdiListItem); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetStringWithNullTheoryData))] - public void Menu_Tag_Set_GetReturnsExpected(object value) - { - var menu = new SubMenu(Array.Empty()) - { - Tag = value - }; - Assert.Same(value, menu.Tag); - - // Set same. - menu.Tag = value; - Assert.Same(value, menu.Tag); - } - - public static IEnumerable FindMenuItem_TestData() - { - yield return new object[] { Array.Empty(), MenuItem.FindHandle, IntPtr.Zero, null }; - yield return new object[] { Array.Empty(), MenuItem.FindShortcut, IntPtr.Zero, null }; - yield return new object[] { Array.Empty(), 2, IntPtr.Zero, null }; - - var menuItem1 = new MenuItem(); - var menuItem2 = new MenuItem(); - yield return new object[] { new MenuItem[] { menuItem1 }, MenuItem.FindHandle, IntPtr.Zero, menuItem1 }; - yield return new object[] { new MenuItem[] { new MenuItem() }, MenuItem.FindHandle, (IntPtr)1, null }; - yield return new object[] { new MenuItem[] { menuItem2 }, MenuItem.FindShortcut, IntPtr.Zero, menuItem2 }; - yield return new object[] { new MenuItem[] { new MenuItem() }, MenuItem.FindShortcut, (IntPtr)1, null }; - yield return new object[] { new MenuItem[] { new MenuItem() }, 2, IntPtr.Zero, null }; - - var shortcutItem1 = new MenuItem - { - Shortcut = Shortcut.CtrlA - }; - yield return new object[] { new MenuItem[] { shortcutItem1 }, MenuItem.FindShortcut, (IntPtr)0x20041, shortcutItem1 }; - yield return new object[] { new MenuItem[] { new MenuItem { Shortcut = Shortcut.CtrlA } }, MenuItem.FindShortcut, (IntPtr)0x20042, null }; - - var parent = new MenuItem("parent", new MenuItem[] { new MenuItem() }); - var shortcutItem2 = new MenuItem - { - Shortcut = Shortcut.CtrlA - }; - yield return new object[] { new MenuItem[] { parent }, MenuItem.FindHandle, IntPtr.Zero, parent }; - yield return new object[] { new MenuItem[] { new MenuItem("parent", new MenuItem[] { new MenuItem() }) }, MenuItem.FindHandle, (IntPtr)1, null }; - yield return new object[] { new MenuItem[] { new MenuItem("parent", new MenuItem[] { new MenuItem() }) }, MenuItem.FindHandle, (IntPtr)1, null }; - yield return new object[] { new MenuItem[] { new MenuItem("parent", new MenuItem[] { shortcutItem2 }) }, MenuItem.FindShortcut, (IntPtr)0x20041, shortcutItem2 }; - yield return new object[] { new MenuItem[] { new MenuItem("parent", new MenuItem[] { new MenuItem() { Shortcut = Shortcut.CtrlA } }) }, MenuItem.FindShortcut, (IntPtr)0x20042, null }; - } - - [Theory] - [MemberData(nameof(FindMenuItem_TestData))] - public void Menu_FindMenuItem_Invoke_ReturnsExpected(MenuItem[] items, int type, IntPtr value, MenuItem expected) - { - var menu = new SubMenu(items); - Assert.Equal(expected, menu.FindMenuItem(type, value)); - } - - public static IEnumerable ProcessCmdKey_TestData() - { - yield return new object[] { new MenuItem { Shortcut = Shortcut.CtrlA }, true, 1, 0 }; - yield return new object[] { new MenuItem { Shortcut = Shortcut.CtrlA, Enabled = false }, false, 0, 0 }; - yield return new object[] { new MenuItem("text", new MenuItem[] { new MenuItem() }) { Shortcut = Shortcut.CtrlA }, true, 0, 1 }; - yield return new object[] { new MenuItem("text", new MenuItem[] { new MenuItem() }) { Shortcut = Shortcut.CtrlA, Enabled = false }, false, 0, 0 }; - } - - [Theory] - [MemberData(nameof(ProcessCmdKey_TestData))] - public void Menu_ProcessCmdKey_HasItemWithShoutcutKey_ReturnsExpected(MenuItem menuItem, bool expectedResult, int expectedOnClickCallCount, int expectedOnPopupCallCount) - { - int onClickCallCount = 0; - menuItem.Click += (sender, e) => - { - onClickCallCount++; - Assert.Same(menuItem, sender); - Assert.Equal(EventArgs.Empty, e); - }; - - int onPopupCallCount = 0; - menuItem.Popup += (sender, e) => - { - onPopupCallCount++; - Assert.Same(menuItem, sender); - Assert.Equal(EventArgs.Empty, e); - }; - - var menu = new SubMenu(new MenuItem[] { menuItem }); - var message = new Message(); - Assert.Equal(expectedResult, menu.ProcessCmdKey(ref message, Keys.Control | Keys.A)); - Assert.Equal(expectedOnClickCallCount, onClickCallCount); - Assert.Equal(expectedOnPopupCallCount, onPopupCallCount); - } - - public static IEnumerable ProcessCmdKey_MenuItemParent_TestData() - { - var enabledParentChild = new MenuItem { Shortcut = Shortcut.CtrlA }; - var enabledParent = new MenuItem("text", new MenuItem[] { enabledParentChild }); - yield return new object[] { enabledParent, enabledParentChild, true, 1, 0, 0, 1 }; - - var enabledParentChildWithItems = new MenuItem("text", new MenuItem[] { new MenuItem() }) { Shortcut = Shortcut.CtrlA }; - var enabledParentWithItems = new MenuItem("text", new MenuItem[] { enabledParentChildWithItems }); - yield return new object[] { enabledParentWithItems, enabledParentChildWithItems, true, 0, 1, 0, 1 }; - - var disabledParentChild = new MenuItem { Shortcut = Shortcut.CtrlA }; - var disabledParent = new MenuItem("text", new MenuItem[] { disabledParentChild }) { Enabled = false }; - yield return new object[] { disabledParent, disabledParentChild, false, 0, 0, 0, 0 }; - } - - [Theory] - [MemberData(nameof(ProcessCmdKey_MenuItemParent_TestData))] - public void Menu_ProcessCmdKey_MenuItemParent_ReturnsExpected(MenuItem parent, MenuItem child, bool expectedResult, int expectedChildOnClickCallCount, int expectedChildOnPopupCallCount, int expectedParentOnClickCallCount, int expectedParentOnPopupCallCount) - { - int childOnClickCallCount = 0; - child.Click += (sender, e) => - { - childOnClickCallCount++; - Assert.Same(child, sender); - Assert.Equal(EventArgs.Empty, e); - }; - - int childOnPopupCallCount = 0; - child.Popup += (sender, e) => - { - childOnPopupCallCount++; - Assert.Same(child, sender); - Assert.Equal(EventArgs.Empty, e); - }; - - int parentOnClickCallCount = 0; - parent.Click += (sender, e) => - { - parentOnClickCallCount++; - Assert.Same(parent, sender); - Assert.Equal(EventArgs.Empty, e); - }; - - int parentOnPopupCallCount = 0; - parent.Popup += (sender, e) => - { - parentOnPopupCallCount++; - Assert.Same(parent, sender); - Assert.Equal(EventArgs.Empty, e); - }; - - var message = new Message(); - Assert.Equal(expectedResult, parent.ProcessCmdKey(ref message, Keys.Control | Keys.A)); - Assert.Equal(expectedChildOnClickCallCount, childOnClickCallCount); - Assert.Equal(expectedChildOnPopupCallCount, childOnPopupCallCount); - Assert.Equal(expectedParentOnClickCallCount, parentOnClickCallCount); - Assert.Equal(expectedParentOnPopupCallCount, parentOnPopupCallCount); - } - - [Fact] - public void Menu_ProcessCmdKey_ParentMenuItemPopupHandlerRemovesChild_ReturnsFalse() - { - var child = new MenuItem { Shortcut = Shortcut.CtrlA }; - var parent = new MenuItem("text", new MenuItem[] { child }); - var message = new Message(); - - parent.Popup += (sender, e) => - { - parent.MenuItems.Remove(child); - }; - - Assert.False(parent.ProcessCmdKey(ref message, Keys.Control | Keys.A)); - } - - [Fact] - public void Menu_ProcessCmdKey_NoSuchShortcutKey_ReturnsFalse() - { - var menu = new SubMenu(new MenuItem[] { new MenuItem() }); - var message = new Message(); - Assert.False(menu.ProcessCmdKey(ref message, Keys.Control | Keys.A)); - } - - [Fact] - public void Menu_Dispose_NoChildren_Success() - { - var menu = new SubMenu(Array.Empty()); - menu.Dispose(); - menu.Dispose(); - } - - [Fact] - public void Menu_Dispose_WithChildren_Success() - { - var menuItem = new MenuItem(); - var menu = new SubMenu(new MenuItem[] { menuItem }); - menu.Dispose(); - Assert.Null(menuItem.Parent); - Assert.Empty(menu.MenuItems); - - menu.Dispose(); - Assert.Empty(menu.MenuItems); - } - - [Fact] - public void Menu_Dispose_ItemHasSite_Success() - { - var menuItem = new MenuItem - { - Site = Mock.Of() - }; - var menu = new SubMenu(new MenuItem[] { menuItem }); - menu.Dispose(); - Assert.Null(menuItem.Parent); - Assert.Empty(menu.MenuItems); - - menu.Dispose(); - Assert.Empty(menu.MenuItems); - } - - [Fact] - public void Menu_Dispose_ItemHasSiteWithContainer_Success() - { - var container = new Container(); - var menuItem = new MenuItem - { - Site = Mock.Of(s => s.Container == container) - }; - container.Add(menuItem); - var menu = new SubMenu(new MenuItem[] { menuItem }); - menu.Dispose(); - Assert.Empty(container.Components); - Assert.Null(menuItem.Parent); - Assert.Empty(menu.MenuItems); - - menu.Dispose(); - Assert.Empty(menu.MenuItems); - } - - public static IEnumerable FindMergePosition_TestData() - { - yield return new object[] { Array.Empty(), -1, 0 }; - yield return new object[] { new MenuItem[] { new MenuItem { MergeOrder = 10 }, new MenuItem { MergeOrder = 12 }, new MenuItem(), new MenuItem(), new MenuItem() }, 12, 5 }; - yield return new object[] { new MenuItem[] { new MenuItem { MergeOrder = 10 }, new MenuItem { MergeOrder = 12 }, new MenuItem(), new MenuItem(), new MenuItem() }, 11, 5 }; - yield return new object[] { new MenuItem[] { new MenuItem { MergeOrder = 10 }, new MenuItem { MergeOrder = 12 }, new MenuItem(), new MenuItem(), new MenuItem() }, -1, 0 }; - yield return new object[] { new MenuItem[] { new MenuItem { MergeOrder = 10 }, new MenuItem(), new MenuItem(), new MenuItem { MergeOrder = 12 }, new MenuItem() }, 0, 5 }; - yield return new object[] { new MenuItem[] { new MenuItem { MergeOrder = 10 }, new MenuItem(), new MenuItem(), new MenuItem { MergeOrder = 12 }, new MenuItem() }, 5, 5 }; - yield return new object[] { new MenuItem[] { new MenuItem() }, 0, 1 }; - } - - [Theory] - [MemberData(nameof(FindMergePosition_TestData))] - public void Menu_FindMergePosition_Invoke_ReturnsExpected(MenuItem[] items, int mergeOrder, int expected) - { - var menu = new SubMenu(items); - Assert.Equal(expected, menu.FindMergePosition(mergeOrder)); - } - - public static IEnumerable GetContextMenu_TestData() - { - yield return new object[] { new SubMenu(Array.Empty()), null }; - yield return new object[] { new MenuItem(), null }; - - var menuItem1 = new MenuItem(); - var menu1 = new ContextMenu(new MenuItem[] { menuItem1 }); - yield return new object[] { menu1, menu1 }; - yield return new object[] { menuItem1, menu1 }; - - var menuItem2 = new MenuItem(); - var menu2 = new SubMenu(new MenuItem[] { menuItem2 }); - yield return new object[] { menu2, null }; - yield return new object[] { menuItem2, null }; - } - - [Theory] - [MemberData(nameof(GetContextMenu_TestData))] - public void Menu_GetContextMenu_Invoke_ReturnsExpected(Menu menu, ContextMenu expected) - { - Assert.Equal(expected, menu.GetContextMenu()); - } - - public static IEnumerable GetMainMenu_TestData() - { - yield return new object[] { new SubMenu(Array.Empty()), null }; - yield return new object[] { new MenuItem(), null }; - - var menuItem1 = new MenuItem(); - var menu1 = new MainMenu(new MenuItem[] { menuItem1 }); - yield return new object[] { menu1, menu1 }; - yield return new object[] { menuItem1, menu1 }; - - var menuItem2 = new MenuItem(); - var menu2 = new SubMenu(new MenuItem[] { menuItem2 }); - yield return new object[] { menu2, null }; - yield return new object[] { menuItem2, null }; - } - - [Theory] - [MemberData(nameof(GetMainMenu_TestData))] - public void Menu_GetMainMenu_Invoke_ReturnsExpected(Menu menu, MainMenu expected) - { - Assert.Equal(expected, menu.GetMainMenu()); - } - - public static IEnumerable MergeMenu_TestData() - { - { - var menu1 = new MenuItem("1"); - var menu2 = new MenuItem("2"); - yield return new object[] - { - new MenuItem[] { menu1 }, - new MenuItem[] { menu2 }, - new MenuItem[] { menu1, menu2 } - }; - } - { - var menu1 = new MenuItem("1"); - var menu2 = new MenuItem("2") { MergeType = MenuMerge.MergeItems }; - yield return new object[] - { - new MenuItem[] { menu1 }, - new MenuItem[] { menu2 }, - new MenuItem[] { menu1, menu2 } - }; - } - { - var menu1 = new MenuItem("1"); - var menu2 = new MenuItem("2"); - var menu3 = new MenuItem("3") { MergeType = MenuMerge.Replace }; - yield return new object[] - { - new MenuItem[] { menu1, menu2 }, - new MenuItem[] { menu3 }, - new MenuItem[] { menu1, menu2, menu3 } - }; - } - { - var menu1 = new MenuItem("1"); - var menu2 = new MenuItem("2") { MergeType = MenuMerge.Remove }; - yield return new object[] - { - new MenuItem[] { menu1 }, - new MenuItem[] { menu2 }, - new MenuItem[] { menu1 } - }; - } - { - var menu1 = new MenuItem("1") { MergeOrder = 1 }; - var menu2 = new MenuItem("2"); - yield return new object[] - { - new MenuItem[] { menu1 }, - new MenuItem[] { menu2 }, - new MenuItem[] { menu2, menu1 } - }; - } - { - var menu1 = new MenuItem("1") { MergeOrder = -1 }; - var menu2 = new MenuItem("2"); - yield return new object[] - { - new MenuItem[] { menu1 }, - new MenuItem[] { menu2 }, - new MenuItem[] { menu1, menu2 } - }; - } - { - var menu1 = new MenuItem("1") { MergeOrder = 1 }; - var menu2 = new MenuItem("2") { MergeOrder = 1 }; - var menu3 = new MenuItem("3") { MergeOrder = 2 }; - var menu4 = new MenuItem("4") { MergeOrder = 2 }; - var menu5 = new MenuItem("5") { MergeOrder = 3 }; - var menu6 = new MenuItem("6") { MergeOrder = 0 }; - yield return new object[] - { - new MenuItem[] { menu1, menu2, menu3 }, - new MenuItem[] { menu4, menu5, menu6 }, - new MenuItem[] { menu6, menu1, menu2, menu3, menu4, menu5 } - }; - } - { - var menu1 = new MenuItem("1") { MergeOrder = 1, MergeType = MenuMerge.Replace }; - var menu2 = new MenuItem("2") { MergeOrder = 1, MergeType = MenuMerge.Replace }; - var menu3 = new MenuItem("3") { MergeOrder = 2, MergeType = MenuMerge.Replace }; - var menu4 = new MenuItem("4") { MergeOrder = 2, MergeType = MenuMerge.Replace }; - var menu5 = new MenuItem("5") { MergeOrder = 3, MergeType = MenuMerge.Replace }; - var menu6 = new MenuItem("6") { MergeOrder = 0, MergeType = MenuMerge.Replace }; - yield return new object[] - { - new MenuItem[] { menu1, menu2, menu3 }, - new MenuItem[] { menu4, menu5, menu6 }, - new MenuItem[] { menu6, menu1, menu3, menu4, menu5 } - }; - } - { - var menu1 = new MenuItem("1") { MergeOrder = 1, MergeType = MenuMerge.Remove }; - var menu2 = new MenuItem("2") { MergeOrder = 1, MergeType = MenuMerge.Remove }; - var menu3 = new MenuItem("3") { MergeOrder = 2, MergeType = MenuMerge.Remove }; - var menu4 = new MenuItem("4") { MergeOrder = 2, MergeType = MenuMerge.Remove }; - var menu5 = new MenuItem("5") { MergeOrder = 3, MergeType = MenuMerge.Remove }; - var menu6 = new MenuItem("6") { MergeOrder = 0, MergeType = MenuMerge.Remove }; - yield return new object[] - { - new MenuItem[] { menu1, menu2, menu3 }, - new MenuItem[] { menu4, menu5, menu6 }, - new MenuItem[] { menu1, menu2, menu3 } - }; - } - { - var menu1 = new MenuItem("1") { MergeOrder = 1, MergeType = MenuMerge.MergeItems }; - var menu2 = new MenuItem("2") { MergeOrder = 1, MergeType = MenuMerge.MergeItems }; - var menu3 = new MenuItem("3") { MergeOrder = 2, MergeType = MenuMerge.MergeItems }; - var menu4 = new MenuItem("4") { MergeOrder = 2, MergeType = MenuMerge.MergeItems }; - var menu5 = new MenuItem("5") { MergeOrder = 3, MergeType = MenuMerge.MergeItems }; - var menu6 = new MenuItem("6") { MergeOrder = 0, MergeType = MenuMerge.MergeItems }; - yield return new object[] - { - new MenuItem[] { menu1, menu2, menu3 }, - new MenuItem[] { menu4, menu5, menu6 }, - new MenuItem[] { menu6, menu1, menu2, menu4, menu5 } - }; - } - { - var menu1 = new MenuItem("1"); - var menu2 = new MenuItem("2"); - yield return new object[] - { - new MenuItem[] { menu1, menu2 }, - null, - new MenuItem[] { menu1, menu2 } - }; - } - { - var menu1 = new MenuItem("1"); - var menu2 = new MenuItem("2"); - yield return new object[] - { - null, - new MenuItem[] { menu1, menu2 }, - new MenuItem[] { menu1, menu2 } - }; - } - { - yield return new object[] - { - null, - null, - Array.Empty() - }; - } - } - - [Theory] - [MemberData(nameof(MergeMenu_TestData))] - public void Menu_MergeMenu_Invoke_ReturnsExpected(MenuItem[] destinationItems, MenuItem[] sourceItems, MenuItem[] expectedItems) - { - var menu = new SubMenu(destinationItems); - var menuSrc = new SubMenu(sourceItems); - menu.MergeMenu(menuSrc); - AssertEqualMenuItems(expectedItems, menu.MenuItems.Cast().ToArray()); - } - - [Fact] - public void Menu_MergeMenu_SameSourceAndDestination_ThrowsArgumentException() - { - var menu = new SubMenu(Array.Empty()); - Assert.Throws("menuSrc", () => menu.MergeMenu(menu)); - } - - [Fact] - public void Menu_MergeMenu_NullSource_ThrowsArgumentNullException() - { - var menu = new SubMenu(Array.Empty()); - Assert.Throws("menuSrc", () => menu.MergeMenu(null)); - } - - public static IEnumerable CloneMenu_TestData() - { - yield return new object[] { Array.Empty() }; - yield return new object[] { new MenuItem[] { new MenuItem("text") } }; - } - - [Theory] - [MemberData(nameof(CloneMenu_TestData))] - public void Menu_CloneMenu_Invoke_Success(MenuItem[] items) - { - var menu = new SubMenu(new MenuItem[] { new MenuItem() }); - menu.CloneMenu(new SubMenu(items)); - AssertEqualMenuItems(items, menu.MenuItems.Cast().ToArray()); - for (int i = 0; i < items.Length; i++) - { - Assert.Equal(i, menu.MenuItems[i].Index); - Assert.Equal(menu, menu.MenuItems[i].Parent); - } - } - - [Fact] - public void Menu_CloneMenu_NullMenuSource_ThrowsArgumentNullException() - { - var menu = new SubMenu(Array.Empty()); - Assert.Throws("menuSrc", () => menu.CloneMenu(null)); - } - - [Fact] - public void Menu_ToString_Invoke_ReturnsExpected() - { - var menu = new SubMenu(new MenuItem[] { new MenuItem() }); - Assert.Equal("System.Windows.Forms.Tests.MenuTests+SubMenu, Items.Count: 1", menu.ToString()); - } - - internal static void AssertEqualMenuItems(MenuItem[] expected, MenuItem[] actual) - { - Assert.Equal(expected.Length, actual.Length); - try - { - Assert.Equal(expected.Select(m => m.Text), actual.Cast().Select(m => m.Text)); - } - catch (ObjectDisposedException) - { - } - for (int i = 0; i < expected.Length; i++) - { - AssertEqualMenuItem(expected[i], actual[i]); - } - } - - internal static void AssertEqualMenuItem(MenuItem expected, MenuItem actual) - { - try - { - Assert.Equal(expected.Name, actual.Name); - } - catch (ObjectDisposedException) - { - } - AssertEqualMenuItems(expected.MenuItems.Cast().ToArray(), actual.MenuItems.Cast().ToArray()); - } - - private class SubMenu : Menu - { - public SubMenu(MenuItem[] items) : base(items) - { - } - - public new int FindMergePosition(int mergeOrder) => base.FindMergePosition(mergeOrder); - - public new void CloneMenu(Menu menuSrc) => base.CloneMenu(menuSrc); - - public new bool ProcessCmdKey(ref Message msg, Keys keyData) => base.ProcessCmdKey(ref msg, keyData); - } - } -} diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ControlTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ControlTests.cs index 80dc5bf7955..7b754c37974 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ControlTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ControlTests.cs @@ -920,7 +920,7 @@ public void Control_Parent_SetWithNonNullOldParent_GetReturnsExpected(Control va { Parent = oldParent }; - + control.Parent = value; Assert.Same(value, control.Parent); Assert.Empty(oldParent.Controls); @@ -1016,7 +1016,7 @@ public void Control_ParentInternal_SetWithNonNullOldParent_GetReturnsExpected(Co { ParentInternal = oldParent }; - + control.ParentInternal = value; Assert.Same(value, control.ParentInternal); Assert.Empty(oldParent.Controls); @@ -3566,11 +3566,11 @@ public void Control_CausesValidation_Set_GetReturnsExpected(bool value) CausesValidation = value }; Assert.Equal(value, control.CausesValidation); - + // Set same control.CausesValidation = value; Assert.Equal(value, control.CausesValidation); - + // Set different control.CausesValidation = !value; Assert.Equal(!value, control.CausesValidation); @@ -3642,17 +3642,6 @@ public void Control_ClientSize_Set_GetReturnsExpected(Size value) Assert.Equal(value, control.ClientSize); } - [Fact] - public void Control_ContextMenuGetSet() - { - var cont = new Control(); - var expected = new ContextMenu(); - - cont.ContextMenu = expected; - - Assert.Equal(expected, cont.ContextMenu); - } - [Fact] public void Control_ContextMenuStripGetSet() { @@ -3740,7 +3729,7 @@ public void Control_Dock_SetWithOldValue_GetReturnsExpected(DockStyle value) { Dock = DockStyle.Top }; - + control.Dock = value; Assert.Equal(value, control.Dock); Assert.Equal(AnchorStyles.Top | AnchorStyles.Left, control.Anchor); @@ -3770,7 +3759,7 @@ public void Control_Dock_SetWithAnchor_GetReturnsExpected(AnchorStyles anchor, D { Anchor = anchor }; - + control.Dock = value; Assert.Equal(value, control.Dock); Assert.Equal(expectedAnchor, control.Anchor); diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridCellTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridCellTests.cs deleted file mode 100644 index 67b3a895107..00000000000 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridCellTests.cs +++ /dev/null @@ -1,94 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Collections.Generic; -using System.ComponentModel; -using WinForms.Common.Tests; -using Xunit; - -namespace System.Windows.Forms.Tests -{ - public class DataGridCellTests - { - [Fact] - public void DataGridCell_Ctor_Default() - { - var cell = new DataGridCell(); - Assert.Equal(0, cell.RowNumber); - Assert.Equal(0, cell.ColumnNumber); - } - - [Theory] - [InlineData(-1, -2)] - [InlineData(0, 0)] - [InlineData(1, 2)] - [InlineData(1, 0)] - [InlineData(0, 1)] - public void DataGridCell_Ctor_Int_Int(int rowNumber, int columnNumber) - { - var cell = new DataGridCell(rowNumber, columnNumber); - Assert.Equal(rowNumber, cell.RowNumber); - Assert.Equal(columnNumber, cell.ColumnNumber); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetIntTheoryData))] - public void DataGridCell_RowNumber_Set_GetReturnsExpected(int value) - { - var cell = new DataGridCell - { - RowNumber = value - }; - Assert.Equal(value, cell.RowNumber); - - // Set same. - cell.RowNumber = value; - Assert.Equal(value, cell.RowNumber); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetIntTheoryData))] - public void DataGridCell_ColumnNumber_Set_GetReturnsExpected(int value) - { - var cell = new DataGridCell - { - ColumnNumber = value - }; - Assert.Equal(value, cell.ColumnNumber); - - // Set same. - cell.ColumnNumber = value; - Assert.Equal(value, cell.ColumnNumber); - } - - public static IEnumerable Equals_TestData() - { - yield return new object[] { new DataGridCell(1, 2), new DataGridCell(1, 2), true }; - yield return new object[] { new DataGridCell(1, 2), new DataGridCell(2, 2), false }; - yield return new object[] { new DataGridCell(1, 2), new DataGridCell(1, 3), false }; - - yield return new object[] { new DataGridCell(1, 2), new object(), false }; - yield return new object[] { new DataGridCell(1, 2), null, false }; - } - - [Theory] - [MemberData(nameof(Equals_TestData))] - public void DataGridCell_Equals_Invoke_ReturnsExpected(DataGridCell cell, object other, bool expected) - { - if (other is DataGridCell otherCell) - { - Assert.Equal(expected, cell.GetHashCode().Equals(otherCell.GetHashCode())); - } - - Assert.Equal(expected, cell.Equals(other)); - } - - [Fact] - public void DataGridCell_ToString_Invoke_ReturnsExpected() - { - var cell = new DataGridCell(1, 2); - Assert.Equal("DataGridCell {RowNumber = 1, ColumnNumber = 2}", cell.ToString()); - } - } -} diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridColumnStyleTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridColumnStyleTests.cs deleted file mode 100644 index d071dc9c1dc..00000000000 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridColumnStyleTests.cs +++ /dev/null @@ -1,1398 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Collections; -using System.Collections.Generic; -using System.ComponentModel; -using System.Drawing; -using WinForms.Common.Tests; -using Xunit; - -namespace System.Windows.Forms.Tests -{ - public class DataGridColumnStyleTests - { - [Fact] - public void DataGridColumnStyle_Ctor_Default() - { - var style = new SubDataGridColumnStyle(); - Assert.Equal(HorizontalAlignment.Left, style.Alignment); - Assert.True(style.CanRaiseEvents); - Assert.Null(style.Container); - Assert.Null(style.DataGridTableStyle); - Assert.False(style.DesignMode); - Assert.NotNull(style.Events); - Assert.Same(style.Events, style.Events); - Assert.Equal(Control.DefaultFont.Height, style.FontHeight); - Assert.NotNull(style.HeaderAccessibleObject); - Assert.Same(style.HeaderAccessibleObject, style.HeaderAccessibleObject); - Assert.Empty(style.HeaderText); - Assert.Empty(style.MappingName); - Assert.Equal("(null)", style.NullText); - Assert.Null(style.PropertyDescriptor); - Assert.False(style.ReadOnly); - Assert.Null(style.Site); - Assert.Equal(-1, style.Width); - } - - public static IEnumerable Ctor_PropertyDescriptor_TestData() - { - yield return new object[] { null, false }; - yield return new object[] { TypeDescriptor.GetProperties(typeof(DataClass))[0], false }; - yield return new object[] { TypeDescriptor.GetProperties(typeof(ReadOnlyDataClass))[0], true }; - } - - [Theory] - [MemberData(nameof(Ctor_PropertyDescriptor_TestData))] - public void Ctor_PropertyDescriptor(PropertyDescriptor descriptor, bool expectedReadOnly) - { - var style = new SubDataGridColumnStyle(descriptor); - Assert.Equal(HorizontalAlignment.Left, style.Alignment); - Assert.True(style.CanRaiseEvents); - Assert.Null(style.Container); - Assert.Null(style.DataGridTableStyle); - Assert.False(style.DesignMode); - Assert.NotNull(style.Events); - Assert.Same(style.Events, style.Events); - Assert.Equal(Control.DefaultFont.Height, style.FontHeight); - Assert.NotNull(style.HeaderAccessibleObject); - Assert.Same(style.HeaderAccessibleObject, style.HeaderAccessibleObject); - Assert.Empty(style.HeaderText); - Assert.Empty(style.MappingName); - Assert.Equal("(null)", style.NullText); - Assert.Same(descriptor, style.PropertyDescriptor); - Assert.Equal(expectedReadOnly, style.ReadOnly); - Assert.Null(style.Site); - Assert.Equal(-1, style.Width); - } - - public static IEnumerable Ctor_PropertyDescriptor_Bool_TestData() - { - yield return new object[] { null, true, string.Empty, false }; - yield return new object[] { null, false, string.Empty, false }; - - yield return new object[] { TypeDescriptor.GetProperties(typeof(DataClass))[0], true, "Value1", false }; - yield return new object[] { TypeDescriptor.GetProperties(typeof(DataClass))[0], false, string.Empty, false }; - - yield return new object[] { TypeDescriptor.GetProperties(typeof(ReadOnlyDataClass))[0], true, "Value1", true }; - yield return new object[] { TypeDescriptor.GetProperties(typeof(ReadOnlyDataClass))[0], false, string.Empty, true }; - } - - [Theory] - [MemberData(nameof(Ctor_PropertyDescriptor_Bool_TestData))] - public void Ctor_PropertyDescriptor_Bool(PropertyDescriptor descriptor, bool isDefault, string expectedMappingName, bool expectedReadOnly) - { - var style = new SubDataGridColumnStyle(descriptor, isDefault); - Assert.Equal(HorizontalAlignment.Left, style.Alignment); - Assert.True(style.CanRaiseEvents); - Assert.Null(style.Container); - Assert.Null(style.DataGridTableStyle); - Assert.False(style.DesignMode); - Assert.NotNull(style.Events); - Assert.Same(style.Events, style.Events); - Assert.Equal(Control.DefaultFont.Height, style.FontHeight); - Assert.NotNull(style.HeaderAccessibleObject); - Assert.Same(style.HeaderAccessibleObject, style.HeaderAccessibleObject); - Assert.Equal(expectedMappingName, style.HeaderText); - Assert.Equal(expectedMappingName, style.MappingName); - Assert.Equal("(null)", style.NullText); - Assert.Same(descriptor, style.PropertyDescriptor); - Assert.Equal(expectedReadOnly, style.ReadOnly); - Assert.Null(style.Site); - Assert.Equal(-1, style.Width); - } - - [Fact] - public void DataGridColumnStyle_DefaultProperty_Get_ReturnsExpected() - { - PropertyDescriptor property = TypeDescriptor.GetDefaultProperty(typeof(DataGridColumnStyle)); - Assert.Equal("HeaderText", property.Name); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetEnumTypeTheoryData), typeof(HorizontalAlignment))] - public void Alignment_Set_GetReturnsExpected(HorizontalAlignment value) - { - var style = new SubDataGridColumnStyle - { - Alignment = value - }; - Assert.Equal(value, style.Alignment); - - // Set same. - style.Alignment = value; - Assert.Equal(value, style.Alignment); - } - - [Fact] - public void DataGridColumnStyle_Alignment_SetWithHandler_CallsAlignmentChanged() - { - var style = new SubDataGridColumnStyle(); - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(style, sender); - Assert.Same(EventArgs.Empty, e); - callCount++; - }; - style.AlignmentChanged += handler; - - // Set different. - style.Alignment = HorizontalAlignment.Center; - Assert.Equal(HorizontalAlignment.Center, style.Alignment); - Assert.Equal(1, callCount); - - // Set same. - style.Alignment = HorizontalAlignment.Center; - Assert.Equal(HorizontalAlignment.Center, style.Alignment); - Assert.Equal(1, callCount); - - // Set different. - style.Alignment = HorizontalAlignment.Left; - Assert.Equal(HorizontalAlignment.Left, style.Alignment); - Assert.Equal(2, callCount); - - // Remove handler. - style.AlignmentChanged -= handler; - style.Alignment = HorizontalAlignment.Center; - Assert.Equal(HorizontalAlignment.Center, style.Alignment); - Assert.Equal(2, callCount); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetEnumTypeTheoryDataInvalid), typeof(HorizontalAlignment))] - public void Alignment_SetInvalid_ThrowsInvalidEnumArgumentException(HorizontalAlignment value) - { - var style = new SubDataGridColumnStyle(); - Assert.Throws("value", () => style.Alignment = value); - } - - [Fact] - public void DataGridColumnStyle_FontHeight_GetWithParentWithDataGrid_ReturnsExpected() - { - Font font = new Font(Control.DefaultFont.FontFamily, 15); - var dataGrid = new DataGrid - { - Font = font - }; - var tableStyle = new DataGridTableStyle(); - dataGrid.TableStyles.Add(tableStyle); - var style = new SubDataGridColumnStyle(); - tableStyle.GridColumnStyles.Add(style); - Assert.Equal(font.Height, style.FontHeight); - } - - [Fact] - public void DataGridColumnStyle_FontHeight_GetWithParentWithoutDataGrid_ReturnsExpected() - { - var tableStyle = new DataGridTableStyle(); - var style = new SubDataGridColumnStyle(); - tableStyle.GridColumnStyles.Add(style); - Assert.Equal(Control.DefaultFont.Height, style.FontHeight); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetStringNormalizedTheoryData))] - public void HeaderText_Set_GetReturnsExpected(string value, string expected) - { - var style = new SubDataGridColumnStyle - { - HeaderText = value - }; - Assert.Equal(expected, style.HeaderText); - - // Set same. - style.HeaderText = value; - Assert.Equal(expected, style.HeaderText); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetStringNormalizedTheoryData))] - public void HeaderText_SetWithPropertyDescriptor_GetReturnsExpected(string value, string expected) - { - PropertyDescriptor property = TypeDescriptor.GetProperties(typeof(DataClass))[0]; - var style = new SubDataGridColumnStyle(property) - { - HeaderText = value - }; - Assert.Equal(expected, style.HeaderText); - - // Set same. - style.HeaderText = value; - Assert.Equal(expected, style.HeaderText); - } - - [Fact] - public void DataGridColumnStyle_HeaderText_SetWithHandler_CallsHeaderTextChanged() - { - var style = new SubDataGridColumnStyle(); - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(style, sender); - Assert.Same(EventArgs.Empty, e); - callCount++; - }; - style.HeaderTextChanged += handler; - - // Set different. - style.HeaderText = "HeaderText"; - Assert.Equal("HeaderText", style.HeaderText); - Assert.Equal(1, callCount); - - // Set same. - style.HeaderText = "HeaderText"; - Assert.Equal("HeaderText", style.HeaderText); - Assert.Equal(1, callCount); - - // Set different. - style.HeaderText = "OtherHeaderText"; - Assert.Equal("OtherHeaderText", style.HeaderText); - Assert.Equal(2, callCount); - - // Set null. - style.HeaderText = null; - Assert.Empty(style.HeaderText); - Assert.Equal(3, callCount); - - // Set null again. - style.HeaderText = null; - Assert.Empty(style.HeaderText); - Assert.Equal(3, callCount); - - // Set empty. - style.HeaderText = string.Empty; - Assert.Empty(style.HeaderText); - Assert.Equal(3, callCount); - - // Remove handler. - style.HeaderTextChanged -= handler; - style.HeaderText = "HeaderText"; - Assert.Equal("HeaderText", style.HeaderText); - Assert.Equal(3, callCount); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetStringNormalizedTheoryData))] - public void MappingName_Set_GetReturnsExpected(string value, string expected) - { - var style = new SubDataGridColumnStyle - { - MappingName = value - }; - Assert.Equal(expected, style.MappingName); - - style.MappingName = value; - Assert.Equal(expected, style.MappingName); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetStringNormalizedTheoryData))] - public void MappingName_SetWithDataGridView_GetReturnsExpected(string value, string expected) - { - var dataGrid = new DataGrid(); - var tableStyle = new DataGridTableStyle(); - dataGrid.TableStyles.Add(tableStyle); - var style = new SubDataGridColumnStyle(); - tableStyle.GridColumnStyles.Add(style); - - style.MappingName = value; - Assert.Equal(expected, style.MappingName); - - style.MappingName = value; - Assert.Equal(expected, style.MappingName); - } - - [Fact] - public void DataGridColumnStyle_MappingName_SetWithHandler_CallsMappingNameChanged() - { - var style = new SubDataGridColumnStyle(); - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(style, sender); - Assert.Same(EventArgs.Empty, e); - callCount++; - }; - style.MappingNameChanged += handler; - - // Set different. - style.MappingName = "MappingName"; - Assert.Equal("MappingName", style.MappingName); - Assert.Equal(1, callCount); - - // Set same. - style.MappingName = "MappingName"; - Assert.Equal("MappingName", style.MappingName); - Assert.Equal(1, callCount); - - // Set different. - style.MappingName = "OtherMappingName"; - Assert.Equal("OtherMappingName", style.MappingName); - Assert.Equal(2, callCount); - - // Set null. - style.MappingName = null; - Assert.Empty(style.MappingName); - Assert.Equal(3, callCount); - - // Set null again. - style.MappingName = null; - Assert.Empty(style.MappingName); - Assert.Equal(3, callCount); - - // Set empty. - style.MappingName = string.Empty; - Assert.Empty(style.MappingName); - Assert.Equal(3, callCount); - - // Remove handler. - style.MappingNameChanged -= handler; - style.MappingName = "MappingName"; - Assert.Equal("MappingName", style.MappingName); - Assert.Equal(3, callCount); - } - - [Fact] - public void DataGridColumnStyle_MappingName_SetInvalid_ThrowsArgumentException() - { - var dataGrid = new DataGrid(); - var tableStyle = new DataGridTableStyle(); - dataGrid.TableStyles.Add(tableStyle); - - var style1 = new SubDataGridColumnStyle - { - MappingName = "MappingName1" - }; - var style2 = new SubDataGridColumnStyle - { - MappingName = "MappingName2" - }; - tableStyle.GridColumnStyles.Add(style1); - tableStyle.GridColumnStyles.Add(style2); - - Assert.Throws("column", () => style2.MappingName = "MappingName1"); - Assert.Equal("MappingName2", style2.MappingName); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetStringWithNullTheoryData))] - public void NullText_Set_GetReturnsExpected(string value) - { - var style = new SubDataGridColumnStyle - { - NullText = value - }; - Assert.Equal(value, style.NullText); - - // Set same. - style.NullText = value; - Assert.Equal(value, style.NullText); - } - - [Fact] - public void DataGridColumnStyle_NullText_SetWithHandler_CallsMappingNameChanged() - { - var style = new SubDataGridColumnStyle(); - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(style, sender); - Assert.Same(EventArgs.Empty, e); - callCount++; - }; - style.NullTextChanged += handler; - - // Set different. - style.NullText = "NullText"; - Assert.Equal("NullText", style.NullText); - Assert.Equal(1, callCount); - - // Set same. - style.NullText = "NullText"; - Assert.Equal("NullText", style.NullText); - Assert.Equal(1, callCount); - - // Set different. - style.NullText = "OtherMappingName"; - Assert.Equal("OtherMappingName", style.NullText); - Assert.Equal(2, callCount); - - // Set null. - style.NullText = null; - Assert.Null(style.NullText); - Assert.Equal(3, callCount); - - // Set null again. - style.NullText = null; - Assert.Null(style.NullText); - Assert.Equal(3, callCount); - - // Remove handler. - style.NullTextChanged -= handler; - style.NullText = "NullText"; - Assert.Equal("NullText", style.NullText); - Assert.Equal(3, callCount); - } - - public static IEnumerable PropertyDescriptor_Set_TestData() - { - yield return new object[] { null }; - yield return new object[] { TypeDescriptor.GetProperties(typeof(DataClass))[0] }; - } - - [Theory] - [MemberData(nameof(PropertyDescriptor_Set_TestData))] - public void PropertyDescriptor_Set_GetReturnsExpected(PropertyDescriptor value) - { - var style = new SubDataGridColumnStyle - { - PropertyDescriptor = value - }; - Assert.Same(value, style.PropertyDescriptor); - - // Set same. - style.PropertyDescriptor = value; - Assert.Same(value, style.PropertyDescriptor); - } - - [Fact] - public void DataGridColumnStyle_PropertyDescriptor_SetWithHandler_CallsPropertyDescriptorChanged() - { - var style = new SubDataGridColumnStyle(); - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(style, sender); - Assert.Same(EventArgs.Empty, e); - callCount++; - }; - style.PropertyDescriptorChanged += handler; - - // Set different. - PropertyDescriptor descriptor1 = TypeDescriptor.GetProperties(typeof(DataClass))[0]; - style.PropertyDescriptor = descriptor1; - Assert.Equal(descriptor1, style.PropertyDescriptor); - Assert.Equal(1, callCount); - - // Set same. - style.PropertyDescriptor = descriptor1; - Assert.Equal(descriptor1, style.PropertyDescriptor); - Assert.Equal(1, callCount); - - // Set different. - PropertyDescriptor descriptor2 = TypeDescriptor.GetProperties(typeof(DataClass))[1]; - style.PropertyDescriptor = descriptor2; - Assert.Equal(descriptor2, style.PropertyDescriptor); - Assert.Equal(2, callCount); - - // Set null. - style.PropertyDescriptor = null; - Assert.Null(style.PropertyDescriptor); - Assert.Equal(3, callCount); - - // Set null again. - style.PropertyDescriptor = null; - Assert.Null(style.PropertyDescriptor); - Assert.Equal(3, callCount); - - // Remove handler. - style.PropertyDescriptorChanged -= handler; - style.PropertyDescriptor = descriptor1; - Assert.Equal(descriptor1, style.PropertyDescriptor); - Assert.Equal(3, callCount); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetBoolTheoryData))] - public void ReadOnly_Set_GetReturnsExpected(bool value) - { - var style = new SubDataGridColumnStyle - { - ReadOnly = value - }; - Assert.Equal(value, style.ReadOnly); - - // Set same. - style.ReadOnly = value; - Assert.Equal(value, style.ReadOnly); - - // Set different - style.ReadOnly = !value; - Assert.Equal(!value, style.ReadOnly); - } - - [Fact] - public void DataGridColumnStyle_ReadOnly_SetWithHandler_CallsMappingNameChanged() - { - var style = new SubDataGridColumnStyle(); - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(style, sender); - Assert.Same(EventArgs.Empty, e); - callCount++; - }; - style.ReadOnlyChanged += handler; - - // Set different. - style.ReadOnly = true; - Assert.True(style.ReadOnly); - Assert.Equal(1, callCount); - - // Set same. - style.ReadOnly = true; - Assert.True(style.ReadOnly); - Assert.Equal(1, callCount); - - // Set different. - style.ReadOnly = false; - Assert.False(style.ReadOnly); - Assert.Equal(2, callCount); - - // Remove handler. - style.ReadOnlyChanged -= handler; - style.ReadOnly = true; - Assert.True(style.ReadOnly); - Assert.Equal(2, callCount); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetIntTheoryData))] - public void Width_Set_GetReturnsExpected(int value) - { - var style = new SubDataGridColumnStyle - { - Width = value - }; - Assert.Equal(value, style.Width); - - // Set same. - style.Width = value; - Assert.Equal(value, style.Width); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetIntTheoryData))] - public void Width_SetWithTableStyleWithDataGrid_GetReturnsExpected(int value) - { - var dataGrid = new DataGrid(); - int callCount = 0; - dataGrid.Layout += (sender, e) => callCount++; - var tableStyle = new DataGridTableStyle(); - dataGrid.TableStyles.Add(tableStyle); - var style = new SubDataGridColumnStyle(); - tableStyle.GridColumnStyles.Add(style); - - style.Width = value; - Assert.Equal(value, style.Width); - Assert.Equal(1, callCount); - - // Set same. - style.Width = value; - Assert.Equal(value, style.Width); - Assert.Equal(1, callCount); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetIntTheoryData))] - public void Width_SetWithTableStyleWithoutDataGrid_GetReturnsExpected(int value) - { - var tableStyle = new DataGridTableStyle(); - var style = new SubDataGridColumnStyle(); - tableStyle.GridColumnStyles.Add(style); - - style.Width = value; - Assert.Equal(value, style.Width); - - // Set same. - style.Width = value; - Assert.Equal(value, style.Width); - } - - [Fact] - public void DataGridColumnStyle_Width_SetWithHandler_CallsWidthChanged() - { - var style = new SubDataGridColumnStyle(); - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(style, sender); - Assert.Same(EventArgs.Empty, e); - callCount++; - }; - style.WidthChanged += handler; - - // Set different. - style.Width = 2; - Assert.Equal(2, style.Width); - Assert.Equal(1, callCount); - - // Set same. - style.Width = 2; - Assert.Equal(2, style.Width); - Assert.Equal(1, callCount); - - // Set different. - style.Width = 3; - Assert.Equal(3, style.Width); - Assert.Equal(2, callCount); - - // Remove handler. - style.WidthChanged -= handler; - style.Width = 2; - Assert.Equal(2, style.Width); - Assert.Equal(2, callCount); - } - - [Fact] - public void DataGridColumnStyle_FontChanged_Add_Remove_Success() - { - var style = new SubDataGridColumnStyle(); - int callCount = 0; - EventHandler handler = (sender, e) => callCount++; - - style.FontChanged += handler; - style.FontChanged -= handler; - Assert.Equal(0, callCount); - } - - [Fact] - public void DataGridColumnStyle_BeginUpdate_EndUpdate_DoesNotCallInvalidate() - { - var style = new InvalidateDataGridColumnStyle(); - style.BeginUpdate(); - style.EndUpdate(); - Assert.Equal(0, style.InvalidateCallCount); - } - - [Fact] - public void DataGridColumnStyle_BeginUpdate_SeveralTimes_DoesNotCallInvalidate() - { - var style = new InvalidateDataGridColumnStyle(); - style.BeginUpdate(); - style.BeginUpdate(); - Assert.Equal(0, style.InvalidateCallCount); - } - - [Fact] - public void DataGridColumnStyle_CheckValidDataSource_HasPropertyDescriptor_Nop() - { - PropertyDescriptor property = TypeDescriptor.GetProperties(typeof(DataClass))[0]; - var style = new SubDataGridColumnStyle(property); - var context = new BindingContext(); - var dataSource = new List { 1, 2, 3 }; - CurrencyManager value = Assert.IsType(context[dataSource]); - style.CheckValidDataSource(value); - } - - [Fact] - public void DataGridColumnStyle_CheckValidDataSource_NullValue_ThrowsArgumentNullException() - { - var style = new SubDataGridColumnStyle(); - Assert.Throws("value", () => style.CheckValidDataSource(null)); - } - - [Fact] - public void DataGridColumnStyle_CheckValidDataSource_NoPropertyDescriptor_ThrowsInvalidOperationException() - { - var style = new SubDataGridColumnStyle(); - var context = new BindingContext(); - var dataSource = new List { 1, 2, 3 }; - CurrencyManager value = Assert.IsType(context[dataSource]); - Assert.Throws(() => style.CheckValidDataSource(value)); - } - - public static IEnumerable ColumnStartedEditing_TestData() - { - yield return new object[] { null }; - yield return new object[] { new Control() }; - } - - [Theory] - [MemberData(nameof(ColumnStartedEditing_TestData))] - public void ColumnStartedEditing_WithTableStyleWithDataGridWithoutRows_Nop(Control editingControl) - { - var dataGrid = new DataGrid(); - var tableStyle = new DataGridTableStyle(); - dataGrid.TableStyles.Add(tableStyle); - var style = new SubDataGridColumnStyle(); - tableStyle.GridColumnStyles.Add(style); - style.ColumnStartedEditing(editingControl); - } - - [Theory] - [MemberData(nameof(ColumnStartedEditing_TestData))] - public void ColumnStartedEditing_WithTableStyle_Nop(Control editingControl) - { - var tableStyle = new DataGridTableStyle(); - var style = new SubDataGridColumnStyle(); - tableStyle.GridColumnStyles.Add(style); - style.ColumnStartedEditing(editingControl); - } - - [Theory] - [MemberData(nameof(ColumnStartedEditing_TestData))] - public void ColumnStartedEditing_NoTableStyle_Nop(Control editingControl) - { - var style = new SubDataGridColumnStyle(); - style.ColumnStartedEditing(editingControl); - } - - [Fact] - public void DataGridColumnStyle_ConcedeFocus_InvokeSeveralTimes_Nop() - { - var style = new SubDataGridColumnStyle(); - style.ConcedeFocus(); - style.ConcedeFocus(); - } - - [Fact] - public void DataGridColumnStyle_CreateHeaderAccessibleObject_Invoke_ReturnsExpected() - { - var style = new SubDataGridColumnStyle(); - AccessibleObject accessibleObject = style.CreateHeaderAccessibleObject(); - Assert.NotNull(accessibleObject); - Assert.NotSame(accessibleObject, style.CreateHeaderAccessibleObject()); - } - - public static IEnumerable Edit_CurrencyManagerIntRectangleBool_TestData() - { - yield return new object[] { null, -2, Rectangle.Empty, false }; - - var context = new BindingContext(); - var dataSource = new List { 1, 2, 3 }; - yield return new object[] { context[dataSource], -1, new Rectangle(1, 2, 3, 4), true }; - yield return new object[] { context[dataSource], 1, new Rectangle(-1, -2, -3, -4), true }; - } - - [Theory] - [MemberData(nameof(Edit_CurrencyManagerIntRectangleBool_TestData))] - public void Edit_InvokeCurrencyManagerIntRectangleBool_Success(CurrencyManager source, int rowNum, Rectangle bounds, bool readOnly) - { - var style = new SubDataGridColumnStyle(); - int callCount = 0; - style.EditAction = (actualSource, actualRowNum, actualBounds, actualReadOnly, actualDisplayText, actualCellIsVisible) => - { - Assert.Same(source, actualSource); - Assert.Equal(rowNum, actualRowNum); - Assert.Equal(bounds, actualBounds); - Assert.Equal(readOnly, actualReadOnly); - Assert.Null(actualDisplayText); - Assert.True(actualCellIsVisible); - callCount++; - }; - style.Edit(source, rowNum, bounds, readOnly); - Assert.Equal(1, callCount); - } - - public static IEnumerable Edit_CurrencyManagerIntRectangleBoolString_TestData() - { - yield return new object[] { null, -2, Rectangle.Empty, false, null }; - - var context = new BindingContext(); - var dataSource = new List { 1, 2, 3 }; - yield return new object[] { context[dataSource], -1, new Rectangle(1, 2, 3, 4), true, string.Empty }; - yield return new object[] { context[dataSource], 1, new Rectangle(-1, -2, -3, -4), true, "displayText" }; - } - - [Theory] - [MemberData(nameof(Edit_CurrencyManagerIntRectangleBoolString_TestData))] - public void Edit_InvokeCurrencyManagerIntRectangleBoolString_Success(CurrencyManager source, int rowNum, Rectangle bounds, bool readOnly, string displayText) - { - var style = new SubDataGridColumnStyle(); - int callCount = 0; - style.EditAction = (actualSource, actualRowNum, actualBounds, actualReadOnly, actualDisplayText, actualCellIsVisible) => - { - Assert.Same(source, actualSource); - Assert.Equal(rowNum, actualRowNum); - Assert.Equal(bounds, actualBounds); - Assert.Equal(readOnly, actualReadOnly); - Assert.Same(displayText, actualDisplayText); - Assert.True(actualCellIsVisible); - callCount++; - }; - style.Edit(source, rowNum, bounds, readOnly, displayText); - Assert.Equal(1, callCount); - } - - [Fact] - public void DataGridColumnStyle_EndUpdate_BeganUpdateInvalidated_DoesNotCallInvalidate() - { - var style = new InvalidateDataGridColumnStyle(); - style.BeginUpdate(); - Assert.Equal(0, style.InvalidateCallCount); - - style.CallInvalidate(); - Assert.Equal(1, style.InvalidateCallCount); - - style.EndUpdate(); - Assert.Equal(2, style.InvalidateCallCount); - } - - [Fact] - public void DataGridColumnStyle_EndUpdate_NotCalledBeganUpdate_DoesNotCallInvalidate() - { - var style = new InvalidateDataGridColumnStyle(); - style.EndUpdate(); - Assert.Equal(0, style.InvalidateCallCount); - } - - [Fact] - public void DataGridColumnStyle_EndUpdate_SeveralTimes_DoesNotCallInvalidate() - { - var style = new InvalidateDataGridColumnStyle(); - style.BeginUpdate(); - style.EndUpdate(); - style.EndUpdate(); - Assert.Equal(0, style.InvalidateCallCount); - } - - [Fact] - public void DataGridColumnStyle_EnterNullValue_InvokeSeveralTimes_Nop() - { - var style = new SubDataGridColumnStyle(); - style.EnterNullValue(); - style.EnterNullValue(); - } - - [Theory] - [InlineData(0, 1)] - [InlineData(1, 2)] - [InlineData(2, 3)] - public void GetColumnValueAtRow_PropertyDescriptor_ReturnsExpected(int rowNum, int expected) - { - PropertyDescriptor descriptor = TypeDescriptor.GetProperties(typeof(DataClass)).Find(nameof(DataClass.Value1), ignoreCase: false); - var style = new SubDataGridColumnStyle(descriptor); - var context = new BindingContext(); - var dataSource = new List { new DataClass { Value1 = 1 }, new DataClass { Value1 = 2 }, new DataClass { Value1 = 3 } }; - CurrencyManager source = Assert.IsType(context[dataSource]); - Assert.Equal(expected, style.GetColumnValueAtRow(source, rowNum)); - } - - [Theory] - [InlineData(0, 1)] - [InlineData(1, 2)] - [InlineData(2, 3)] - public void GetColumnValueAtRow_PropertyDescriptorCalledTwice_ReturnsExpected(int rowNum, int expected) - { - PropertyDescriptor descriptor = TypeDescriptor.GetProperties(typeof(DataClass)).Find(nameof(DataClass.Value1), ignoreCase: false); - var style = new NullPropertyDescriptorDataGridColumnStyle(descriptor, 2); - var context = new BindingContext(); - var dataSource = new List { new DataClass { Value1 = 1 }, new DataClass { Value1 = 2 }, new DataClass { Value1 = 3 } }; - CurrencyManager source = Assert.IsType(context[dataSource]); - Assert.Equal(expected, style.GetColumnValueAtRow(source, rowNum)); - } - - [Fact] - public void DataGridColumnStyle_GetColumnValueAtRow_NullSource_ThrowsArgumentNullException() - { - var style = new SubDataGridColumnStyle(); - Assert.Throws("value", () => style.GetColumnValueAtRow(null, 0)); - } - - [Fact] - public void DataGridColumnStyle_GetColumnValueAtRow_NoPropertyDescriptor_ThrowsInvalidOperationException() - { - var style = new SubDataGridColumnStyle(); - var context = new BindingContext(); - var dataSource = new List { 1, 2, 3 }; - CurrencyManager source = Assert.IsType(context[dataSource]); - Assert.Throws(() => style.GetColumnValueAtRow(source, 0)); - } - - [Fact] - public void DataGridColumnStyle_GetColumnValueAtRow_NoPropertyDescriptorNoValidation_ThrowsInvalidOperationException() - { - var style = new NullPropertyDescriptorDataGridColumnStyle(1); - var context = new BindingContext(); - var dataSource = new List { 1, 2, 3 }; - CurrencyManager source = Assert.IsType(context[dataSource]); - Assert.Throws(() => style.GetColumnValueAtRow(source, 0)); - } - - [Theory] - [InlineData(-1)] - [InlineData(3)] - public void GetColumnValueAtRow_InvalidIndex_ThrowsIndexOutOfRangeException(int rowNum) - { - PropertyDescriptor descriptor = TypeDescriptor.GetProperties(typeof(DataClass)).Find(nameof(DataClass.Value1), ignoreCase: false); - var style = new SubDataGridColumnStyle(descriptor); - var context = new BindingContext(); - var dataSource = new List { new DataClass { Value1 = 1 }, new DataClass { Value1 = 2 }, new DataClass { Value1 = 3 } }; - CurrencyManager source = Assert.IsType(context[dataSource]); - Assert.Throws((() => style.GetColumnValueAtRow(source, rowNum))); - } - - [Fact] - public void DataGridColumnStyle_Invalidate_InvokeSeveralTimesWithTableStyleWithDataGrid_Nop() - { - var dataGrid = new DataGrid(); - var tableStyle = new DataGridTableStyle(); - dataGrid.TableStyles.Add(tableStyle); - var style = new SubDataGridColumnStyle(); - tableStyle.GridColumnStyles.Add(style); - style.Invalidate(); - style.Invalidate(); - } - - [Fact] - public void DataGridColumnStyle_Invalidate_InvokeSeveralTimesWithTableStyle_Nop() - { - var tableStyle = new DataGridTableStyle(); - var style = new SubDataGridColumnStyle(); - tableStyle.GridColumnStyles.Add(style); - style.Invalidate(); - style.Invalidate(); - } - - [Fact] - public void DataGridColumnStyle_Invalidate_InvokeSeveralTimes_Nop() - { - var style = new SubDataGridColumnStyle(); - style.Invalidate(); - style.Invalidate(); - } - - public static IEnumerable Paint_TestData() - { - yield return new object[] { null, Rectangle.Empty, null, -2, null, null, false }; - - var image = new Bitmap(10, 10); - var style = new SubDataGridColumnStyle(); - var context = new BindingContext(); - var dataSource = new List { new DataClass { Value1 = 1 }, new DataClass { Value1 = 2 }, new DataClass { Value1 = 3 } }; - CurrencyManager source = Assert.IsType(context[dataSource]); - yield return new object[] { Graphics.FromImage(image), new Rectangle(1, 2, 3, 4), source, -1, new SolidBrush(Color.Red), new SolidBrush(Color.Blue), true }; - yield return new object[] { Graphics.FromImage(image), new Rectangle(-1, -2, -3, -4), source, 1, new SolidBrush(Color.Red), new SolidBrush(Color.Blue), false }; - } - - [Theory] - [MemberData(nameof(Paint_TestData))] - public void Paint_Invoke_Success(Graphics g, Rectangle bounds, CurrencyManager source, int rowNum, Brush backBrush, Brush foreBrush, bool alignToRight) - { - var style = new SubDataGridColumnStyle(); - int callCount = 0; - style.PaintAction = (actualG, actualBounds, actualSource, actualRowNum, actualAlignToRight) => - { - Assert.Same(g, actualG); - Assert.Same(source, actualSource); - Assert.Equal(bounds, actualBounds); - Assert.Equal(rowNum, actualRowNum); - Assert.Equal(alignToRight, actualAlignToRight); - callCount++; - }; - style.Paint(g, bounds, source, rowNum, backBrush, foreBrush, alignToRight); - Assert.Equal(1, callCount); - } - - [Fact] - public void DataGridColumnStyle_ReleaseHostedControl_InvokeSeveralTimes_Nop() - { - var style = new SubDataGridColumnStyle(); - style.ReleaseHostedControl(); - style.ReleaseHostedControl(); - } - - [Fact] - public void DataGridColumnStyle_ResetHeaderText_Invoke_Success() - { - var style = new SubDataGridColumnStyle - { - HeaderText = "HeaderText" - }; - style.ResetHeaderText(); - Assert.Empty(style.HeaderText); - - // Reset again. - style.ResetHeaderText(); - Assert.Empty(style.HeaderText); - } - - [Theory] - [InlineData(0, 2)] - [InlineData(1, 3)] - [InlineData(2, 4)] - public void SetColumnValueAtRow_PropertyDescriptor_ReturnsExpected(int rowNum, int value) - { - PropertyDescriptor descriptor = TypeDescriptor.GetProperties(typeof(DataClass)).Find(nameof(DataClass.Value1), ignoreCase: false); - var style = new SubDataGridColumnStyle(descriptor); - var context = new BindingContext(); - var dataSource = new List { new DataClass { Value1 = 1 }, new DataClass { Value1 = 2 }, new DataClass { Value1 = 3 } }; - CurrencyManager source = Assert.IsType(context[dataSource]); - source.Position = rowNum; - - style.SetColumnValueAtRow(source, rowNum, value); - Assert.Equal(value, style.GetColumnValueAtRow(source, rowNum)); - Assert.Equal(value, dataSource[rowNum].Value1); - } - - [Theory] - [InlineData(0, 2)] - [InlineData(1, 3)] - [InlineData(2, 4)] - public void SetColumnValueAtRow_IEditablePropertyDescriptor_ReturnsExpected(int rowNum, int value) - { - PropertyDescriptor descriptor = TypeDescriptor.GetProperties(typeof(EditableDataClass)).Find(nameof(EditableDataClass.Value), ignoreCase: false); - var style = new SubDataGridColumnStyle(descriptor); - var context = new BindingContext(); - var dataSource = new List { new EditableDataClass { Value = 1 }, new EditableDataClass { Value = 2 }, new EditableDataClass { Value = 3 } }; - CurrencyManager source = Assert.IsType(context[dataSource]); - source.Position = rowNum; - Assert.Equal(1, dataSource[rowNum].BeginEditCallCount); - - style.SetColumnValueAtRow(source, rowNum, value); - Assert.Equal(value, style.GetColumnValueAtRow(source, rowNum)); - Assert.Equal(value, dataSource[rowNum].Value); - Assert.Equal(2, dataSource[rowNum].BeginEditCallCount); - } - - [Theory] - [InlineData(0, 2)] - [InlineData(1, 3)] - [InlineData(2, 4)] - public void SetColumnValueAtRow_PropertyDescriptorCalledTwice_ReturnsExpected(int rowNum, int value) - { - PropertyDescriptor descriptor = TypeDescriptor.GetProperties(typeof(DataClass)).Find(nameof(DataClass.Value1), ignoreCase: false); - var style = new NullPropertyDescriptorDataGridColumnStyle(descriptor, 2); - var context = new BindingContext(); - var dataSource = new List { new DataClass { Value1 = 1 }, new DataClass { Value1 = 2 }, new DataClass { Value1 = 3 } }; - CurrencyManager source = Assert.IsType(context[dataSource]); - source.Position = rowNum; - - style.SetColumnValueAtRow(source, rowNum, value); - style.RequiredCallCount = int.MaxValue; - Assert.Equal(value, style.GetColumnValueAtRow(source, rowNum)); - Assert.Equal(value, dataSource[rowNum].Value1); - } - - [Fact] - public void DataGridColumnStyle_SetColumnValueAtRow_NullSource_ThrowsArgumentNullException() - { - var style = new SubDataGridColumnStyle(); - Assert.Throws("value", () => style.SetColumnValueAtRow(null, 0, 1)); - } - - [Fact] - public void DataGridColumnStyle_SetColumnValueAtRow_NoPropertyDescriptor_ThrowsInvalidOperationException() - { - var style = new SubDataGridColumnStyle(); - var context = new BindingContext(); - var dataSource = new List { 1, 2, 3 }; - CurrencyManager source = Assert.IsType(context[dataSource]); - Assert.Throws(() => style.SetColumnValueAtRow(source, 0, 1)); - } - - [Fact] - public void DataGridColumnStyle_SetColumnValueAtRow_NoPropertyDescriptorNoValidation_ThrowsInvalidOperationException() - { - var style = new NullPropertyDescriptorDataGridColumnStyle(1); - var context = new BindingContext(); - var dataSource = new List { 1, 2, 3 }; - CurrencyManager source = Assert.IsType(context[dataSource]); - Assert.Throws(() => style.SetColumnValueAtRow(source, 0, new object())); - } - - [Theory] - [InlineData(-1)] - [InlineData(1)] - [InlineData(2)] - [InlineData(3)] - public void SetColumnValueAtRow_InvalidIndex_ThrowsArgumentException(int rowNum) - { - PropertyDescriptor descriptor = TypeDescriptor.GetProperties(typeof(DataClass)).Find(nameof(DataClass.Value1), ignoreCase: false); - var style = new SubDataGridColumnStyle(descriptor); - var context = new BindingContext(); - var dataSource = new List { new DataClass { Value1 = 1 }, new DataClass { Value1 = 2 }, new DataClass { Value1 = 3 } }; - CurrencyManager source = Assert.IsType(context[dataSource]); - Assert.Throws("rowNum", () => style.SetColumnValueAtRow(source, rowNum, 1)); - } - - public static IEnumerable DataGrid_TestData() - { - yield return new object[] { null }; - yield return new object[] { new DataGrid() }; - } - - [Theory] - [MemberData(nameof(DataGrid_TestData))] - public void SetDataGrid_Invoke_CallsSetDataGridInColumn(DataGrid value) - { - var style = new SetDataGridInColumnDataGridColumnStyle(); - int callCount = 0; - style.SetDataGridInColumnAction = actualValue => - { - Assert.Same(value, actualValue); - callCount++; - }; - style.SetDataGrid(value); - Assert.Equal(1, callCount); - } - - public static IEnumerable SetDataGridInColumn_TestData() - { - yield return new object[] { null, null, null }; - - var dataGridWithoutListManager = new DataGrid(); - Assert.Null(dataGridWithoutListManager.ListManager); - yield return new object[] { null, dataGridWithoutListManager, null }; - - var dataGrid = new DataGrid - { - BindingContext = new BindingContext(), - DataSource = new List { new DataClass { Value1 = 1 } } - }; - Assert.NotNull(dataGrid.ListManager); - yield return new object[] { null, dataGrid, null }; - yield return new object[] { string.Empty, dataGrid, null }; - yield return new object[] { "NoSuchProperty", dataGrid, null }; - yield return new object[] { nameof(DataClass.ListProperty), dataGrid, null }; - yield return new object[] { nameof(DataClass.Value1).ToLower(), dataGrid, null }; - yield return new object[] { nameof(DataClass.Value1), dataGrid, TypeDescriptor.GetProperties(typeof(DataClass)).Find(nameof(DataClass.Value1), ignoreCase: false) }; - } - - [Theory] - [MemberData(nameof(SetDataGridInColumn_TestData))] - public void SetDataGridInColumn_DataGridWithoutListManager_Nop(string headerText, DataGrid value, object expectedPropertyDescriptor) - { - var style = new SubDataGridColumnStyle - { - HeaderText = headerText - }; - style.SetDataGrid(value); - Assert.Equal(expectedPropertyDescriptor, style.PropertyDescriptor); - } - - [Fact] - public void DataGridColumnStyle_SetDataGridInColumn_HasPropertyDescriptor_Nop() - { - PropertyDescriptor descriptor = TypeDescriptor.GetProperties(typeof(DataClass)).Find(nameof(DataClass.Value1), ignoreCase: false); - var style = new SubDataGridColumnStyle(descriptor) - { - HeaderText = nameof(DataClass.Value2) - }; - var dataGrid = new DataGrid - { - BindingContext = new BindingContext(), - DataSource = new List { new DataClass { Value1 = 1 } } - }; - Assert.NotNull(dataGrid.ListManager); - style.SetDataGridInColumn(dataGrid); - Assert.Same(descriptor, style.PropertyDescriptor); - } - - public static IEnumerable UpdateUI_TestData() - { - yield return new object[] { null, -2, null }; - - var style = new SubDataGridColumnStyle(); - var context = new BindingContext(); - var dataSource = new List { new DataClass { Value1 = 1 }, new DataClass { Value1 = 2 }, new DataClass { Value1 = 3 } }; - CurrencyManager source = Assert.IsType(context[dataSource]); - yield return new object[] { source, -1, string.Empty }; - yield return new object[] { source, 1, "displayText" }; - } - - [Theory] - [MemberData(nameof(UpdateUI_TestData))] - public void UpdateUI_Invoke_Nop(CurrencyManager source, int rowNum, string displayText) - { - var style = new SubDataGridColumnStyle(); - style.UpdateUI(source, rowNum, displayText); - } - - private class DataClass - { - public int Value1 { get; set; } - public int Value2 { get; set; } - - public IList ListProperty { get; set; } - } - - private class EditableDataClass : IEditableObject - { - public int BeginEditCallCount { get; set; } - - public void BeginEdit() => BeginEditCallCount++; - - public void CancelEdit() => throw new NotImplementedException(); - - public void EndEdit() { } - - public int Value { get; set; } - } - - private class ReadOnlyDataClass - { - public int Value1 { get; } - } - - private abstract class CustomDataGridColumnStyle : DataGridColumnStyle - { - public CustomDataGridColumnStyle() - { - } - - public CustomDataGridColumnStyle(PropertyDescriptor prop) : base(prop) - { - } - - public CustomDataGridColumnStyle(PropertyDescriptor prop, bool isDefault) : base(prop, isDefault) - { - } - - protected internal override void Abort(int rowNum) - { - throw new NotImplementedException(); - } - - protected internal override bool Commit(CurrencyManager dataSource, int rowNum) - { - throw new NotImplementedException(); - } - - protected internal override void Edit(CurrencyManager source, int rowNum, Rectangle bounds, bool readOnly, string displayText, bool cellIsVisible) - { - throw new NotImplementedException(); - } - - protected internal override Size GetPreferredSize(Graphics g, object value) - { - throw new NotImplementedException(); - } - - protected internal override int GetMinimumHeight() - { - throw new NotImplementedException(); - } - - protected internal override int GetPreferredHeight(Graphics g, object value) - { - throw new NotImplementedException(); - } - - protected internal override void Paint(Graphics g, Rectangle bounds, CurrencyManager source, int rowNum) - { - throw new NotImplementedException(); - } - - protected internal override void Paint(Graphics g, Rectangle bounds, CurrencyManager source, int rowNum, bool alignToRight) - { - throw new NotImplementedException(); - } - } - - private class SubDataGridColumnStyle : CustomDataGridColumnStyle - { - public SubDataGridColumnStyle() - { - } - - public SubDataGridColumnStyle(PropertyDescriptor prop) : base(prop) - { - } - - public SubDataGridColumnStyle(PropertyDescriptor prop, bool isDefault) : base(prop, isDefault) - { - } - - public new bool CanRaiseEvents => base.CanRaiseEvents; - - public new bool DesignMode => base.DesignMode; - - public new EventHandlerList Events => base.Events; - - public new int FontHeight => base.FontHeight; - - public new void BeginUpdate() => base.BeginUpdate(); - - public new void CheckValidDataSource(CurrencyManager value) => base.CheckValidDataSource(value); - - public new AccessibleObject CreateHeaderAccessibleObject() => base.CreateHeaderAccessibleObject(); - - public new void EndUpdate() => base.EndUpdate(); - - public new void Invalidate() => base.Invalidate(); - - public new void SetDataGrid(DataGrid value) => base.SetDataGrid(value); - - public new void SetDataGridInColumn(DataGrid value) => base.SetDataGridInColumn(value); - - public Action EditAction { get; set; } - - protected internal override void Edit(CurrencyManager source, int rowNum, Rectangle bounds, bool readOnly, string displayText, bool cellIsVisible) - { - EditAction(source, rowNum, bounds, readOnly, displayText, cellIsVisible); - } - - public Action PaintAction { get; set; } - - protected internal override void Paint(Graphics g, Rectangle bounds, CurrencyManager source, int rowNum, bool alignToRight) - { - PaintAction(g, bounds, source, rowNum, alignToRight); - } - } - - private class NullPropertyDescriptorDataGridColumnStyle : CustomDataGridColumnStyle - { - public NullPropertyDescriptorDataGridColumnStyle(int requiredCallCount) - { - RequiredCallCount = requiredCallCount; - } - - public NullPropertyDescriptorDataGridColumnStyle(PropertyDescriptor prop, int requiredCallCount) : base(prop) - { - RequiredCallCount = requiredCallCount; - } - - public int RequiredCallCount { get; set; } - - private int _callCount = 0; - - public override PropertyDescriptor PropertyDescriptor - { - get - { - if (_callCount < RequiredCallCount) - { - _callCount++; - return TypeDescriptor.GetProperties(typeof(DataClass)).Find(nameof(DataClass.Value1), ignoreCase: false); - } - - return null; - } - set { } - } - } - - private class InvalidateDataGridColumnStyle : CustomDataGridColumnStyle - { - public new void BeginUpdate() => base.BeginUpdate(); - - public new void EndUpdate() => base.EndUpdate(); - - public void CallInvalidate() => Invalidate(); - - public int InvalidateCallCount { get; set; } - - protected override void Invalidate() - { - InvalidateCallCount++; - base.Invalidate(); - } - } - - private class SetDataGridInColumnDataGridColumnStyle : CustomDataGridColumnStyle - { - public new void SetDataGrid(DataGrid value) => base.SetDataGrid(value); - - public Action SetDataGridInColumnAction { get; set; } - - protected override void SetDataGridInColumn(DataGrid value) - { - SetDataGridInColumnAction(value); - } - } - } -} diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridTableStyleTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridTableStyleTests.cs deleted file mode 100644 index eca6e956312..00000000000 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridTableStyleTests.cs +++ /dev/null @@ -1,4997 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Collections.Generic; -using System.ComponentModel; -using System.Drawing; -using System.Linq; -using WinForms.Common.Tests; -using Xunit; - -namespace System.Windows.Forms.Tests -{ - public class DataGridTableStyleTests - { - [Fact] - public void DataGridTableStyle_Ctor_Default() - { - var style = new SubDataGridTableStyle(); - Assert.True(style.AllowSorting); - Assert.Equal(SystemColors.Window, style.AlternatingBackColor); - Assert.Equal(SystemColors.Window, style.BackColor); - Assert.True(style.CanRaiseEvents); - Assert.True(style.ColumnHeadersVisible); - Assert.Null(style.Container); - Assert.Null(style.DataGrid); - Assert.False(style.DesignMode); - Assert.NotNull(style.Events); - Assert.Same(style.Events, style.Events); - Assert.Equal(SystemColors.WindowText, style.ForeColor); - Assert.Empty(style.GridColumnStyles); - Assert.Same(style.GridColumnStyles, style.GridColumnStyles); - Assert.Equal(SystemColors.Control, style.GridLineColor); - Assert.Equal(DataGridLineStyle.Solid, style.GridLineStyle); - Assert.Equal(SystemColors.Control, style.HeaderBackColor); - Assert.Same(Control.DefaultFont, style.HeaderFont); - Assert.Equal(SystemColors.ControlText, style.HeaderForeColor); - Assert.Equal(SystemColors.HotTrack, style.LinkColor); - Assert.Equal(SystemColors.HotTrack, style.LinkHoverColor); - Assert.Empty(style.MappingName); - Assert.Equal(75, style.PreferredColumnWidth); - Assert.Equal(Control.DefaultFont.Height + 3, style.PreferredRowHeight); - Assert.False(style.ReadOnly); - Assert.True(style.RowHeadersVisible); - Assert.Equal(35, style.RowHeaderWidth); - Assert.Equal(SystemColors.ActiveCaption, style.SelectionBackColor); - Assert.Equal(SystemColors.ActiveCaptionText, style.SelectionForeColor); - Assert.Null(style.Site); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetBoolTheoryData))] - public void DataGridTableStyle_Ctor_Bool(bool isDefaultTableStyle) - { - var style = new SubDataGridTableStyle(isDefaultTableStyle); - Assert.True(style.AllowSorting); - Assert.Equal(SystemColors.Window, style.AlternatingBackColor); - Assert.Equal(SystemColors.Window, style.BackColor); - Assert.True(style.CanRaiseEvents); - Assert.True(style.ColumnHeadersVisible); - Assert.Null(style.Container); - Assert.Null(style.DataGrid); - Assert.False(style.DesignMode); - Assert.NotNull(style.Events); - Assert.Same(style.Events, style.Events); - Assert.Equal(SystemColors.WindowText, style.ForeColor); - Assert.Empty(style.GridColumnStyles); - Assert.Same(style.GridColumnStyles, style.GridColumnStyles); - Assert.Equal(SystemColors.Control, style.GridLineColor); - Assert.Equal(DataGridLineStyle.Solid, style.GridLineStyle); - Assert.Equal(SystemColors.Control, style.HeaderBackColor); - Assert.Same(Control.DefaultFont, style.HeaderFont); - Assert.Equal(SystemColors.ControlText, style.HeaderForeColor); - Assert.Equal(SystemColors.HotTrack, style.LinkColor); - Assert.Equal(SystemColors.HotTrack, style.LinkHoverColor); - Assert.Empty(style.MappingName); - Assert.Equal(75, style.PreferredColumnWidth); - Assert.Equal(Control.DefaultFont.Height + 3, style.PreferredRowHeight); - Assert.False(style.ReadOnly); - Assert.True(style.RowHeadersVisible); - Assert.Equal(35, style.RowHeaderWidth); - Assert.Equal(SystemColors.ActiveCaption, style.SelectionBackColor); - Assert.Equal(SystemColors.ActiveCaptionText, style.SelectionForeColor); - Assert.Null(style.Site); - } - - [Fact] - public void DataGridTableStyle_DefaultTableStyle_Get_ReturnsExpected() - { - DataGridTableStyle style = DataGridTableStyle.DefaultTableStyle; - Assert.True(style.AllowSorting); - Assert.Equal(SystemColors.Window, style.AlternatingBackColor); - Assert.Equal(SystemColors.Window, style.BackColor); - Assert.True(style.ColumnHeadersVisible); - Assert.Null(style.Container); - Assert.Null(style.DataGrid); - Assert.Equal(SystemColors.WindowText, style.ForeColor); - Assert.Empty(style.GridColumnStyles); - Assert.Same(style.GridColumnStyles, style.GridColumnStyles); - Assert.Equal(SystemColors.Control, style.GridLineColor); - Assert.Equal(DataGridLineStyle.Solid, style.GridLineStyle); - Assert.Equal(SystemColors.Control, style.HeaderBackColor); - Assert.Same(Control.DefaultFont, style.HeaderFont); - Assert.Equal(SystemColors.ControlText, style.HeaderForeColor); - Assert.Equal(SystemColors.HotTrack, style.LinkColor); - Assert.Equal(SystemColors.HotTrack, style.LinkHoverColor); - Assert.Empty(style.MappingName); - Assert.Equal(75, style.PreferredColumnWidth); - Assert.Equal(Control.DefaultFont.Height + 3, style.PreferredRowHeight); - Assert.False(style.ReadOnly); - Assert.True(style.RowHeadersVisible); - Assert.Equal(35, style.RowHeaderWidth); - Assert.Equal(SystemColors.ActiveCaption, style.SelectionBackColor); - Assert.Equal(SystemColors.ActiveCaptionText, style.SelectionForeColor); - Assert.Null(style.Site); - Assert.Same(style, DataGridTableStyle.DefaultTableStyle); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetBoolTheoryData))] - public void DataGridTableStyle_AllowSorting_Set_GetReturnsExpected(bool value) - { - var style = new DataGridTableStyle - { - AllowSorting = value - }; - Assert.Equal(value, style.AllowSorting); - - // Set same. - style.AllowSorting = value; - Assert.Equal(value, style.AllowSorting); - - // Set different - style.AllowSorting = !value; - Assert.Equal(!value, style.AllowSorting); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetBoolTheoryData))] - public void DataGridTableStyle_AllowSorting_SetWithDataGrid_DoesNotCallInvalidate(bool value) - { - var dataGrid = new DataGrid(); - var style = new DataGridTableStyle - { - DataGrid = dataGrid - }; - int invalidatedCallCount = 0; - dataGrid.Invalidated += (sender, e) => invalidatedCallCount++; - Assert.NotEqual(IntPtr.Zero, dataGrid.Handle); - - style.AllowSorting = value; - Assert.Equal(value, style.AllowSorting); - Assert.Equal(0, invalidatedCallCount); - - // Set same. - style.AllowSorting = value; - Assert.Equal(value, style.AllowSorting); - Assert.Equal(0, invalidatedCallCount); - - // Set different - style.AllowSorting = !value; - Assert.Equal(!value, style.AllowSorting); - Assert.Equal(0, invalidatedCallCount); - } - - [Fact] - public void DataGridTableStyle_AllowSorting_SetWithHandler_CallsAllowSortingChanged() - { - var style = new DataGridTableStyle - { - AllowSorting = true - }; - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(style, sender); - Assert.Same(EventArgs.Empty, e); - callCount++; - }; - style.AllowSortingChanged += handler; - - // Set different. - style.AllowSorting = false; - Assert.False(style.AllowSorting); - Assert.Equal(1, callCount); - - // Set same. - style.AllowSorting = false; - Assert.False(style.AllowSorting); - Assert.Equal(1, callCount); - - // Set different. - style.AllowSorting = true; - Assert.True(style.AllowSorting); - Assert.Equal(2, callCount); - - // Remove handler. - style.AllowSortingChanged -= handler; - style.AllowSorting = false; - Assert.False(style.AllowSorting); - Assert.Equal(2, callCount); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetBoolTheoryData))] - public void DataGridTableStyle_AllowSorting_SetDefaultTableStyle_ThrowsArgumentException(bool value) - { - var style = new DataGridTableStyle(isDefaultTableStyle: true); - Assert.Throws(null, () => style.AllowSorting = value); - Assert.True(style.AllowSorting); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetColorTheoryData))] - public void DataGridTableStyle_AlternatingBackColor_Set_GetReturnsExpected(Color value) - { - var style = new DataGridTableStyle - { - AlternatingBackColor = value - }; - Assert.Equal(value, style.AlternatingBackColor); - - // Set same. - style.AlternatingBackColor = value; - Assert.Equal(value, style.AlternatingBackColor); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetColorTheoryData))] - public void DataGridTableStyle_AlternatingBackColor_SetWithDataGrid_CallsInvalidate(Color value) - { - var dataGrid = new DataGrid(); - var style = new DataGridTableStyle - { - DataGrid = dataGrid - }; - int invalidatedCallCount = 0; - dataGrid.Invalidated += (sender, e) => invalidatedCallCount++; - Assert.NotEqual(IntPtr.Zero, dataGrid.Handle); - - style.AlternatingBackColor = value; - Assert.Equal(value, style.AlternatingBackColor); - Assert.Equal(1, invalidatedCallCount); - - // Set same. - style.AlternatingBackColor = value; - Assert.Equal(value, style.AlternatingBackColor); - Assert.Equal(1, invalidatedCallCount); - } - - [Fact] - public void DataGridTableStyle_AlternatingBackColor_SetWithHandler_CallsAlternatingBackColorChanged() - { - var style = new DataGridTableStyle(); - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(style, sender); - Assert.Same(EventArgs.Empty, e); - callCount++; - }; - style.AlternatingBackColorChanged += handler; - - // Set different. - style.AlternatingBackColor = Color.Red; - Assert.Equal(Color.Red, style.AlternatingBackColor); - Assert.Equal(1, callCount); - - // Set same. - style.AlternatingBackColor = Color.Red; - Assert.Equal(Color.Red, style.AlternatingBackColor); - Assert.Equal(1, callCount); - - // Set different. - style.AlternatingBackColor = Color.Blue; - Assert.Equal(Color.Blue, style.AlternatingBackColor); - Assert.Equal(2, callCount); - - // Remove handler. - style.AlternatingBackColorChanged -= handler; - style.AlternatingBackColor = Color.Red; - Assert.Equal(Color.Red, style.AlternatingBackColor); - Assert.Equal(2, callCount); - } - - public static IEnumerable InvalidColor_TestData() - { - yield return new object[] { Color.Empty }; - yield return new object[] { Color.FromArgb(244, 1, 2, 3) }; - } - - [Theory] - [MemberData(nameof(InvalidColor_TestData))] - public void DataGridTableStyle_AlternatingBackColor_SetInvalid_ThrowsArgumentException(Color value) - { - var style = new DataGridTableStyle(); - Assert.Throws("value", () => style.AlternatingBackColor = value); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetColorWithEmptyTheoryData))] - public void DataGridTableStyle_AlternatingBackColor_SetDefaultTableStyle_ThrowsArgumentException(Color value) - { - var style = new DataGridTableStyle(isDefaultTableStyle: true); - Assert.Throws(null, () => style.AlternatingBackColor = value); - Assert.Equal(SystemColors.Window, style.AlternatingBackColor); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetColorTheoryData))] - public void DataGridTableStyle_BackColor_Set_GetReturnsExpected(Color value) - { - var style = new DataGridTableStyle - { - BackColor = value - }; - Assert.Equal(value, style.BackColor); - - // Set same. - style.BackColor = value; - Assert.Equal(value, style.BackColor); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetColorTheoryData))] - public void DataGridTableStyle_BackColor_SetWithDataGrid_CallsInvalidate(Color value) - { - var dataGrid = new DataGrid(); - var style = new DataGridTableStyle - { - DataGrid = dataGrid - }; - int invalidatedCallCount = 0; - dataGrid.Invalidated += (sender, e) => invalidatedCallCount++; - Assert.NotEqual(IntPtr.Zero, dataGrid.Handle); - - style.BackColor = value; - Assert.Equal(value, style.BackColor); - Assert.Equal(1, invalidatedCallCount); - - // Set same. - style.BackColor = value; - Assert.Equal(value, style.BackColor); - Assert.Equal(1, invalidatedCallCount); - } - - [Fact] - public void DataGridTableStyle_BackColor_SetWithHandler_CallsBackColorChanged() - { - var style = new DataGridTableStyle(); - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(style, sender); - Assert.Same(EventArgs.Empty, e); - callCount++; - }; - style.BackColorChanged += handler; - - // Set different. - style.BackColor = Color.Red; - Assert.Equal(Color.Red, style.BackColor); - Assert.Equal(1, callCount); - - // Set same. - style.BackColor = Color.Red; - Assert.Equal(Color.Red, style.BackColor); - Assert.Equal(1, callCount); - - // Set different. - style.BackColor = Color.Blue; - Assert.Equal(Color.Blue, style.BackColor); - Assert.Equal(2, callCount); - - // Remove handler. - style.BackColorChanged -= handler; - style.BackColor = Color.Red; - Assert.Equal(Color.Red, style.BackColor); - Assert.Equal(2, callCount); - } - - [Theory] - [MemberData(nameof(InvalidColor_TestData))] - public void DataGridTableStyle_BackColor_SetInvalid_ThrowsArgumentException(Color value) - { - var style = new DataGridTableStyle(); - Assert.Throws("value", () => style.BackColor = value); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetColorWithEmptyTheoryData))] - public void DataGridTableStyle_BackColor_SetDefaultTableStyle_ThrowsArgumentException(Color value) - { - var style = new DataGridTableStyle(isDefaultTableStyle: true); - Assert.Throws(null, () => style.BackColor = value); - Assert.Equal(SystemColors.Window, style.BackColor); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetBoolTheoryData))] - public void DataGridTableStyle_ColumnHeadersVisible_Set_GetReturnsExpected(bool value) - { - var style = new DataGridTableStyle - { - ColumnHeadersVisible = value - }; - Assert.Equal(value, style.ColumnHeadersVisible); - - // Set same. - style.ColumnHeadersVisible = value; - Assert.Equal(value, style.ColumnHeadersVisible); - - // Set different - style.ColumnHeadersVisible = !value; - Assert.Equal(!value, style.ColumnHeadersVisible); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetBoolTheoryData))] - public void DataGridTableStyle_ColumnHeadersVisible_SetDefaultTableStyle_GetReturnsExpected(bool value) - { - var style = new DataGridTableStyle(isDefaultTableStyle: true) - { - ColumnHeadersVisible = value - }; - Assert.Equal(value, style.ColumnHeadersVisible); - - // Set same. - style.ColumnHeadersVisible = value; - Assert.Equal(value, style.ColumnHeadersVisible); - - // Set different - style.ColumnHeadersVisible = !value; - Assert.Equal(!value, style.ColumnHeadersVisible); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetBoolTheoryData))] - public void DataGridTableStyle_ColumnHeadersVisible_SetWithDataGrid_DoesNotCallInvalidate(bool value) - { - var dataGrid = new DataGrid(); - var style = new DataGridTableStyle - { - DataGrid = dataGrid - }; - int invalidatedCallCount = 0; - dataGrid.Invalidated += (sender, e) => invalidatedCallCount++; - Assert.NotEqual(IntPtr.Zero, dataGrid.Handle); - - style.ColumnHeadersVisible = value; - Assert.Equal(value, style.ColumnHeadersVisible); - Assert.Equal(0, invalidatedCallCount); - - // Set same. - style.ColumnHeadersVisible = value; - Assert.Equal(value, style.ColumnHeadersVisible); - Assert.Equal(0, invalidatedCallCount); - - // Set different - style.ColumnHeadersVisible = !value; - Assert.Equal(!value, style.ColumnHeadersVisible); - Assert.Equal(0, invalidatedCallCount); - } - - [Fact] - public void DataGridTableStyle_ColumnHeadersVisible_SetWithHandler_CallsColumnHeadersVisibleChanged() - { - var style = new DataGridTableStyle - { - ColumnHeadersVisible = true - }; - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(style, sender); - Assert.Same(EventArgs.Empty, e); - callCount++; - }; - style.ColumnHeadersVisibleChanged += handler; - - // Set different. - style.ColumnHeadersVisible = false; - Assert.False(style.ColumnHeadersVisible); - Assert.Equal(1, callCount); - - // Set same. - style.ColumnHeadersVisible = false; - Assert.False(style.ColumnHeadersVisible); - Assert.Equal(1, callCount); - - // Set different. - style.ColumnHeadersVisible = true; - Assert.True(style.ColumnHeadersVisible); - Assert.Equal(2, callCount); - - // Remove handler. - style.ColumnHeadersVisibleChanged -= handler; - style.ColumnHeadersVisible = false; - Assert.False(style.ColumnHeadersVisible); - Assert.Equal(2, callCount); - } - - public static IEnumerable DataGrid_TestData() - { - yield return new object[] { null }; - yield return new object[] { new DataGrid() }; - } - - [Theory] - [MemberData(nameof(DataGrid_TestData))] - public void DataGridTableStyle_DataGrid_Set_GetReturnsExpected(DataGrid value) - { - var style = new DataGridTableStyle - { - DataGrid = value - }; - Assert.Same(value, style.DataGrid); - Assert.Same(value?.Font ?? Control.DefaultFont, style.HeaderFont); - - // Set same. - style.DataGrid = value; - Assert.Same(value, style.DataGrid); - Assert.Same(value?.Font ?? Control.DefaultFont, style.HeaderFont); - } - - [Theory] - [MemberData(nameof(DataGrid_TestData))] - public void DataGridTableStyle_DataGrid_SetDefaultTableStyle_GetReturnsExpected(DataGrid value) - { - var style = new DataGridTableStyle(isDefaultTableStyle: true) - { - DataGrid = value - }; - Assert.Same(value, style.DataGrid); - Assert.Same(value?.Font ?? Control.DefaultFont, style.HeaderFont); - - // Set same. - style.DataGrid = value; - Assert.Same(value, style.DataGrid); - Assert.Same(value?.Font ?? Control.DefaultFont, style.HeaderFont); - } - - [Fact] - public void DataGridTableStyle_DataGrid_SetWithGridColumnStyles_SetsDataGridOnGridColumnStyles() - { - var dataGrid = new DataGrid(); - var style = new DataGridTableStyle(); - var columnStyle = new SubDataGridColumnStyle(); - int callCount = 0; - columnStyle.SetDataGridInColumnAction = actualDataGrid => - { - Assert.Same(dataGrid, actualDataGrid); - callCount++; - }; - style.GridColumnStyles.Add(columnStyle); - - style.DataGrid = dataGrid; - Assert.Same(dataGrid, style.DataGrid); - Assert.Equal(1, callCount); - - // Set same. - style.DataGrid = dataGrid; - Assert.Same(dataGrid, style.DataGrid); - Assert.Equal(2, callCount); - - // Set null. - style.DataGrid = null; - Assert.Null(style.DataGrid); - Assert.Equal(2, callCount); - } - - [Fact] - public void DataGridTableStyle_DataGrid_SetWithGridColumnStylesInitializing_DoesNotSetDataGridOnGridColumnStyles() - { - var dataGrid = new DataGrid(); - var style = new DataGridTableStyle(); - var columnStyle = new SubDataGridColumnStyle(); - int callCount = 0; - columnStyle.SetDataGridInColumnAction = actualDataGrid => - { - Assert.Same(dataGrid, actualDataGrid); - callCount++; - }; - style.GridColumnStyles.Add(columnStyle); - dataGrid.BeginInit(); - - style.DataGrid = dataGrid; - Assert.Same(dataGrid, style.DataGrid); - Assert.Equal(0, callCount); - - // Set same. - style.DataGrid = dataGrid; - Assert.Same(dataGrid, style.DataGrid); - Assert.Equal(0, callCount); - - // Set null. - style.DataGrid = null; - Assert.Null(style.DataGrid); - Assert.Equal(0, callCount); - } - - public static IEnumerable ForeColor_Set_TestData() - { - yield return new object[] { Color.FromArgb(254, 1, 2, 3) }; - yield return new object[] { Color.Red }; - } - - [Theory] - [MemberData(nameof(ForeColor_Set_TestData))] - public void DataGridTableStyle_ForeColor_Set_GetReturnsExpected(Color value) - { - var style = new DataGridTableStyle - { - ForeColor = value - }; - Assert.Equal(value, style.ForeColor); - - // Set same. - style.ForeColor = value; - Assert.Equal(value, style.ForeColor); - } - - [Theory] - [MemberData(nameof(ForeColor_Set_TestData))] - public void DataGridTableStyle_ForeColor_SetWithDataGrid_CallsInvalidate(Color value) - { - var dataGrid = new DataGrid(); - var style = new DataGridTableStyle - { - DataGrid = dataGrid - }; - int invalidatedCallCount = 0; - dataGrid.Invalidated += (sender, e) => invalidatedCallCount++; - Assert.NotEqual(IntPtr.Zero, dataGrid.Handle); - - style.ForeColor = value; - Assert.Equal(value, style.ForeColor); - Assert.Equal(1, invalidatedCallCount); - - // Set same. - style.ForeColor = value; - Assert.Equal(value, style.ForeColor); - Assert.Equal(1, invalidatedCallCount); - } - - [Fact] - public void DataGridTableStyle_ForeColor_SetWithHandler_CallsForeColorChanged() - { - var style = new DataGridTableStyle(); - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(style, sender); - Assert.Same(EventArgs.Empty, e); - callCount++; - }; - style.ForeColorChanged += handler; - - // Set different. - style.ForeColor = Color.Red; - Assert.Equal(Color.Red, style.ForeColor); - Assert.Equal(1, callCount); - - // Set same. - style.ForeColor = Color.Red; - Assert.Equal(Color.Red, style.ForeColor); - Assert.Equal(1, callCount); - - // Set different. - style.ForeColor = Color.Blue; - Assert.Equal(Color.Blue, style.ForeColor); - Assert.Equal(2, callCount); - - // Remove handler. - style.ForeColorChanged -= handler; - style.ForeColor = Color.Red; - Assert.Equal(Color.Red, style.ForeColor); - Assert.Equal(2, callCount); - } - - [Fact] - public void DataGridTableStyle_ForeColor_SetEmpty_ThrowsArgumentException() - { - var style = new DataGridTableStyle(); - Assert.Throws("value", () => style.ForeColor = Color.Empty); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetColorWithEmptyTheoryData))] - public void DataGridTableStyle_ForeColor_SetDefaultTableStyle_ThrowsArgumentException(Color value) - { - var style = new DataGridTableStyle(isDefaultTableStyle: true); - Assert.Throws(null, () => style.ForeColor = value); - Assert.Equal(SystemColors.WindowText, style.ForeColor); - } - - public static IEnumerable GridLineColor_Set_TestData() - { - yield return new object[] { Color.FromArgb(254, 1, 2, 3) }; - yield return new object[] { Color.Red }; - } - - [Theory] - [MemberData(nameof(GridLineColor_Set_TestData))] - public void DataGridTableStyle_GridLineColor_Set_GetReturnsExpected(Color value) - { - var style = new DataGridTableStyle - { - GridLineColor = value - }; - Assert.Equal(value, style.GridLineColor); - - // Set same. - style.GridLineColor = value; - Assert.Equal(value, style.GridLineColor); - } - - [Theory] - [MemberData(nameof(GridLineColor_Set_TestData))] - public void DataGridTableStyle_GridLineColor_SetWithDataGrid_DoesNotCallInvalidate(Color value) - { - var dataGrid = new DataGrid(); - var style = new DataGridTableStyle - { - DataGrid = dataGrid - }; - int invalidatedCallCount = 0; - dataGrid.Invalidated += (sender, e) => invalidatedCallCount++; - Assert.NotEqual(IntPtr.Zero, dataGrid.Handle); - - style.GridLineColor = value; - Assert.Equal(value, style.GridLineColor); - Assert.Equal(0, invalidatedCallCount); - - // Set same. - style.GridLineColor = value; - Assert.Equal(value, style.GridLineColor); - Assert.Equal(0, invalidatedCallCount); - } - - [Fact] - public void DataGridTableStyle_GridLineColor_SetWithHandler_CallsGridLineColorChanged() - { - var style = new DataGridTableStyle(); - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(style, sender); - Assert.Same(EventArgs.Empty, e); - callCount++; - }; - style.GridLineColorChanged += handler; - - // Set different. - style.GridLineColor = Color.Red; - Assert.Equal(Color.Red, style.GridLineColor); - Assert.Equal(1, callCount); - - // Set same. - style.GridLineColor = Color.Red; - Assert.Equal(Color.Red, style.GridLineColor); - Assert.Equal(1, callCount); - - // Set different. - style.GridLineColor = Color.Blue; - Assert.Equal(Color.Blue, style.GridLineColor); - Assert.Equal(2, callCount); - - // Remove handler. - style.GridLineColorChanged -= handler; - style.GridLineColor = Color.Red; - Assert.Equal(Color.Red, style.GridLineColor); - Assert.Equal(2, callCount); - } - - [Fact] - public void DataGridTableStyle_GridLineColor_SetEmpty_ThrowsArgumentException() - { - var style = new DataGridTableStyle(); - Assert.Throws("value", () => style.GridLineColor = Color.Empty); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetColorWithEmptyTheoryData))] - public void DataGridTableStyle_GridLineColor_SetDefaultTableStyle_ThrowsArgumentException(Color value) - { - var style = new DataGridTableStyle(isDefaultTableStyle: true); - Assert.Throws(null, () => style.GridLineColor = value); - Assert.Equal(SystemColors.Control, style.GridLineColor); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetEnumTypeTheoryData), typeof(DataGridLineStyle))] - public void DataGridTableStyle_GridLineStyle_Set_GetReturnsExpected(DataGridLineStyle value) - { - var style = new DataGridTableStyle - { - GridLineStyle = value - }; - Assert.Equal(value, style.GridLineStyle); - - // Set same. - style.GridLineStyle = value; - Assert.Equal(value, style.GridLineStyle); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetEnumTypeTheoryData), typeof(DataGridLineStyle))] - public void DataGridTableStyle_GridLineStyle_SetWithDataGrid_DoesNotCallInvalidate(DataGridLineStyle value) - { - var dataGrid = new DataGrid(); - var style = new DataGridTableStyle - { - DataGrid = dataGrid - }; - int invalidatedCallCount = 0; - dataGrid.Invalidated += (sender, e) => invalidatedCallCount++; - Assert.NotEqual(IntPtr.Zero, dataGrid.Handle); - - style.GridLineStyle = value; - Assert.Equal(value, style.GridLineStyle); - Assert.Equal(0, invalidatedCallCount); - - // Set same. - style.GridLineStyle = value; - Assert.Equal(value, style.GridLineStyle); - Assert.Equal(0, invalidatedCallCount); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetEnumTypeTheoryDataInvalid), typeof(DataGridLineStyle))] - public void DataGridTableStyle_GridLineStyle_SetInvalidValue_ThrowsInvalidEnumArgumentException(DataGridLineStyle value) - { - var style = new DataGridTableStyle(); - Assert.Throws("value", () => style.GridLineStyle = value); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetEnumTypeTheoryData), typeof(DataGridLineStyle))] - [CommonMemberData(nameof(CommonTestHelper.GetEnumTypeTheoryDataInvalid), typeof(DataGridLineStyle))] - public void DataGridTableStyle_GridLineStyle_SetDefaultTableStyle_ThrowsArgumentException(DataGridLineStyle value) - { - var style = new DataGridTableStyle(isDefaultTableStyle: true); - Assert.Throws(null, () => style.GridLineStyle = value); - Assert.Equal(DataGridLineStyle.Solid, style.GridLineStyle); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetColorTheoryData))] - public void DataGridTableStyle_HeaderBackColor_Set_GetReturnsExpected(Color value) - { - var style = new DataGridTableStyle - { - HeaderBackColor = value - }; - Assert.Equal(value, style.HeaderBackColor); - - // Set same. - style.HeaderBackColor = value; - Assert.Equal(value, style.HeaderBackColor); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetColorTheoryData))] - public void DataGridTableStyle_HeaderBackColor_SetWithDataGrid_DoesNotCallInvalidate(Color value) - { - var dataGrid = new DataGrid(); - var style = new DataGridTableStyle - { - DataGrid = dataGrid - }; - int invalidatedCallCount = 0; - dataGrid.Invalidated += (sender, e) => invalidatedCallCount++; - Assert.NotEqual(IntPtr.Zero, dataGrid.Handle); - - style.HeaderBackColor = value; - Assert.Equal(value, style.HeaderBackColor); - Assert.Equal(0, invalidatedCallCount); - - // Set same. - style.HeaderBackColor = value; - Assert.Equal(value, style.HeaderBackColor); - Assert.Equal(0, invalidatedCallCount); - } - - [Fact] - public void DataGridTableStyle_HeaderBackColor_SetWithHandler_CallsHeaderBackColorChanged() - { - var style = new DataGridTableStyle(); - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(style, sender); - Assert.Same(EventArgs.Empty, e); - callCount++; - }; - style.HeaderBackColorChanged += handler; - - // Set different. - style.HeaderBackColor = Color.Red; - Assert.Equal(Color.Red, style.HeaderBackColor); - Assert.Equal(1, callCount); - - // Set same. - style.HeaderBackColor = Color.Red; - Assert.Equal(Color.Red, style.HeaderBackColor); - Assert.Equal(1, callCount); - - // Set different. - style.HeaderBackColor = Color.Blue; - Assert.Equal(Color.Blue, style.HeaderBackColor); - Assert.Equal(2, callCount); - - // Remove handler. - style.HeaderBackColorChanged -= handler; - style.HeaderBackColor = Color.Red; - Assert.Equal(Color.Red, style.HeaderBackColor); - Assert.Equal(2, callCount); - } - - [Theory] - [MemberData(nameof(InvalidColor_TestData))] - public void DataGridTableStyle_HeaderBackColor_SetInvalid_ThrowsArgumentException(Color value) - { - var style = new DataGridTableStyle(); - Assert.Throws("value", () => style.HeaderBackColor = value); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetColorWithEmptyTheoryData))] - public void DataGridTableStyle_HeaderBackColor_SetDefaultTableStyle_ThrowsArgumentException(Color value) - { - var style = new DataGridTableStyle(isDefaultTableStyle: true); - Assert.Throws(null, () => style.HeaderBackColor = value); - Assert.Equal(SystemColors.Control, style.HeaderBackColor); - } - - [Fact] - public void DataGridTableStyle_HeaderFont_Set_GetReturnsExpected() - { - var font1 = new Font(SystemFonts.MessageBoxFont.FontFamily, 10); - var font2 = new Font(SystemFonts.MessageBoxFont.FontFamily, 11); - var style = new DataGridTableStyle - { - HeaderFont = font1 - }; - Assert.Same(font1, style.HeaderFont); - - // Set same. - style.HeaderFont = font1; - Assert.Same(font1, style.HeaderFont); - - // Set null. - style.HeaderFont = null; - Assert.Same(Control.DefaultFont, style.HeaderFont); - - // Set null again. - style.HeaderFont = null; - Assert.Same(Control.DefaultFont, style.HeaderFont); - - // Set different. - style.HeaderFont = font1; - Assert.Same(font1, style.HeaderFont); - - // Set different. - style.HeaderFont = font2; - Assert.Same(font2, style.HeaderFont); - } - - [Fact] - public void DataGridTableStyle_HeaderFont_SetWithDataGrid_DoesNotCallInvalidate() - { - var font1 = new Font(SystemFonts.MessageBoxFont.FontFamily, 10); - var font2 = new Font(SystemFonts.MessageBoxFont.FontFamily, 11); - var dataGrid = new DataGrid - { - Font = SystemFonts.StatusFont - }; - int invalidatedCallCount = 0; - dataGrid.Invalidated += (sender, e) => invalidatedCallCount++; - var style = new DataGridTableStyle - { - DataGrid = dataGrid - }; - Assert.NotEqual(IntPtr.Zero, dataGrid.Handle); - - style.HeaderFont = font1; - Assert.Same(font1, style.HeaderFont); - Assert.Equal(0, invalidatedCallCount); - - // Set same. - style.HeaderFont = font1; - Assert.Same(font1, style.HeaderFont); - Assert.Equal(0, invalidatedCallCount); - - // Set null. - style.HeaderFont = null; - Assert.Same(dataGrid.Font, style.HeaderFont); - Assert.Equal(0, invalidatedCallCount); - - // Set null again. - style.HeaderFont = null; - Assert.Same(dataGrid.Font, style.HeaderFont); - Assert.Equal(0, invalidatedCallCount); - - // Set different. - style.HeaderFont = font1; - Assert.Same(font1, style.HeaderFont); - Assert.Equal(0, invalidatedCallCount); - - // Set different. - style.HeaderFont = font2; - Assert.Same(font2, style.HeaderFont); - Assert.Equal(0, invalidatedCallCount); - } - - [Fact] - public void DataGridTableStyle_HeaderFont_SetWithHandler_CallsHeaderFontChanged() - { - var font1 = new Font(SystemFonts.MessageBoxFont.FontFamily, 10); - var font2 = new Font(SystemFonts.MessageBoxFont.FontFamily, 11); - var style = new DataGridTableStyle(); - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(style, sender); - Assert.Same(EventArgs.Empty, e); - callCount++; - }; - style.HeaderFontChanged += handler; - - // Set different. - style.HeaderFont = font1; - Assert.Same(font1, style.HeaderFont); - Assert.Equal(1, callCount); - - // Set same. - style.HeaderFont = font1; - Assert.Same(font1, style.HeaderFont); - Assert.Equal(1, callCount); - - // Set null. - style.HeaderFont = null; - Assert.Same(Control.DefaultFont, style.HeaderFont); - Assert.Equal(2, callCount); - - // Set null again. - style.HeaderFont = null; - Assert.Same(Control.DefaultFont, style.HeaderFont); - Assert.Equal(2, callCount); - - // Set different. - style.HeaderFont = font1; - Assert.Same(font1, style.HeaderFont); - Assert.Equal(3, callCount); - - // Set different. - style.HeaderFont = font2; - Assert.Same(font2, style.HeaderFont); - Assert.Equal(4, callCount); - - // Remove handler. - style.HeaderFontChanged -= handler; - style.HeaderFont = font1; - Assert.Same(font1, style.HeaderFont); - Assert.Equal(4, callCount); - } - - public static IEnumerable HeaderForeColor_Set_TestData() - { - yield return new object[] { Color.FromArgb(254, 1, 2, 3) }; - yield return new object[] { Color.Red }; - } - - [Theory] - [MemberData(nameof(HeaderForeColor_Set_TestData))] - public void DataGridTableStyle_HeaderForeColor_Set_GetReturnsExpected(Color value) - { - var style = new DataGridTableStyle - { - HeaderForeColor = value - }; - Assert.Equal(value, style.HeaderForeColor); - - // Set same. - style.HeaderForeColor = value; - Assert.Equal(value, style.HeaderForeColor); - } - - [Theory] - [MemberData(nameof(HeaderForeColor_Set_TestData))] - public void DataGridTableStyle_HeaderForeColor_SetWithDataGrid_DoesNotCallInvalidate(Color value) - { - var dataGrid = new DataGrid(); - var style = new DataGridTableStyle - { - DataGrid = dataGrid - }; - int invalidatedCallCount = 0; - dataGrid.Invalidated += (sender, e) => invalidatedCallCount++; - Assert.NotEqual(IntPtr.Zero, dataGrid.Handle); - - style.HeaderForeColor = value; - Assert.Equal(value, style.HeaderForeColor); - Assert.Equal(0, invalidatedCallCount); - - // Set same. - style.HeaderForeColor = value; - Assert.Equal(value, style.HeaderForeColor); - Assert.Equal(0, invalidatedCallCount); - } - - [Fact] - public void DataGridTableStyle_HeaderForeColor_SetWithHandler_CallsHeaderForeColorChanged() - { - var style = new DataGridTableStyle(); - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(style, sender); - Assert.Same(EventArgs.Empty, e); - callCount++; - }; - style.HeaderForeColorChanged += handler; - - // Set different. - style.HeaderForeColor = Color.Red; - Assert.Equal(Color.Red, style.HeaderForeColor); - Assert.Equal(1, callCount); - - // Set same. - style.HeaderForeColor = Color.Red; - Assert.Equal(Color.Red, style.HeaderForeColor); - Assert.Equal(1, callCount); - - // Set different. - style.HeaderForeColor = Color.Blue; - Assert.Equal(Color.Blue, style.HeaderForeColor); - Assert.Equal(2, callCount); - - // Remove handler. - style.HeaderForeColorChanged -= handler; - style.HeaderForeColor = Color.Red; - Assert.Equal(Color.Red, style.HeaderForeColor); - Assert.Equal(2, callCount); - } - - [Fact] - public void DataGridTableStyle_HeaderForeColor_SetEmpty_ThrowsArgumentException() - { - var style = new DataGridTableStyle(); - Assert.Throws("value", () => style.HeaderForeColor = Color.Empty); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetColorWithEmptyTheoryData))] - public void DataGridTableStyle_HeaderForeColor_SetDefaultTableStyle_ThrowsArgumentException(Color value) - { - var style = new DataGridTableStyle(isDefaultTableStyle: true); - Assert.Throws(null, () => style.HeaderForeColor = value); - Assert.Equal(SystemColors.ControlText, style.HeaderForeColor); - } - - public static IEnumerable LinkColor_Set_TestData() - { - yield return new object[] { Color.FromArgb(254, 1, 2, 3) }; - yield return new object[] { Color.Red }; - } - - [Theory] - [MemberData(nameof(LinkColor_Set_TestData))] - public void DataGridTableStyle_LinkColor_Set_GetReturnsExpected(Color value) - { - var style = new DataGridTableStyle - { - LinkColor = value - }; - Assert.Equal(value, style.LinkColor); - Assert.Equal(value, style.LinkHoverColor); - - // Set same. - style.LinkColor = value; - Assert.Equal(value, style.LinkColor); - Assert.Equal(value, style.LinkHoverColor); - } - - [Theory] - [MemberData(nameof(LinkColor_Set_TestData))] - public void DataGridTableStyle_LinkColor_SetWithDataGrid_DoesNotCallInvalidate(Color value) - { - var dataGrid = new DataGrid(); - var style = new DataGridTableStyle - { - DataGrid = dataGrid - }; - int invalidatedCallCount = 0; - dataGrid.Invalidated += (sender, e) => invalidatedCallCount++; - Assert.NotEqual(IntPtr.Zero, dataGrid.Handle); - - style.LinkColor = value; - Assert.Equal(value, style.LinkColor); - Assert.Equal(value, style.LinkHoverColor); - Assert.Equal(0, invalidatedCallCount); - - // Set same. - style.LinkColor = value; - Assert.Equal(value, style.LinkColor); - Assert.Equal(value, style.LinkHoverColor); - Assert.Equal(0, invalidatedCallCount); - } - - [Fact] - public void DataGridTableStyle_LinkColor_SetWithHandler_CallsLinkColorChanged() - { - var style = new DataGridTableStyle(); - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(style, sender); - Assert.Same(EventArgs.Empty, e); - callCount++; - }; - style.LinkColorChanged += handler; - - // Set different. - style.LinkColor = Color.Red; - Assert.Equal(Color.Red, style.LinkColor); - Assert.Equal(Color.Red, style.LinkHoverColor); - Assert.Equal(1, callCount); - - // Set same. - style.LinkColor = Color.Red; - Assert.Equal(Color.Red, style.LinkColor); - Assert.Equal(Color.Red, style.LinkHoverColor); - Assert.Equal(1, callCount); - - // Set different. - style.LinkColor = Color.Blue; - Assert.Equal(Color.Blue, style.LinkColor); - Assert.Equal(Color.Blue, style.LinkHoverColor); - Assert.Equal(2, callCount); - - // Remove handler. - style.LinkColorChanged -= handler; - style.LinkColor = Color.Red; - Assert.Equal(Color.Red, style.LinkColor); - Assert.Equal(Color.Red, style.LinkHoverColor); - Assert.Equal(2, callCount); - } - - [Fact] - public void DataGridTableStyle_LinkColor_SetEmpty_ThrowsArgumentException() - { - var style = new DataGridTableStyle(); - Assert.Throws("value", () => style.LinkColor = Color.Empty); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetColorWithEmptyTheoryData))] - public void DataGridTableStyle_LinkColor_SetDefaultTableStyle_ThrowsArgumentException(Color value) - { - var style = new DataGridTableStyle(isDefaultTableStyle: true); - Assert.Throws(null, () => style.LinkColor = value); - Assert.Equal(SystemColors.HotTrack, style.LinkColor); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetColorWithEmptyTheoryData))] - public void DataGridTableStyle_LinkHoverColor_Set_Nop(Color value) - { - var style = new DataGridTableStyle(); - style.LinkHoverColor = value; - Assert.Equal(SystemColors.HotTrack, style.LinkColor); - Assert.Equal(SystemColors.HotTrack, style.LinkHoverColor); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetStringNormalizedTheoryData))] - public void DataGridTableStyle_MappingName_Set_GetReturnsExpected(string value, string expected) - { - var style = new DataGridTableStyle - { - MappingName = value - }; - Assert.Equal(expected, style.MappingName); - - // Set same. - style.MappingName = value; - Assert.Equal(expected, style.MappingName); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetStringNormalizedTheoryData))] - public void DataGridTableStyle_MappingName_SetWithDataGridView_GetReturnsExpected(string value, string expected) - { - var dataGrid = new DataGrid(); - var style = new DataGridTableStyle - { - DataGrid = dataGrid - }; - int invalidatedCallCount = 0; - dataGrid.Invalidated += (sender, e) => invalidatedCallCount++; - Assert.NotEqual(IntPtr.Zero, dataGrid.Handle); - - style.MappingName = value; - Assert.Equal(expected, style.MappingName); - Assert.Equal(0, invalidatedCallCount); - - style.MappingName = value; - Assert.Equal(expected, style.MappingName); - Assert.Equal(0, invalidatedCallCount); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetStringNormalizedTheoryData))] - public void DataGridTableStyle_MappingName_SetDefaultTableStyle_GetReturnsExpected(string value, string expected) - { - var style = new DataGridTableStyle(isDefaultTableStyle: true) - { - MappingName = value - }; - Assert.Equal(expected, style.MappingName); - - style.MappingName = value; - Assert.Equal(expected, style.MappingName); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetStringNormalizedTheoryData))] - [InlineData("mappingname2", "mappingname2")] - public void DataGridTableStyle_MappingName_SetNonDuplicate_GetReturnsExpected(string value, string expected) - { - var dataGrid = new DataGrid(); - var style1 = new DataGridTableStyle - { - MappingName = "MappingName1" - }; - var style2 = new DataGridTableStyle - { - MappingName = "MappingName2" - }; - dataGrid.TableStyles.Add(style1); - dataGrid.TableStyles.Add(style2); - - style1.MappingName = value; - Assert.Equal(expected, style1.MappingName); - - // Set same. - style1.MappingName = value; - Assert.Equal(expected, style1.MappingName); - } - - [Fact] - public void DataGridTableStyle_MappingName_SetDuplicate_Throws() - { - var dataGrid = new DataGrid(); - var style1 = new DataGridTableStyle - { - MappingName = "MappingName1" - }; - var style2 = new DataGridTableStyle - { - MappingName = "MappingName2" - }; - dataGrid.TableStyles.Add(style1); - dataGrid.TableStyles.Add(style2); - - Assert.Throws("table", () => style1.MappingName = "MappingName2"); - Assert.Equal("MappingName1", style1.MappingName); - } - - [Fact] - public void DataGridTableStyle_MappingName_SetWithHandler_CallsMappingNameChanged() - { - var control = new SubDataGridTableStyle(); - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(control, sender); - Assert.Same(EventArgs.Empty, e); - callCount++; - }; - control.MappingNameChanged += handler; - - // Set different. - control.MappingName = "mappingName"; - Assert.Same("mappingName", control.MappingName); - Assert.Equal(1, callCount); - - // Set same. - control.MappingName = "mappingName"; - Assert.Same("mappingName", control.MappingName); - Assert.Equal(1, callCount); - - // Set empty. - control.MappingName = string.Empty; - Assert.Empty(control.MappingName); - Assert.Equal(2, callCount); - - // Set null. - control.MappingName = null; - Assert.Empty(control.MappingName); - Assert.Equal(2, callCount); - - // Remove handler. - control.MappingNameChanged -= handler; - control.MappingName = "mappingName"; - Assert.Same("mappingName", control.MappingName); - Assert.Equal(2, callCount); - } - - [Theory] - [InlineData(0)] - [InlineData(1)] - [InlineData(75)] - [InlineData(76)] - public void DataGridTableStyle_PreferredColumnWidth_Set_GetReturnsExpected(int value) - { - var style = new DataGridTableStyle - { - PreferredColumnWidth = value - }; - Assert.Equal(value, style.PreferredColumnWidth); - - // Set same. - style.PreferredColumnWidth = value; - Assert.Equal(value, style.PreferredColumnWidth); - } - - [Theory] - [InlineData(0)] - [InlineData(1)] - [InlineData(75)] - [InlineData(76)] - public void DataGridTableStyle_PreferredColumnWidth_SetWithDataGrid_DoesNotCallInvalidate(int value) - { - var dataGrid = new DataGrid(); - var style = new DataGridTableStyle - { - DataGrid = dataGrid - }; - int invalidatedCallCount = 0; - dataGrid.Invalidated += (sender, e) => invalidatedCallCount++; - Assert.NotEqual(IntPtr.Zero, dataGrid.Handle); - - style.PreferredColumnWidth = value; - Assert.Equal(value, style.PreferredColumnWidth); - Assert.Equal(0, invalidatedCallCount); - - // Set same. - style.PreferredColumnWidth = value; - Assert.Equal(value, style.PreferredColumnWidth); - Assert.Equal(0, invalidatedCallCount); - } - - [Fact] - public void DataGridTableStyle_PreferredColumnWidth_SetWithHandler_CallsPreferredColumnWidthChanged() - { - var style = new DataGridTableStyle(); - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(style, sender); - Assert.Same(EventArgs.Empty, e); - callCount++; - }; - style.PreferredColumnWidthChanged += handler; - - // Set different. - style.PreferredColumnWidth = 1; - Assert.Equal(1, style.PreferredColumnWidth); - Assert.Equal(1, callCount); - - // Set same. - style.PreferredColumnWidth = 1; - Assert.Equal(1, style.PreferredColumnWidth); - Assert.Equal(1, callCount); - - // Set different. - style.PreferredColumnWidth = 2; - Assert.Equal(2, style.PreferredColumnWidth); - Assert.Equal(2, callCount); - - // Remove handler. - style.PreferredColumnWidthChanged -= handler; - style.PreferredColumnWidth = 1; - Assert.Equal(1, style.PreferredColumnWidth); - Assert.Equal(2, callCount); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetIntTheoryData))] - public void DataGridTableStyle_PreferredColumnWidth_SetDefaultTableStyle_ThrowsArgumentException(int value) - { - var style = new DataGridTableStyle(isDefaultTableStyle: true); - Assert.Throws(null, () => style.PreferredColumnWidth = value); - Assert.Equal(75, style.PreferredColumnWidth); - } - - [Fact] - public void DataGridTableStyle_PreferredColumnWidth_SetNegative_ThrowsArgumentOutOfRangeException() - { - var style = new DataGridTableStyle(); - Assert.Throws("value", () => style.PreferredColumnWidth = -1); - } - - [Theory] - [InlineData(0)] - [InlineData(1)] - [InlineData(75)] - [InlineData(76)] - public void DataGridTableStyle_PreferredRowHeight_Set_GetReturnsExpected(int value) - { - var style = new DataGridTableStyle - { - PreferredRowHeight = value - }; - Assert.Equal(value, style.PreferredRowHeight); - - // Set same. - style.PreferredRowHeight = value; - Assert.Equal(value, style.PreferredRowHeight); - } - - [Theory] - [InlineData(0)] - [InlineData(1)] - [InlineData(75)] - [InlineData(76)] - public void DataGridTableStyle_PreferredRowHeight_SetWithDataGrid_DoesNotCallInvalidate(int value) - { - var dataGrid = new DataGrid(); - var style = new DataGridTableStyle - { - DataGrid = dataGrid - }; - int invalidatedCallCount = 0; - dataGrid.Invalidated += (sender, e) => invalidatedCallCount++; - Assert.NotEqual(IntPtr.Zero, dataGrid.Handle); - - style.PreferredRowHeight = value; - Assert.Equal(value, style.PreferredRowHeight); - Assert.Equal(0, invalidatedCallCount); - - // Set same. - style.PreferredRowHeight = value; - Assert.Equal(value, style.PreferredRowHeight); - Assert.Equal(0, invalidatedCallCount); - } - - [Fact] - public void DataGridTableStyle_PreferredRowHeight_SetWithHandler_CallsPreferredRowHeightChanged() - { - var style = new DataGridTableStyle(); - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(style, sender); - Assert.Same(EventArgs.Empty, e); - callCount++; - }; - style.PreferredRowHeightChanged += handler; - - // Set different. - style.PreferredRowHeight = 1; - Assert.Equal(1, style.PreferredRowHeight); - Assert.Equal(1, callCount); - - // Set same. - style.PreferredRowHeight = 1; - Assert.Equal(1, style.PreferredRowHeight); - Assert.Equal(1, callCount); - - // Set different. - style.PreferredRowHeight = 2; - Assert.Equal(2, style.PreferredRowHeight); - Assert.Equal(2, callCount); - - // Remove handler. - style.PreferredRowHeightChanged -= handler; - style.PreferredRowHeight = 1; - Assert.Equal(1, style.PreferredRowHeight); - Assert.Equal(2, callCount); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetIntTheoryData))] - public void DataGridTableStyle_PreferredRowHeight_SetDefaultTableStyle_ThrowsArgumentException(int value) - { - var style = new DataGridTableStyle(isDefaultTableStyle: true); - Assert.Throws(null, () => style.PreferredRowHeight = value); - Assert.Equal(Control.DefaultFont.Height + 3, style.PreferredRowHeight); - } - - [Fact] - public void DataGridTableStyle_PreferredRowHeight_SetNegative_ThrowsArgumentOutOfRangeException() - { - var style = new DataGridTableStyle(); - Assert.Throws("value", () => style.PreferredRowHeight = -1); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetBoolTheoryData))] - public void DataGridTableStyle_ReadOnly_Set_GetReturnsExpected(bool value) - { - var style = new DataGridTableStyle - { - ReadOnly = value - }; - Assert.Equal(value, style.ReadOnly); - - // Set same. - style.ReadOnly = value; - Assert.Equal(value, style.ReadOnly); - - // Set different - style.ReadOnly = !value; - Assert.Equal(!value, style.ReadOnly); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetBoolTheoryData))] - public void DataGridTableStyle_ReadOnly_SetWithDataGrid_DoesNotCallInvalidate(bool value) - { - var dataGrid = new DataGrid(); - var style = new DataGridTableStyle - { - DataGrid = dataGrid - }; - int invalidatedCallCount = 0; - dataGrid.Invalidated += (sender, e) => invalidatedCallCount++; - Assert.NotEqual(IntPtr.Zero, dataGrid.Handle); - - style.ReadOnly = value; - Assert.Equal(value, style.ReadOnly); - Assert.Equal(0, invalidatedCallCount); - - // Set same. - style.ReadOnly = value; - Assert.Equal(value, style.ReadOnly); - Assert.Equal(0, invalidatedCallCount); - - // Set different - style.ReadOnly = !value; - Assert.Equal(!value, style.ReadOnly); - Assert.Equal(0, invalidatedCallCount); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetBoolTheoryData))] - public void DataGridTableStyle_ReadOnly_SetDefaultTableStyle_GetReturnsExpected(bool value) - { - var style = new DataGridTableStyle(isDefaultTableStyle: true) - { - ReadOnly = value - }; - Assert.Equal(value, style.ReadOnly); - - // Set same. - style.ReadOnly = value; - Assert.Equal(value, style.ReadOnly); - - // Set different - style.ReadOnly = !value; - Assert.Equal(!value, style.ReadOnly); - } - - [Fact] - public void DataGridTableStyle_ReadOnly_SetWithHandler_CallsReadOnlyChanged() - { - var style = new DataGridTableStyle - { - ReadOnly = true - }; - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(style, sender); - Assert.Same(EventArgs.Empty, e); - callCount++; - }; - style.ReadOnlyChanged += handler; - - // Set different. - style.ReadOnly = false; - Assert.False(style.ReadOnly); - Assert.Equal(1, callCount); - - // Set same. - style.ReadOnly = false; - Assert.False(style.ReadOnly); - Assert.Equal(1, callCount); - - // Set different. - style.ReadOnly = true; - Assert.True(style.ReadOnly); - Assert.Equal(2, callCount); - - // Remove handler. - style.ReadOnlyChanged -= handler; - style.ReadOnly = false; - Assert.False(style.ReadOnly); - Assert.Equal(2, callCount); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetBoolTheoryData))] - public void DataGridTableStyle_RowHeadersVisible_Set_GetReturnsExpected(bool value) - { - var style = new DataGridTableStyle - { - RowHeadersVisible = value - }; - Assert.Equal(value, style.RowHeadersVisible); - - // Set same. - style.RowHeadersVisible = value; - Assert.Equal(value, style.RowHeadersVisible); - - // Set different - style.RowHeadersVisible = !value; - Assert.Equal(!value, style.RowHeadersVisible); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetBoolTheoryData))] - public void DataGridTableStyle_RowHeadersVisible_SetWithDataGrid_DoesNotCallInvalidate(bool value) - { - var dataGrid = new DataGrid(); - var style = new DataGridTableStyle - { - DataGrid = dataGrid - }; - int invalidatedCallCount = 0; - dataGrid.Invalidated += (sender, e) => invalidatedCallCount++; - Assert.NotEqual(IntPtr.Zero, dataGrid.Handle); - - style.RowHeadersVisible = value; - Assert.Equal(value, style.RowHeadersVisible); - Assert.Equal(0, invalidatedCallCount); - - // Set same. - style.RowHeadersVisible = value; - Assert.Equal(value, style.RowHeadersVisible); - Assert.Equal(0, invalidatedCallCount); - - // Set different - style.RowHeadersVisible = !value; - Assert.Equal(!value, style.RowHeadersVisible); - Assert.Equal(0, invalidatedCallCount); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetBoolTheoryData))] - public void DataGridTableStyle_RowHeadersVisible_SetDefaultTableStyle_GetReturnsExpected(bool value) - { - var style = new DataGridTableStyle(isDefaultTableStyle: true) - { - RowHeadersVisible = value - }; - Assert.Equal(value, style.RowHeadersVisible); - - // Set same. - style.RowHeadersVisible = value; - Assert.Equal(value, style.RowHeadersVisible); - - // Set different - style.RowHeadersVisible = !value; - Assert.Equal(!value, style.RowHeadersVisible); - } - - [Fact] - public void DataGridTableStyle_RowHeadersVisible_SetWithHandler_CallsRowHeadersVisibleChanged() - { - var style = new DataGridTableStyle - { - RowHeadersVisible = true - }; - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(style, sender); - Assert.Same(EventArgs.Empty, e); - callCount++; - }; - style.RowHeadersVisibleChanged += handler; - - // Set different. - style.RowHeadersVisible = false; - Assert.False(style.RowHeadersVisible); - Assert.Equal(1, callCount); - - // Set same. - style.RowHeadersVisible = false; - Assert.False(style.RowHeadersVisible); - Assert.Equal(1, callCount); - - // Set different. - style.RowHeadersVisible = true; - Assert.True(style.RowHeadersVisible); - Assert.Equal(2, callCount); - - // Remove handler. - style.RowHeadersVisibleChanged -= handler; - style.RowHeadersVisible = false; - Assert.False(style.RowHeadersVisible); - Assert.Equal(2, callCount); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetIntTheoryData))] - public void DataGridTableStyle_RowHeaderWidth_Set_GetReturnsExpected(int value) - { - var style = new DataGridTableStyle - { - RowHeaderWidth = value - }; - Assert.Equal(value, style.RowHeaderWidth); - - // Set same. - style.RowHeaderWidth = value; - Assert.Equal(value, style.RowHeaderWidth); - } - - [Theory] - [InlineData(-1, 0)] - [InlineData(0, 0)] - [InlineData(1, 1)] - [InlineData(35, 35)] - [InlineData(36, 36)] - public void DataGridTableStyle_RowHeaderWidth_SetWithDataGrid_DoesNotCallInvalidate(int value, int expected) - { - var dataGrid = new DataGrid(); - var style = new DataGridTableStyle - { - DataGrid = dataGrid - }; - int invalidatedCallCount = 0; - dataGrid.Invalidated += (sender, e) => invalidatedCallCount++; - Assert.NotEqual(IntPtr.Zero, dataGrid.Handle); - - style.RowHeaderWidth = value; - Assert.Equal(expected, style.RowHeaderWidth); - Assert.Equal(0, invalidatedCallCount); - - // Set same. - style.RowHeaderWidth = value; - Assert.Equal(expected, style.RowHeaderWidth); - Assert.Equal(0, invalidatedCallCount); - } - - [Fact] - public void DataGridTableStyle_RowHeaderWidth_SetWithHandler_CallsRowHeaderWidthChanged() - { - var style = new DataGridTableStyle(); - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(style, sender); - Assert.Same(EventArgs.Empty, e); - callCount++; - }; - style.RowHeaderWidthChanged += handler; - - // Set different. - style.RowHeaderWidth = 1; - Assert.Equal(1, style.RowHeaderWidth); - Assert.Equal(1, callCount); - - // Set same. - style.RowHeaderWidth = 1; - Assert.Equal(1, style.RowHeaderWidth); - Assert.Equal(1, callCount); - - // Set different. - style.RowHeaderWidth = 2; - Assert.Equal(2, style.RowHeaderWidth); - Assert.Equal(2, callCount); - - // Remove handler. - style.RowHeaderWidthChanged -= handler; - style.RowHeaderWidth = 1; - Assert.Equal(1, style.RowHeaderWidth); - Assert.Equal(2, callCount); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetColorTheoryData))] - public void DataGridTableStyle_SelectionBackColor_Set_GetReturnsExpected(Color value) - { - var style = new DataGridTableStyle - { - SelectionBackColor = value - }; - Assert.Equal(value, style.SelectionBackColor); - - // Set same. - style.SelectionBackColor = value; - Assert.Equal(value, style.SelectionBackColor); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetColorTheoryData))] - public void DataGridTableStyle_SelectionBackColor_SetWithDataGrid_CallsInvalidate(Color value) - { - var dataGrid = new DataGrid(); - var style = new DataGridTableStyle - { - DataGrid = dataGrid - }; - int invalidatedCallCount = 0; - dataGrid.Invalidated += (sender, e) => invalidatedCallCount++; - Assert.NotEqual(IntPtr.Zero, dataGrid.Handle); - - style.SelectionBackColor = value; - Assert.Equal(value, style.SelectionBackColor); - Assert.Equal(1, invalidatedCallCount); - - // Set same. - style.SelectionBackColor = value; - Assert.Equal(value, style.SelectionBackColor); - Assert.Equal(1, invalidatedCallCount); - } - - [Fact] - public void DataGridTableStyle_SelectionBackColor_SetWithHandler_CallsSelectionBackColorChanged() - { - var style = new DataGridTableStyle(); - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(style, sender); - Assert.Same(EventArgs.Empty, e); - callCount++; - }; - style.SelectionBackColorChanged += handler; - - // Set different. - style.SelectionBackColor = Color.Red; - Assert.Equal(Color.Red, style.SelectionBackColor); - Assert.Equal(1, callCount); - - // Set same. - style.SelectionBackColor = Color.Red; - Assert.Equal(Color.Red, style.SelectionBackColor); - Assert.Equal(1, callCount); - - // Set different. - style.SelectionBackColor = Color.Blue; - Assert.Equal(Color.Blue, style.SelectionBackColor); - Assert.Equal(2, callCount); - - // Remove handler. - style.SelectionBackColorChanged -= handler; - style.SelectionBackColor = Color.Red; - Assert.Equal(Color.Red, style.SelectionBackColor); - Assert.Equal(2, callCount); - } - - [Theory] - [MemberData(nameof(InvalidColor_TestData))] - public void DataGridTableStyle_SelectionBackColor_SetInvalid_ThrowsArgumentException(Color value) - { - var style = new DataGridTableStyle(); - Assert.Throws("value", () => style.SelectionBackColor = value); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetColorWithEmptyTheoryData))] - public void DataGridTableStyle_SelectionBackColor_SetDefaultTableStyle_ThrowsArgumentException(Color value) - { - var style = new DataGridTableStyle(isDefaultTableStyle: true); - Assert.Throws(null, () => style.SelectionBackColor = value); - Assert.Equal(SystemColors.ActiveCaption, style.SelectionBackColor); - } - - public static IEnumerable SelectionForeColor_Set_TestData() - { - yield return new object[] { Color.FromArgb(254, 1, 2, 3) }; - yield return new object[] { Color.Red }; - } - - [Theory] - [MemberData(nameof(SelectionForeColor_Set_TestData))] - public void DataGridTableStyle_SelectionForeColor_Set_GetReturnsExpected(Color value) - { - var style = new DataGridTableStyle - { - SelectionForeColor = value - }; - Assert.Equal(value, style.SelectionForeColor); - - // Set same. - style.SelectionForeColor = value; - Assert.Equal(value, style.SelectionForeColor); - } - - [Theory] - [MemberData(nameof(SelectionForeColor_Set_TestData))] - public void DataGridTableStyle_SelectionForeColor_SetWithDataGrid_CallsInvalidate(Color value) - { - var dataGrid = new DataGrid(); - var style = new DataGridTableStyle - { - DataGrid = dataGrid - }; - int invalidatedCallCount = 0; - dataGrid.Invalidated += (sender, e) => invalidatedCallCount++; - Assert.NotEqual(IntPtr.Zero, dataGrid.Handle); - - style.SelectionForeColor = value; - Assert.Equal(value, style.SelectionForeColor); - Assert.Equal(1, invalidatedCallCount); - - // Set same. - style.SelectionForeColor = value; - Assert.Equal(value, style.SelectionForeColor); - Assert.Equal(1, invalidatedCallCount); - } - - [Fact] - public void DataGridTableStyle_SelectionForeColor_SetWithHandler_CallsSelectionForeColorChanged() - { - var style = new DataGridTableStyle(); - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(style, sender); - Assert.Same(EventArgs.Empty, e); - callCount++; - }; - style.SelectionForeColorChanged += handler; - - // Set different. - style.SelectionForeColor = Color.Red; - Assert.Equal(Color.Red, style.SelectionForeColor); - Assert.Equal(1, callCount); - - // Set same. - style.SelectionForeColor = Color.Red; - Assert.Equal(Color.Red, style.SelectionForeColor); - Assert.Equal(1, callCount); - - // Set different. - style.SelectionForeColor = Color.Blue; - Assert.Equal(Color.Blue, style.SelectionForeColor); - Assert.Equal(2, callCount); - - // Remove handler. - style.SelectionForeColorChanged -= handler; - style.SelectionForeColor = Color.Red; - Assert.Equal(Color.Red, style.SelectionForeColor); - Assert.Equal(2, callCount); - } - - [Fact] - public void DataGridTableStyle_SelectionForeColor_SetEmpty_ThrowsArgumentException() - { - var style = new DataGridTableStyle(); - Assert.Throws("value", () => style.SelectionForeColor = Color.Empty); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetColorWithEmptyTheoryData))] - public void DataGridTableStyle_SelectionForeColor_SetDefaultTableStyle_ThrowsArgumentException(Color value) - { - var style = new DataGridTableStyle(isDefaultTableStyle: true); - Assert.Throws(null, () => style.SelectionForeColor = value); - Assert.Equal(SystemColors.ActiveCaptionText, style.SelectionForeColor); - } - - public static IEnumerable BeginEdit_WithDataSource_TestData() - { - yield return new object[] { 0, true, true, 0, 1, 0, 0, 5 }; - yield return new object[] { 1, true, true, 1, 2, 1, 0, 5 }; - yield return new object[] { -1, true, true, 0, 1, 0, 0, 5 }; - yield return new object[] { 2, true, true, 1, 2, 1, 0, 5 }; - - yield return new object[] { 0, false, true, 0, 1, 0, 0, 2 }; - yield return new object[] { 1, false, true, 1, 2, 1, 1, 3 }; - yield return new object[] { -1, false, true, 0, 1, 0, 0, 2 }; - yield return new object[] { 2, false, true, 1, 2, 1, 1, 3 }; - } - - [Theory] - [MemberData(nameof(BeginEdit_WithDataSource_TestData))] - public void DataGridTableStyle_BeginEdit_InvokeWithDataSource_ReturnsExpected(int rowNumber, bool commitResult1, bool commitResult2, int expectedRowNumber, int expectedEditCallCount, int expectedCommitCallCount, int expectedAbortCallCount, int expectedCommitCallCount2) - { - var dataSource = new DataClass[] - { - new DataClass { Value1 = "Value1_1", Value2 = "Value2_1" }, - new DataClass { Value1 = "Value1_2", Value2 = "Value2_2" } - }; - var bindingContext = new BindingContext(); - CurrencyManager currencyManager = (CurrencyManager)bindingContext[dataSource, null]; - - var style = new DataGridTableStyle - { - MappingName = "DataClass[]" - }; - - var gridColumn1 = new SubDataGridColumnStyle - { - MappingName = "Value1" - }; - int editCallCount1 = 0; - gridColumn1.EditAction = (source, rowNum, bounds, readOnly, displayText, cellIsVisible) => - { - Assert.Same(currencyManager, source); - Assert.Equal(expectedRowNumber, rowNum); - Assert.NotEqual(Rectangle.Empty, bounds); - Assert.False(readOnly); - Assert.Null(displayText); - Assert.True(cellIsVisible); - editCallCount1++; - }; - int commitCallCount1 = 0; - gridColumn1.CommitAction = (dataSource, rowNum) => - { - Assert.Same(currencyManager, dataSource); - Assert.Equal(expectedRowNumber, rowNum); - commitCallCount1++; - return commitResult1; - }; - int abortCallCount1 = 0; - gridColumn1.AbortAction = (rowNum) => - { - Assert.Equal(expectedRowNumber, rowNum); - abortCallCount1++; - }; - style.GridColumnStyles.Add(gridColumn1); - - var gridColumn2 = new SubDataGridColumnStyle - { - MappingName = "Value2" - }; - int editCallCount2 = 0; - gridColumn2.EditAction = (source, rowNum, bounds, readOnly, displayText, cellIsVisible) => - { - Assert.Same(currencyManager, source); - Assert.Equal(expectedRowNumber, rowNum); - Assert.NotEqual(Rectangle.Empty, bounds); - Assert.False(readOnly); - Assert.Null(displayText); - Assert.True(cellIsVisible); - editCallCount2++; - }; - int commitCallCount2 = 0; - gridColumn2.CommitAction = (dataSource, rowNum) => - { - Assert.Same(currencyManager, dataSource); - Assert.Equal(expectedRowNumber, rowNum); - commitCallCount2++; - return commitResult2; - }; - int abortCallCount2 = 0; - gridColumn2.AbortAction = (rowNum) => - { - Assert.Equal(expectedRowNumber, rowNum); - abortCallCount2++; - }; - style.GridColumnStyles.Add(gridColumn2); - - var dataGrid = new SubDataGrid - { - BindingContext = bindingContext - }; - dataGrid.TableStyles.Add(style); - dataGrid.SetDataBinding(dataSource, null); - - // Simulate layout on the DataGrid. - using (var image = new Bitmap(10, 10)) - using (Graphics graphics = Graphics.FromImage(image)) - { - dataGrid.OnPaint(new PaintEventArgs(graphics, new Rectangle(0, 0, 1, 2))); - } - - // Edit cell. - Assert.True(style.BeginEdit(gridColumn1, rowNumber)); - Assert.Equal(new DataGridCell(expectedRowNumber, 0), dataGrid.CurrentCell); - Assert.Equal(expectedEditCallCount, editCallCount1); - Assert.Equal(0, editCallCount2); - Assert.Equal(expectedCommitCallCount, commitCallCount1); - Assert.Equal(0, commitCallCount2); - Assert.Equal(expectedAbortCallCount, abortCallCount1); - Assert.Equal(0, abortCallCount2); - Assert.False(dataGrid.IsSelected(0)); - Assert.False(dataGrid.IsSelected(1)); - - // Edit same. - Assert.True(style.BeginEdit(gridColumn1, rowNumber)); - Assert.Equal(new DataGridCell(expectedRowNumber, 0), dataGrid.CurrentCell); - Assert.Equal(expectedEditCallCount + 1, editCallCount1); - Assert.Equal(0, editCallCount2); - Assert.Equal(expectedCommitCallCount + 1, commitCallCount1); - Assert.Equal(0, commitCallCount2); - Assert.False(dataGrid.IsSelected(0)); - Assert.False(dataGrid.IsSelected(1)); - - // Edit another. - Assert.True(style.BeginEdit(gridColumn2, rowNumber)); - Assert.Equal(new DataGridCell(expectedRowNumber, 1), dataGrid.CurrentCell); - Assert.Equal(expectedEditCallCount + 1, editCallCount1); - Assert.Equal(2, editCallCount2); - Assert.Equal(expectedCommitCallCount2, commitCallCount1); - Assert.Equal(1, commitCallCount2); - Assert.False(dataGrid.IsSelected(0)); - Assert.False(dataGrid.IsSelected(1)); - - // Edit invalid. - Assert.False(style.BeginEdit(new SubDataGridColumnStyle(), rowNumber)); - Assert.Equal(new DataGridCell(expectedRowNumber, 1), dataGrid.CurrentCell); - Assert.Equal(expectedEditCallCount + 1, editCallCount1); - Assert.Equal(2, editCallCount2); - Assert.Equal(expectedCommitCallCount2, commitCallCount1); - Assert.Equal(1, commitCallCount2); - Assert.False(dataGrid.IsSelected(0)); - Assert.False(dataGrid.IsSelected(1)); - - // Edit null. - Assert.False(style.BeginEdit(null, rowNumber)); - Assert.Equal(new DataGridCell(expectedRowNumber, 1), dataGrid.CurrentCell); - Assert.Equal(expectedEditCallCount + 1, editCallCount1); - Assert.Equal(2, editCallCount2); - Assert.Equal(expectedCommitCallCount2, commitCallCount1); - Assert.Equal(1, commitCallCount2); - Assert.False(dataGrid.IsSelected(0)); - Assert.False(dataGrid.IsSelected(1)); - } - - [Theory] - [InlineData(0)] - [InlineData(1)] - [InlineData(-1)] - [InlineData(2)] - public void DataGridTableStyle_BeginEdit_InvokeWithEmptyDataSource_ReturnsExpected(int rowNumber) - { - var dataSource = new DataClass[0]; - var bindingContext = new BindingContext(); - CurrencyManager currencyManager = (CurrencyManager)bindingContext[dataSource, null]; - - var style = new DataGridTableStyle - { - MappingName = "DataClass[]" - }; - - var gridColumn1 = new SubDataGridColumnStyle - { - MappingName = "Value1" - }; - int editCallCount1 = 0; - gridColumn1.EditAction = (source, rowNum, bounds, readOnly, displayText, cellIsVisible) => - { - editCallCount1++; - }; - int commitCallCount1 = 0; - gridColumn1.CommitAction = (dataSource, rowNum) => - { - commitCallCount1++; - return true; - }; - style.GridColumnStyles.Add(gridColumn1); - - var gridColumn2 = new SubDataGridColumnStyle - { - MappingName = "Value2" - }; - int editCallCount2 = 0; - gridColumn2.EditAction = (source, rowNum, bounds, readOnly, displayText, cellIsVisible) => - { - editCallCount2++; - }; - int commitCallCount2 = 0; - gridColumn2.CommitAction = (dataSource, rowNum) => - { - commitCallCount2++; - return true; - }; - style.GridColumnStyles.Add(gridColumn2); - - var dataGrid = new SubDataGrid - { - BindingContext = bindingContext - }; - dataGrid.TableStyles.Add(style); - dataGrid.SetDataBinding(dataSource, null); - - // Simulate layout on the DataGrid. - using (var image = new Bitmap(10, 10)) - using (Graphics graphics = Graphics.FromImage(image)) - { - dataGrid.OnPaint(new PaintEventArgs(graphics, new Rectangle(0, 0, 1, 2))); - } - - // Edit cell. - Assert.True(style.BeginEdit(gridColumn1, rowNumber)); - Assert.Equal(new DataGridCell(0, 0), dataGrid.CurrentCell); - Assert.Equal(0, editCallCount1); - Assert.Equal(0, editCallCount2); - Assert.Equal(0, commitCallCount1); - Assert.Equal(0, commitCallCount2); - - // Edit same. - Assert.True(style.BeginEdit(gridColumn1, rowNumber)); - Assert.Equal(new DataGridCell(0, 0), dataGrid.CurrentCell); - Assert.Equal(0, editCallCount1); - Assert.Equal(0, editCallCount2); - Assert.Equal(0, commitCallCount1); - Assert.Equal(0, commitCallCount2); - - // Edit another. - Assert.True(style.BeginEdit(gridColumn2, rowNumber)); - Assert.Equal(new DataGridCell(0, 0), dataGrid.CurrentCell); - Assert.Equal(0, editCallCount1); - Assert.Equal(0, editCallCount2); - Assert.Equal(0, commitCallCount1); - Assert.Equal(0, commitCallCount2); - - // Edit invalid. - Assert.False(style.BeginEdit(new SubDataGridColumnStyle(), rowNumber)); - Assert.Equal(new DataGridCell(0, 0), dataGrid.CurrentCell); - Assert.Equal(0, editCallCount1); - Assert.Equal(0, editCallCount2); - Assert.Equal(0, commitCallCount1); - Assert.Equal(0, commitCallCount2); - - // Edit null. - Assert.False(style.BeginEdit(null, rowNumber)); - Assert.Equal(new DataGridCell(0, 0), dataGrid.CurrentCell); - Assert.Equal(0, editCallCount1); - Assert.Equal(0, editCallCount2); - Assert.Equal(0, commitCallCount1); - Assert.Equal(0, commitCallCount2); - } - - [Theory] - [InlineData(0, 0, 1, 0)] - [InlineData(1, 1, 2, 1)] - [InlineData(-1, 0, 1, 0)] - [InlineData(2, 1, 2, 1)] - public void DataGridTableStyle_BeginEdit_InvokeWithDataSource_ResetsSelection(int rowNumber, int expectedRowNumber, int expectedEditCallCount, int expectedCommitCallCount) - { - var dataSource = new DataClass[] - { - new DataClass { Value1 = "Value1_1", Value2 = "Value2_1" }, - new DataClass { Value1 = "Value1_2", Value2 = "Value2_2" } - }; - var bindingContext = new BindingContext(); - CurrencyManager currencyManager = (CurrencyManager)bindingContext[dataSource, null]; - - var style = new DataGridTableStyle - { - MappingName = "DataClass[]" - }; - - var gridColumn1 = new SubDataGridColumnStyle - { - MappingName = "Value1" - }; - int editCallCount1 = 0; - gridColumn1.EditAction = (source, rowNum, bounds, readOnly, displayText, cellIsVisible) => - { - Assert.Same(currencyManager, source); - Assert.Equal(expectedRowNumber, rowNum); - Assert.NotEqual(Rectangle.Empty, bounds); - Assert.False(readOnly); - Assert.Null(displayText); - Assert.True(cellIsVisible); - editCallCount1++; - }; - int commitCallCount1 = 0; - gridColumn1.CommitAction = (dataSource, rowNum) => - { - Assert.Same(currencyManager, dataSource); - Assert.Equal(expectedRowNumber, rowNum); - commitCallCount1++; - return true; - }; - style.GridColumnStyles.Add(gridColumn1); - - var gridColumn2 = new SubDataGridColumnStyle - { - MappingName = "Value2" - }; - int editCallCount2 = 0; - gridColumn2.EditAction = (source, rowNum, bounds, readOnly, displayText, cellIsVisible) => - { - Assert.Same(currencyManager, source); - Assert.Equal(expectedRowNumber, rowNum); - Assert.NotEqual(Rectangle.Empty, bounds); - Assert.False(readOnly); - Assert.Null(displayText); - Assert.True(cellIsVisible); - editCallCount2++; - }; - int commitCallCount2 = 0; - gridColumn2.CommitAction = (dataSource, rowNum) => - { - Assert.Same(currencyManager, dataSource); - Assert.Equal(expectedRowNumber, rowNum); - commitCallCount2++; - return true; - }; - style.GridColumnStyles.Add(gridColumn2); - - var dataGrid = new SubDataGrid - { - BindingContext = bindingContext - }; - dataGrid.TableStyles.Add(style); - dataGrid.SetDataBinding(dataSource, null); - - // Simulate layout on the DataGrid. - using (var image = new Bitmap(10, 10)) - using (Graphics graphics = Graphics.FromImage(image)) - { - dataGrid.OnPaint(new PaintEventArgs(graphics, new Rectangle(0, 0, 1, 2))); - } - - dataGrid.Select(0); - Assert.True(dataGrid.IsSelected(0)); - Assert.False(dataGrid.IsSelected(1)); - - // Edit cell. - Assert.True(style.BeginEdit(gridColumn1, rowNumber)); - Assert.Equal(new DataGridCell(expectedRowNumber, 0), dataGrid.CurrentCell); - Assert.Equal(expectedEditCallCount, editCallCount1); - Assert.Equal(0, editCallCount2); - Assert.Equal(expectedCommitCallCount, commitCallCount1); - Assert.Equal(0, commitCallCount2); - Assert.False(dataGrid.IsSelected(0)); - Assert.False(dataGrid.IsSelected(1)); - } - - [Theory] - [InlineData(0, 0, 1, 0)] - [InlineData(1, 1, 2, 1)] - [InlineData(-1, 0, 1, 0)] - [InlineData(2, 1, 2, 1)] - public void DataGridTableStyle_BeginEdit_InvokeWithDataSourceEditing_ReturnsFalse(int rowNumber, int expectedRowNumber, int expectedEditCallCount, int expectedCommitCallCount) - { - var dataSource = new DataClass[] - { - new DataClass { Value1 = "Value1_1", Value2 = "Value2_1" }, - new DataClass { Value1 = "Value1_2", Value2 = "Value2_2" } - }; - var bindingContext = new BindingContext(); - CurrencyManager currencyManager = (CurrencyManager)bindingContext[dataSource, null]; - - var style = new DataGridTableStyle - { - MappingName = "DataClass[]" - }; - - var gridColumn1 = new SubDataGridColumnStyle - { - MappingName = "Value1" - }; - int editCallCount1 = 0; - gridColumn1.EditAction = (source, rowNum, bounds, readOnly, displayText, cellIsVisible) => - { - Assert.Same(currencyManager, source); - Assert.Equal(expectedRowNumber, rowNum); - Assert.NotEqual(Rectangle.Empty, bounds); - Assert.False(readOnly); - Assert.Null(displayText); - Assert.True(cellIsVisible); - editCallCount1++; - }; - int commitCallCount1 = 0; - gridColumn1.CommitAction = (dataSource, rowNum) => - { - Assert.Same(currencyManager, dataSource); - Assert.Equal(expectedRowNumber, rowNum); - commitCallCount1++; - return true; - }; - style.GridColumnStyles.Add(gridColumn1); - - var gridColumn2 = new SubDataGridColumnStyle - { - MappingName = "Value2" - }; - int editCallCount2 = 0; - gridColumn2.EditAction = (source, rowNum, bounds, readOnly, displayText, cellIsVisible) => - { - Assert.Same(currencyManager, source); - Assert.Equal(expectedRowNumber, rowNum); - Assert.NotEqual(Rectangle.Empty, bounds); - Assert.False(readOnly); - Assert.Null(displayText); - Assert.True(cellIsVisible); - editCallCount2++; - }; - int commitCallCount2 = 0; - gridColumn2.CommitAction = (dataSource, rowNum) => - { - Assert.Same(currencyManager, dataSource); - Assert.Equal(expectedRowNumber, rowNum); - commitCallCount2++; - return true; - }; - style.GridColumnStyles.Add(gridColumn2); - - var dataGrid = new SubDataGrid - { - BindingContext = bindingContext - }; - dataGrid.TableStyles.Add(style); - dataGrid.SetDataBinding(dataSource, null); - - // Simulate layout on the DataGrid. - using (var image = new Bitmap(10, 10)) - using (Graphics graphics = Graphics.FromImage(image)) - { - dataGrid.OnPaint(new PaintEventArgs(graphics, new Rectangle(0, 0, 1, 2))); - } - - // Edit cell. - Assert.True(style.BeginEdit(gridColumn1, rowNumber)); - Assert.Equal(new DataGridCell(expectedRowNumber, 0), dataGrid.CurrentCell); - Assert.Equal(expectedEditCallCount, editCallCount1); - Assert.Equal(0, editCallCount2); - Assert.Equal(expectedCommitCallCount, commitCallCount1); - Assert.Equal(0, commitCallCount2); - Assert.False(dataGrid.IsSelected(0)); - Assert.False(dataGrid.IsSelected(1)); - - // Actual edit. - dataGrid.ColumnStartedEditing(Rectangle.Empty); - Assert.False(style.BeginEdit(gridColumn1, rowNumber)); - Assert.Equal(new DataGridCell(expectedRowNumber, 0), dataGrid.CurrentCell); - Assert.Equal(expectedEditCallCount, editCallCount1); - Assert.Equal(0, editCallCount2); - Assert.Equal(expectedCommitCallCount, commitCallCount1); - Assert.Equal(0, commitCallCount2); - Assert.False(dataGrid.IsSelected(0)); - Assert.False(dataGrid.IsSelected(1)); - } - - public static IEnumerable BeginEdit_WithoutDataSource_TestData() - { - yield return new object[] { null, null, -1, null }; - yield return new object[] { null, null, 0, null }; - yield return new object[] { null, null, 1, null }; - yield return new object[] { null, new SubDataGridColumnStyle(), -1, null }; - yield return new object[] { null, new SubDataGridColumnStyle(), 0, null }; - yield return new object[] { null, new SubDataGridColumnStyle(), 1, null }; - - yield return new object[] { new DataGrid(), null, -1, new DataGridCell(0, 0) }; - yield return new object[] { new DataGrid(), null, 0, new DataGridCell(0, 0) }; - yield return new object[] { new DataGrid(), null, 1, new DataGridCell(0, 0) }; - yield return new object[] { new DataGrid(), new SubDataGridColumnStyle(), -1, new DataGridCell(0, 0) }; - yield return new object[] { new DataGrid(), new SubDataGridColumnStyle(), 0, new DataGridCell(0, 0) }; - yield return new object[] { new DataGrid(), new SubDataGridColumnStyle(), 1, new DataGridCell(0, 0) }; - } - - [Theory] - [MemberData(nameof(BeginEdit_WithoutDataSource_TestData))] - public void DataGridTableStyle_BeginEdit_InvokeWithoutDataSource_ReturnsFalse(DataGrid dataGrid, DataGridColumnStyle gridColumn, int rowNumber, DataGridCell? expectedCurrentCell) - { - var style = new DataGridTableStyle - { - DataGrid = dataGrid - }; - Assert.False(style.BeginEdit(gridColumn, rowNumber)); - Assert.Equal(expectedCurrentCell, dataGrid?.CurrentCell); - } - - [Fact] - public void DataGridTableStyle_CreateGridColumn_InvokePropertyDescriptorBoolProperty_ReturnsExpected() - { - PropertyDescriptor prop = TypeDescriptor.GetProperties(typeof(ClassWithProperties))[nameof(ClassWithProperties.BoolProperty)]; - var style = new SubDataGridTableStyle(); - DataGridBoolColumn columnStyle = Assert.IsType(style.CreateGridColumn(prop)); - Assert.Same(prop, columnStyle.PropertyDescriptor); - Assert.Empty(columnStyle.MappingName); - } - - [Theory] - [InlineData(nameof(ClassWithProperties.SByteProperty), "G")] - [InlineData(nameof(ClassWithProperties.ShortProperty), "G")] - [InlineData(nameof(ClassWithProperties.IntProperty), "G")] - [InlineData(nameof(ClassWithProperties.LongProperty), "G")] - [InlineData(nameof(ClassWithProperties.ByteProperty), "G")] - [InlineData(nameof(ClassWithProperties.UShortProperty), "G")] - [InlineData(nameof(ClassWithProperties.UIntProperty), "G")] - [InlineData(nameof(ClassWithProperties.ULongProperty), "G")] - [InlineData(nameof(ClassWithProperties.CharProperty), "")] - [InlineData(nameof(ClassWithProperties.StringProperty), "")] - [InlineData(nameof(ClassWithProperties.DateTimeProperty), "d")] - [InlineData(nameof(ClassWithProperties.DecimalProperty), "G")] - [InlineData(nameof(ClassWithProperties.DoubleProperty), "G")] - [InlineData(nameof(ClassWithProperties.FloatProperty), "G")] - [InlineData(nameof(ClassWithProperties.ObjectProperty), "")] - public void DataGridTableStyle_CreateGridColumn_InvokePropertyDescriptorTextBoxProperty_ReturnsExpected(string propertyName, string expectedFormat) - { - PropertyDescriptor prop = TypeDescriptor.GetProperties(typeof(ClassWithProperties))[propertyName]; - var style = new SubDataGridTableStyle(); - DataGridTextBoxColumn columnStyle = Assert.IsType(style.CreateGridColumn(prop)); - Assert.Same(prop, columnStyle.PropertyDescriptor); - Assert.Equal(expectedFormat, columnStyle.Format); - Assert.Empty(columnStyle.MappingName); - } - - [Theory] - [InlineData(true, nameof(ClassWithProperties.BoolProperty))] - [InlineData(false, "")] - public void DataGridTableStyle_CreateGridColumn_InvokePropertyDescriptorBoolBoolProperty_ReturnsExpected(bool isDefault, string expectedMappingName) - { - PropertyDescriptor prop = TypeDescriptor.GetProperties(typeof(ClassWithProperties))[nameof(ClassWithProperties.BoolProperty)]; - var style = new SubDataGridTableStyle(); - DataGridBoolColumn columnStyle = Assert.IsType(style.CreateGridColumn(prop, isDefault)); - Assert.Same(prop, columnStyle.PropertyDescriptor); - Assert.Equal(expectedMappingName, columnStyle.MappingName); - } - - public static IEnumerable CreateGridColumn_TextBoxProperty_TestData() - { - yield return new object[] { nameof(ClassWithProperties.SByteProperty), false, "G", string.Empty }; - yield return new object[] { nameof(ClassWithProperties.ShortProperty), false, "G", string.Empty }; - yield return new object[] { nameof(ClassWithProperties.IntProperty), false, "G", string.Empty }; - yield return new object[] { nameof(ClassWithProperties.LongProperty), false, "G", string.Empty }; - yield return new object[] { nameof(ClassWithProperties.ByteProperty), false, "G", string.Empty }; - yield return new object[] { nameof(ClassWithProperties.UShortProperty), false, "G", string.Empty }; - yield return new object[] { nameof(ClassWithProperties.UIntProperty), false, "G", string.Empty }; - yield return new object[] { nameof(ClassWithProperties.ULongProperty), false, "G", string.Empty }; - yield return new object[] { nameof(ClassWithProperties.CharProperty), false, "", string.Empty }; - yield return new object[] { nameof(ClassWithProperties.StringProperty), false, "", string.Empty }; - yield return new object[] { nameof(ClassWithProperties.DateTimeProperty), false, "d", string.Empty }; - yield return new object[] { nameof(ClassWithProperties.DecimalProperty), false, "G", string.Empty }; - yield return new object[] { nameof(ClassWithProperties.DoubleProperty), false, "G", string.Empty }; - yield return new object[] { nameof(ClassWithProperties.FloatProperty), false, "G", string.Empty }; - yield return new object[] { nameof(ClassWithProperties.ObjectProperty), false, "", string.Empty }; - - yield return new object[] { nameof(ClassWithProperties.SByteProperty), true, "G", nameof(ClassWithProperties.SByteProperty) }; - yield return new object[] { nameof(ClassWithProperties.ShortProperty), true, "G", nameof(ClassWithProperties.ShortProperty) }; - yield return new object[] { nameof(ClassWithProperties.IntProperty), true, "G", nameof(ClassWithProperties.IntProperty) }; - yield return new object[] { nameof(ClassWithProperties.LongProperty), true, "G", nameof(ClassWithProperties.LongProperty) }; - yield return new object[] { nameof(ClassWithProperties.ByteProperty), true, "G", nameof(ClassWithProperties.ByteProperty) }; - yield return new object[] { nameof(ClassWithProperties.UShortProperty), true, "G", nameof(ClassWithProperties.UShortProperty) }; - yield return new object[] { nameof(ClassWithProperties.UIntProperty), true, "G", nameof(ClassWithProperties.UIntProperty) }; - yield return new object[] { nameof(ClassWithProperties.ULongProperty), true, "G", nameof(ClassWithProperties.ULongProperty) }; - yield return new object[] { nameof(ClassWithProperties.CharProperty), true, "", nameof(ClassWithProperties.CharProperty) }; - yield return new object[] { nameof(ClassWithProperties.StringProperty), true, "", nameof(ClassWithProperties.StringProperty) }; - yield return new object[] { nameof(ClassWithProperties.DateTimeProperty), true, "d", nameof(ClassWithProperties.DateTimeProperty) }; - yield return new object[] { nameof(ClassWithProperties.DecimalProperty), true, "G", nameof(ClassWithProperties.DecimalProperty) }; - yield return new object[] { nameof(ClassWithProperties.DoubleProperty), true, "G", nameof(ClassWithProperties.DoubleProperty) }; - yield return new object[] { nameof(ClassWithProperties.FloatProperty), true, "G", nameof(ClassWithProperties.FloatProperty) }; - yield return new object[] { nameof(ClassWithProperties.ObjectProperty), true, "", nameof(ClassWithProperties.ObjectProperty) }; - } - - [Theory] - [MemberData(nameof(CreateGridColumn_TextBoxProperty_TestData))] - public void DataGridTableStyle_CreateGridColumn_InvokePropertyDescriptorBoolTextBoxProperty_ReturnsExpected(string propertyName, bool isDefault, string expectedFormat, string expectedMappingName) - { - PropertyDescriptor prop = TypeDescriptor.GetProperties(typeof(ClassWithProperties))[propertyName]; - var style = new SubDataGridTableStyle(); - DataGridTextBoxColumn columnStyle = Assert.IsType(style.CreateGridColumn(prop, isDefault)); - Assert.Same(prop, columnStyle.PropertyDescriptor); - Assert.Equal(expectedFormat, columnStyle.Format); - Assert.Equal(expectedMappingName, columnStyle.MappingName); - } - - [Fact] - public void DataGridTableStyle_CreateGridColumn_NullProp_ThrowsArgumentNullException() - { - var style = new SubDataGridTableStyle(); - Assert.Throws("prop", () => style.CreateGridColumn(null)); - Assert.Throws("prop", () => style.CreateGridColumn(null, isDefault: true)); - Assert.Throws("prop", () => style.CreateGridColumn(null, isDefault: false)); - } - - [Fact] - public void DataGridTableStyle_Dispose_InvokeWithEmptyGridColumnStyles_Nop() - { - var style = new DataGridTableStyle(); - style.Dispose(); - style.Dispose(); - } - - [Fact] - public void DataGridTableStyle_Dispose_InvokeWithNullGridColumnStyles_Nop() - { - var style = new NullGridColumnStylesDataGridTableStyle(); - style.Dispose(); - style.Dispose(); - } - - [Fact] - public void DataGridTableStyle_Dispose_Invoke_CallsDisposeOnChildren() - { - var columnStyle = new SubDataGridColumnStyle(); - int disposeCallCount = 0; - columnStyle.DisposeAction = (disposing) => - { - Assert.True(disposing); - disposeCallCount++; - }; - var style = new DataGridTableStyle(); - style.GridColumnStyles.Add(columnStyle); - - style.Dispose(); - Assert.Equal(1, disposeCallCount); - Assert.Same(columnStyle, Assert.Single(style.GridColumnStyles)); - - // Call again. - style.Dispose(); - Assert.Equal(2, disposeCallCount); - Assert.Same(columnStyle, Assert.Single(style.GridColumnStyles)); - - columnStyle.DisposeAction = null; - } - - [Fact] - public void DataGridTableStyle_Dispose_InvokeWithHandler_CallsDisposed() - { - var style = new DataGridTableStyle(); - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(style, sender); - Assert.Same(EventArgs.Empty, e); - callCount++; - }; - style.Disposed += handler; - - // Call with handler. - style.Dispose(); - Assert.Equal(1, callCount); - - // Call again. - style.Dispose(); - Assert.Equal(2, callCount); - - // Remove handler. - style.Disposed -= handler; - style.Dispose(); - Assert.Equal(2, callCount); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetBoolTheoryData))] - public void DataGridTableStyle_Dispose_InvokeBoolWithEmptyGridColumnStyles_Nop(bool disposing) - { - var style = new SubDataGridTableStyle(); - style.Dispose(disposing); - style.Dispose(disposing); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetBoolTheoryData))] - public void DataGridTableStyle_Dispose_InvokeBoolWithNullGridColumnStyles_Nop(bool disposing) - { - var style = new NullGridColumnStylesDataGridTableStyle(); - style.Dispose(disposing); - style.Dispose(disposing); - } - - [Theory] - [InlineData(true, 1)] - [InlineData(false, 0)] - public void DataGridTableStyle_Dispose_InvokeBool_CallsDisposeOnChildren(bool disposing, int expectedCallCount) - { - var columnStyle = new SubDataGridColumnStyle(); - int disposeCallCount = 0; - columnStyle.DisposeAction += (disposing) => - { - Assert.True(disposing); - disposeCallCount++; - }; - var style = new SubDataGridTableStyle(); - style.GridColumnStyles.Add(columnStyle); - - style.Dispose(disposing); - Assert.Equal(expectedCallCount, disposeCallCount); - Assert.Same(columnStyle, Assert.Single(style.GridColumnStyles)); - - // Call again. - style.Dispose(disposing); - Assert.Equal(expectedCallCount * 2, disposeCallCount); - Assert.Same(columnStyle, Assert.Single(style.GridColumnStyles)); - - columnStyle.DisposeAction = null; - } - - [Theory] - [InlineData(true, 1)] - [InlineData(false, 0)] - public void DataGridTableStyle_Dispose_InvokeBoolWithHandler_CallsDisposed(bool disposing, int expectedCallCount) - { - var style = new SubDataGridTableStyle(); - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(style, sender); - Assert.Same(EventArgs.Empty, e); - callCount++; - }; - style.Disposed += handler; - - // Call with handler. - style.Dispose(disposing); - Assert.Equal(expectedCallCount, callCount); - - // Call again. - style.Dispose(disposing); - Assert.Equal(expectedCallCount * 2, callCount); - - // Remove handler. - style.Disposed -= handler; - style.Dispose(disposing); - Assert.Equal(expectedCallCount * 2, callCount); - } - - public static IEnumerable EndEdit_DataSource_TestData() - { - foreach (bool commitResult in new bool[] { true, false }) - { - yield return new object[] { 0, true, 0, 1, 0, 1, 0, commitResult, true }; - yield return new object[] { 1, true, 1, 2, 1, 1, 1, commitResult, true }; - yield return new object[] { -1, true, 0, 1, 0, 1, 0, commitResult, true }; - yield return new object[] { 2, true, 1, 2, 1, 1, 1, commitResult, true }; - yield return new object[] { 0, false, 0, 1, 0, 0, 1, commitResult, commitResult }; - yield return new object[] { 1, false, 1, 2, 1, 0, 2, commitResult, commitResult }; - yield return new object[] { -1, false, 0, 1, 0, 0, 1, commitResult, commitResult }; - yield return new object[] { 2, false, 1, 2, 1, 0, 2, commitResult, commitResult }; - } - } - - [Theory] - [MemberData(nameof(EndEdit_DataSource_TestData))] - public void DataGridTableStyle_EndEdit_InvokeWithDataSourceAbort_ReturnsExpected(int rowNumber, bool shouldAbort, int expectedRowNumber, int expectedEditCallCount, int expectedCommitCallCount, int expectedAbortCallCount, int expectedCommitCallCount2, bool commitResult, bool expected) - { - var dataSource = new DataClass[] - { - new DataClass { Value1 = "Value1_1", Value2 = "Value2_1" }, - new DataClass { Value1 = "Value1_2", Value2 = "Value2_2" } - }; - var bindingContext = new BindingContext(); - CurrencyManager currencyManager = (CurrencyManager)bindingContext[dataSource, null]; - - var style = new DataGridTableStyle - { - MappingName = "DataClass[]" - }; - - var gridColumn1 = new SubDataGridColumnStyle - { - MappingName = "Value1" - }; - int editCallCount1 = 0; - gridColumn1.EditAction = (source, rowNum, bounds, readOnly, displayText, cellIsVisible) => - { - Assert.Same(currencyManager, source); - Assert.Equal(expectedRowNumber, rowNum); - Assert.NotEqual(Rectangle.Empty, bounds); - Assert.False(readOnly); - Assert.Null(displayText); - Assert.True(cellIsVisible); - editCallCount1++; - }; - int commitCallCount1 = 0; - gridColumn1.CommitAction = (dataSource, rowNum) => - { - Assert.Same(currencyManager, dataSource); - Assert.Equal(expectedRowNumber, rowNum); - commitCallCount1++; - return true; - }; - int abortCallCount1 = 0; - gridColumn1.AbortAction = (rowNum) => - { - Assert.Equal(expectedRowNumber, rowNum); - abortCallCount1++; - }; - style.GridColumnStyles.Add(gridColumn1); - - var gridColumn2 = new SubDataGridColumnStyle - { - MappingName = "Value2" - }; - int editCallCount2 = 0; - gridColumn2.EditAction = (source, rowNum, bounds, readOnly, displayText, cellIsVisible) => - { - Assert.Same(currencyManager, source); - Assert.Equal(expectedRowNumber, rowNum); - Assert.NotEqual(Rectangle.Empty, bounds); - Assert.False(readOnly); - Assert.Null(displayText); - Assert.True(cellIsVisible); - editCallCount2++; - }; - int commitCallCount2 = 0; - gridColumn2.CommitAction = (dataSource, rowNum) => - { - Assert.Same(currencyManager, dataSource); - Assert.Equal(expectedRowNumber, rowNum); - commitCallCount2++; - return true; - }; - int abortCallCount2 = 0; - gridColumn2.AbortAction = (rowNum) => - { - Assert.Equal(expectedRowNumber, rowNum); - abortCallCount2++; - }; - style.GridColumnStyles.Add(gridColumn2); - - var dataGrid = new SubDataGrid - { - BindingContext = bindingContext - }; - dataGrid.TableStyles.Add(style); - dataGrid.SetDataBinding(dataSource, null); - - // Simulate layout on the DataGrid. - using (var image = new Bitmap(10, 10)) - using (Graphics graphics = Graphics.FromImage(image)) - { - dataGrid.OnPaint(new PaintEventArgs(graphics, new Rectangle(0, 0, 1, 2))); - } - - // Edit cell. - Assert.True(style.BeginEdit(gridColumn1, rowNumber)); - Assert.Equal(new DataGridCell(expectedRowNumber, 0), dataGrid.CurrentCell); - Assert.Equal(expectedEditCallCount, editCallCount1); - Assert.Equal(0, editCallCount2); - Assert.Equal(expectedCommitCallCount, commitCallCount1); - Assert.Equal(0, commitCallCount2); - Assert.Equal(0, abortCallCount1); - Assert.Equal(0, abortCallCount2); - Assert.False(dataGrid.IsSelected(0)); - Assert.False(dataGrid.IsSelected(1)); - - // End edit. - gridColumn1.CommitAction = (dataSource, rowNum) => - { - Assert.Same(currencyManager, dataSource); - Assert.Equal(expectedRowNumber, rowNum); - commitCallCount1++; - return commitResult; - }; - gridColumn2.CommitAction = (dataSource, rowNum) => - { - Assert.Same(currencyManager, dataSource); - Assert.Equal(expectedRowNumber, rowNum); - commitCallCount2++; - return commitResult; - }; - dataGrid.ColumnStartedEditing(Rectangle.Empty); - Assert.Equal(expected, style.EndEdit(gridColumn1, rowNumber, shouldAbort)); - Assert.Equal(new DataGridCell(expectedRowNumber, 0), dataGrid.CurrentCell); - Assert.Equal(expectedEditCallCount, editCallCount1); - Assert.Equal(0, editCallCount2); - Assert.Equal(expectedCommitCallCount2, commitCallCount1); - Assert.Equal(0, commitCallCount2); - Assert.Equal(expectedAbortCallCount, abortCallCount1); - Assert.Equal(0, abortCallCount2); - Assert.False(dataGrid.IsSelected(0)); - Assert.False(dataGrid.IsSelected(1)); - - // End edit again. - Assert.False(style.EndEdit(gridColumn1, rowNumber, shouldAbort)); - } - - [Theory] - [MemberData(nameof(EndEdit_DataSource_TestData))] - public void DataGridTableStyle_EndEdit_InvokeWithDataSourceDifferentColumn_ReturnsExpected(int rowNumber, bool shouldAbort, int expectedRowNumber, int expectedEditCallCount, int expectedCommitCallCount, int expectedAbortCallCount, int expectedCommitCallCount2, bool commitResult, bool expected) - { - var dataSource = new DataClass[] - { - new DataClass { Value1 = "Value1_1", Value2 = "Value2_1" }, - new DataClass { Value1 = "Value1_2", Value2 = "Value2_2" } - }; - var bindingContext = new BindingContext(); - CurrencyManager currencyManager = (CurrencyManager)bindingContext[dataSource, null]; - - var style = new DataGridTableStyle - { - MappingName = "DataClass[]" - }; - - var gridColumn1 = new SubDataGridColumnStyle - { - MappingName = "Value1" - }; - int editCallCount1 = 0; - gridColumn1.EditAction = (source, rowNum, bounds, readOnly, displayText, cellIsVisible) => - { - Assert.Same(currencyManager, source); - Assert.Equal(expectedRowNumber, rowNum); - Assert.NotEqual(Rectangle.Empty, bounds); - Assert.False(readOnly); - Assert.Null(displayText); - Assert.True(cellIsVisible); - editCallCount1++; - }; - int commitCallCount1 = 0; - gridColumn1.CommitAction = (dataSource, rowNum) => - { - Assert.Same(currencyManager, dataSource); - Assert.Equal(expectedRowNumber, rowNum); - commitCallCount1++; - return true; - }; - int abortCallCount1 = 0; - gridColumn1.AbortAction = (rowNum) => - { - Assert.Equal(expectedRowNumber, rowNum); - abortCallCount1++; - }; - style.GridColumnStyles.Add(gridColumn1); - - var gridColumn2 = new SubDataGridColumnStyle - { - MappingName = "Value2" - }; - int editCallCount2 = 0; - gridColumn2.EditAction = (source, rowNum, bounds, readOnly, displayText, cellIsVisible) => - { - Assert.Same(currencyManager, source); - Assert.Equal(expectedRowNumber, rowNum); - Assert.NotEqual(Rectangle.Empty, bounds); - Assert.False(readOnly); - Assert.Null(displayText); - Assert.True(cellIsVisible); - editCallCount2++; - }; - int commitCallCount2 = 0; - gridColumn2.CommitAction = (dataSource, rowNum) => - { - Assert.Same(currencyManager, dataSource); - Assert.Equal(expectedRowNumber, rowNum); - commitCallCount2++; - return true; - }; - int abortCallCount2 = 0; - gridColumn2.AbortAction = (rowNum) => - { - Assert.Equal(expectedRowNumber, rowNum); - abortCallCount2++; - }; - style.GridColumnStyles.Add(gridColumn2); - - var dataGrid = new SubDataGrid - { - BindingContext = bindingContext - }; - dataGrid.TableStyles.Add(style); - dataGrid.SetDataBinding(dataSource, null); - - // Simulate layout on the DataGrid. - using (var image = new Bitmap(10, 10)) - using (Graphics graphics = Graphics.FromImage(image)) - { - dataGrid.OnPaint(new PaintEventArgs(graphics, new Rectangle(0, 0, 1, 2))); - } - - // Edit cell. - Assert.True(style.BeginEdit(gridColumn1, rowNumber)); - Assert.Equal(new DataGridCell(expectedRowNumber, 0), dataGrid.CurrentCell); - Assert.Equal(expectedEditCallCount, editCallCount1); - Assert.Equal(0, editCallCount2); - Assert.Equal(expectedCommitCallCount, commitCallCount1); - Assert.Equal(0, commitCallCount2); - Assert.Equal(0, abortCallCount1); - Assert.Equal(0, abortCallCount2); - Assert.False(dataGrid.IsSelected(0)); - Assert.False(dataGrid.IsSelected(1)); - - // End edit. - gridColumn1.CommitAction = (dataSource, rowNum) => - { - Assert.Same(currencyManager, dataSource); - Assert.Equal(expectedRowNumber, rowNum); - commitCallCount1++; - return commitResult; - }; - gridColumn2.CommitAction = (dataSource, rowNum) => - { - Assert.Same(currencyManager, dataSource); - Assert.Equal(expectedRowNumber, rowNum); - commitCallCount2++; - return commitResult; - }; - dataGrid.ColumnStartedEditing(Rectangle.Empty); - Assert.Equal(expected, style.EndEdit(gridColumn2, rowNumber, shouldAbort)); - Assert.Equal(new DataGridCell(expectedRowNumber, 0), dataGrid.CurrentCell); - Assert.Equal(expectedEditCallCount, editCallCount1); - Assert.Equal(0, editCallCount2); - Assert.Equal(expectedCommitCallCount2, commitCallCount1); - Assert.Equal(0, commitCallCount2); - Assert.Equal(expectedAbortCallCount, abortCallCount1); - Assert.Equal(0, abortCallCount2); - Assert.False(dataGrid.IsSelected(0)); - Assert.False(dataGrid.IsSelected(1)); - - // End edit again. - Assert.False(style.EndEdit(gridColumn2, rowNumber, shouldAbort)); - } - - public static IEnumerable EndEdit_DataSourceInvalidColumn_TestData() - { - foreach (object[] testData in EndEdit_DataSource_TestData()) - { - yield return testData.Prepend(null).ToArray(); - yield return testData.Prepend(new SubDataGridColumnStyle()).ToArray(); - } - } - - [Theory] - [MemberData(nameof(EndEdit_DataSourceInvalidColumn_TestData))] - public void DataGridTableStyle_EndEdit_InvokeWithDataSourceInvalidColumn_ReturnsExpected(DataGridColumnStyle gridColumn, int rowNumber, bool shouldAbort, int expectedRowNumber, int expectedEditCallCount, int expectedCommitCallCount, int expectedAbortCallCount, int expectedCommitCallCount2, bool commitResult, bool expected) - { - var dataSource = new DataClass[] - { - new DataClass { Value1 = "Value1_1", Value2 = "Value2_1" }, - new DataClass { Value1 = "Value1_2", Value2 = "Value2_2" } - }; - var bindingContext = new BindingContext(); - CurrencyManager currencyManager = (CurrencyManager)bindingContext[dataSource, null]; - - var style = new DataGridTableStyle - { - MappingName = "DataClass[]" - }; - - var gridColumn1 = new SubDataGridColumnStyle - { - MappingName = "Value1" - }; - int editCallCount1 = 0; - gridColumn1.EditAction = (source, rowNum, bounds, readOnly, displayText, cellIsVisible) => - { - Assert.Same(currencyManager, source); - Assert.Equal(expectedRowNumber, rowNum); - Assert.NotEqual(Rectangle.Empty, bounds); - Assert.False(readOnly); - Assert.Null(displayText); - Assert.True(cellIsVisible); - editCallCount1++; - }; - int commitCallCount1 = 0; - gridColumn1.CommitAction = (dataSource, rowNum) => - { - Assert.Same(currencyManager, dataSource); - Assert.Equal(expectedRowNumber, rowNum); - commitCallCount1++; - return true; - }; - int abortCallCount1 = 0; - gridColumn1.AbortAction = (rowNum) => - { - Assert.Equal(expectedRowNumber, rowNum); - abortCallCount1++; - }; - style.GridColumnStyles.Add(gridColumn1); - - var gridColumn2 = new SubDataGridColumnStyle - { - MappingName = "Value2" - }; - int editCallCount2 = 0; - gridColumn2.EditAction = (source, rowNum, bounds, readOnly, displayText, cellIsVisible) => - { - Assert.Same(currencyManager, source); - Assert.Equal(expectedRowNumber, rowNum); - Assert.NotEqual(Rectangle.Empty, bounds); - Assert.False(readOnly); - Assert.Null(displayText); - Assert.True(cellIsVisible); - editCallCount2++; - }; - int commitCallCount2 = 0; - gridColumn2.CommitAction = (dataSource, rowNum) => - { - Assert.Same(currencyManager, dataSource); - Assert.Equal(expectedRowNumber, rowNum); - commitCallCount2++; - return true; - }; - int abortCallCount2 = 0; - gridColumn2.AbortAction = (rowNum) => - { - Assert.Equal(expectedRowNumber, rowNum); - abortCallCount2++; - }; - style.GridColumnStyles.Add(gridColumn2); - - var dataGrid = new SubDataGrid - { - BindingContext = bindingContext - }; - dataGrid.TableStyles.Add(style); - dataGrid.SetDataBinding(dataSource, null); - - // Simulate layout on the DataGrid. - using (var image = new Bitmap(10, 10)) - using (Graphics graphics = Graphics.FromImage(image)) - { - dataGrid.OnPaint(new PaintEventArgs(graphics, new Rectangle(0, 0, 1, 2))); - } - - // Edit cell. - Assert.True(style.BeginEdit(gridColumn1, rowNumber)); - Assert.Equal(new DataGridCell(expectedRowNumber, 0), dataGrid.CurrentCell); - Assert.Equal(expectedEditCallCount, editCallCount1); - Assert.Equal(0, editCallCount2); - Assert.Equal(expectedCommitCallCount, commitCallCount1); - Assert.Equal(0, commitCallCount2); - Assert.Equal(0, abortCallCount1); - Assert.Equal(0, abortCallCount2); - Assert.False(dataGrid.IsSelected(0)); - Assert.False(dataGrid.IsSelected(1)); - - // End edit. - gridColumn1.CommitAction = (dataSource, rowNum) => - { - Assert.Same(currencyManager, dataSource); - Assert.Equal(expectedRowNumber, rowNum); - commitCallCount1++; - return commitResult; - }; - gridColumn2.CommitAction = (dataSource, rowNum) => - { - Assert.Same(currencyManager, dataSource); - Assert.Equal(expectedRowNumber, rowNum); - commitCallCount2++; - return commitResult; - }; - dataGrid.ColumnStartedEditing(Rectangle.Empty); - Assert.Equal(expected, style.EndEdit(gridColumn, rowNumber, shouldAbort)); - Assert.Equal(new DataGridCell(expectedRowNumber, 0), dataGrid.CurrentCell); - Assert.Equal(expectedEditCallCount, editCallCount1); - Assert.Equal(0, editCallCount2); - Assert.Equal(expectedCommitCallCount2, commitCallCount1); - Assert.Equal(0, commitCallCount2); - Assert.Equal(expectedAbortCallCount, abortCallCount1); - Assert.Equal(0, abortCallCount2); - Assert.False(dataGrid.IsSelected(0)); - Assert.False(dataGrid.IsSelected(1)); - - // End edit again. - Assert.False(style.EndEdit(gridColumn, rowNumber, shouldAbort)); - } - - [Theory] - [InlineData(0, true, 0, 1, 0)] - [InlineData(1, true, 1, 2, 1)] - [InlineData(-1, true, 0, 1, 0)] - [InlineData(2, true, 1, 2, 1)] - [InlineData(0, false, 0, 1, 0)] - [InlineData(1, false, 1, 2, 1)] - [InlineData(-1, false, 0, 1, 0)] - [InlineData(2, false, 1, 2, 1)] - public void DataGridTableStyle_EndEdit_InvokeWithDataSourceNotEditing_ReturnsFalse(int rowNumber, bool shouldAbort, int expectedRowNumber, int expectedEditCallCount, int expectedCommitCallCount) - { - var dataSource = new DataClass[] - { - new DataClass { Value1 = "Value1_1", Value2 = "Value2_1" }, - new DataClass { Value1 = "Value1_2", Value2 = "Value2_2" } - }; - var bindingContext = new BindingContext(); - CurrencyManager currencyManager = (CurrencyManager)bindingContext[dataSource, null]; - - var style = new DataGridTableStyle - { - MappingName = "DataClass[]" - }; - - var gridColumn1 = new SubDataGridColumnStyle - { - MappingName = "Value1" - }; - int editCallCount1 = 0; - gridColumn1.EditAction = (source, rowNum, bounds, readOnly, displayText, cellIsVisible) => - { - editCallCount1++; - }; - int commitCallCount1 = 0; - gridColumn1.CommitAction = (dataSource, rowNum) => - { - commitCallCount1++; - return true; - }; - style.GridColumnStyles.Add(gridColumn1); - - var gridColumn2 = new SubDataGridColumnStyle - { - MappingName = "Value2" - }; - int editCallCount2 = 0; - gridColumn2.EditAction = (source, rowNum, bounds, readOnly, displayText, cellIsVisible) => - { - editCallCount2++; - }; - int commitCallCount2 = 0; - gridColumn2.CommitAction = (dataSource, rowNum) => - { - commitCallCount2++; - return true; - }; - style.GridColumnStyles.Add(gridColumn2); - - var dataGrid = new SubDataGrid - { - BindingContext = bindingContext - }; - dataGrid.TableStyles.Add(style); - dataGrid.SetDataBinding(dataSource, null); - - // Simulate layout on the DataGrid. - using (var image = new Bitmap(10, 10)) - using (Graphics graphics = Graphics.FromImage(image)) - { - dataGrid.OnPaint(new PaintEventArgs(graphics, new Rectangle(0, 0, 1, 2))); - } - - // Edit cell. - Assert.True(style.BeginEdit(gridColumn1, rowNumber)); - Assert.Equal(new DataGridCell(expectedRowNumber, 0), dataGrid.CurrentCell); - Assert.Equal(expectedEditCallCount, editCallCount1); - Assert.Equal(0, editCallCount2); - Assert.Equal(expectedCommitCallCount, commitCallCount1); - Assert.Equal(0, commitCallCount2); - Assert.False(dataGrid.IsSelected(0)); - Assert.False(dataGrid.IsSelected(1)); - - // End edit. - Assert.False(style.EndEdit(gridColumn1, rowNumber, shouldAbort)); - Assert.Equal(new DataGridCell(expectedRowNumber, 0), dataGrid.CurrentCell); - Assert.Equal(expectedEditCallCount, editCallCount1); - Assert.Equal(0, editCallCount2); - Assert.Equal(expectedCommitCallCount, commitCallCount1); - Assert.Equal(0, commitCallCount2); - Assert.False(dataGrid.IsSelected(0)); - Assert.False(dataGrid.IsSelected(1)); - } - - public static IEnumerable EndEdit_TestData() - { - foreach (bool shouldAbort in new bool[] { true, false }) - { - yield return new object[] { null, null, -1, shouldAbort, null }; - yield return new object[] { null, null, 0, shouldAbort, null }; - yield return new object[] { null, null, 1, shouldAbort, null }; - yield return new object[] { null, new SubDataGridColumnStyle(), -1, shouldAbort, null }; - yield return new object[] { null, new SubDataGridColumnStyle(), 0, shouldAbort, null }; - yield return new object[] { null, new SubDataGridColumnStyle(), 1, shouldAbort, null }; - - yield return new object[] { new DataGrid(), null, -1, shouldAbort, new DataGridCell(0, 0) }; - yield return new object[] { new DataGrid(), null, 0, shouldAbort, new DataGridCell(0, 0) }; - yield return new object[] { new DataGrid(), null, 1, shouldAbort, new DataGridCell(0, 0) }; - yield return new object[] { new DataGrid(), new SubDataGridColumnStyle(), -1, shouldAbort, new DataGridCell(0, 0) }; - yield return new object[] { new DataGrid(), new SubDataGridColumnStyle(), 0, shouldAbort, new DataGridCell(0, 0) }; - yield return new object[] { new DataGrid(), new SubDataGridColumnStyle(), 1, shouldAbort, new DataGridCell(0, 0) }; - } - } - - [Theory] - [MemberData(nameof(EndEdit_TestData))] - public void DataGridTableStyle_EndEdit_InvokeWithoutDataSource_ReturnsFalse(DataGrid dataGrid, DataGridColumnStyle gridColumn, int rowNumber, bool shouldAbort, DataGridCell? expectedCurrentCell) - { - var style = new DataGridTableStyle - { - DataGrid = dataGrid - }; - Assert.False(style.EndEdit(gridColumn, rowNumber, shouldAbort)); - Assert.Equal(expectedCurrentCell, dataGrid?.CurrentCell); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetEventArgsTheoryData))] - public void DataGridTableStyle_OnAllowSortingChanged_Invoke_CallsAllowSortingChanged(EventArgs eventArgs) - { - var style = new SubDataGridTableStyle(); - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(style, sender); - Assert.Same(eventArgs, e); - callCount++; - }; - - // Call with handler. - style.AllowSortingChanged += handler; - style.OnAllowSortingChanged(eventArgs); - Assert.Equal(1, callCount); - - // Remove handler. - style.AllowSortingChanged -= handler; - style.OnAllowSortingChanged(eventArgs); - Assert.Equal(1, callCount); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetEventArgsTheoryData))] - public void DataGridTableStyle_OnAlternatingBackColorChanged_Invoke_CallsAlternatingBackColorChanged(EventArgs eventArgs) - { - var style = new SubDataGridTableStyle(); - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(style, sender); - Assert.Same(eventArgs, e); - callCount++; - }; - - // Call with handler. - style.AlternatingBackColorChanged += handler; - style.OnAlternatingBackColorChanged(eventArgs); - Assert.Equal(1, callCount); - - // Remove handler. - style.AlternatingBackColorChanged -= handler; - style.OnAlternatingBackColorChanged(eventArgs); - Assert.Equal(1, callCount); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetEventArgsTheoryData))] - public void DataGridTableStyle_OnBackColorChanged_Invoke_CallsBackColorChanged(EventArgs eventArgs) - { - var style = new SubDataGridTableStyle(); - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(style, sender); - Assert.Same(eventArgs, e); - callCount++; - }; - - // Call with handler. - style.BackColorChanged += handler; - style.OnBackColorChanged(eventArgs); - Assert.Equal(1, callCount); - - // Remove handler. - style.BackColorChanged -= handler; - style.OnBackColorChanged(eventArgs); - Assert.Equal(1, callCount); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetEventArgsTheoryData))] - public void DataGridTableStyle_OnColumnHeadersVisibleChanged_Invoke_CallsColumnHeadersVisibleChanged(EventArgs eventArgs) - { - var style = new SubDataGridTableStyle(); - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(style, sender); - Assert.Same(eventArgs, e); - callCount++; - }; - - // Call with handler. - style.ColumnHeadersVisibleChanged += handler; - style.OnColumnHeadersVisibleChanged(eventArgs); - Assert.Equal(1, callCount); - - // Remove handler. - style.ColumnHeadersVisibleChanged -= handler; - style.OnColumnHeadersVisibleChanged(eventArgs); - Assert.Equal(1, callCount); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetEventArgsTheoryData))] - public void DataGridTableStyle_OnForeColorChanged_Invoke_CallsForeColorChanged(EventArgs eventArgs) - { - var style = new SubDataGridTableStyle(); - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(style, sender); - Assert.Same(eventArgs, e); - callCount++; - }; - - // Call with handler. - style.ForeColorChanged += handler; - style.OnForeColorChanged(eventArgs); - Assert.Equal(1, callCount); - - // Remove handler. - style.ForeColorChanged -= handler; - style.OnForeColorChanged(eventArgs); - Assert.Equal(1, callCount); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetEventArgsTheoryData))] - public void DataGridTableStyle_OnGridLineColorChanged_Invoke_CallsGridLineColorChanged(EventArgs eventArgs) - { - var style = new SubDataGridTableStyle(); - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(style, sender); - Assert.Same(eventArgs, e); - callCount++; - }; - - // Call with handler. - style.GridLineColorChanged += handler; - style.OnGridLineColorChanged(eventArgs); - Assert.Equal(1, callCount); - - // Remove handler. - style.GridLineColorChanged -= handler; - style.OnGridLineColorChanged(eventArgs); - Assert.Equal(1, callCount); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetEventArgsTheoryData))] - public void DataGridTableStyle_OnGridLineStyleChanged_Invoke_CallsGridLineStyleChanged(EventArgs eventArgs) - { - var style = new SubDataGridTableStyle(); - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(style, sender); - Assert.Same(eventArgs, e); - callCount++; - }; - - // Call with handler. - style.GridLineStyleChanged += handler; - style.OnGridLineStyleChanged(eventArgs); - Assert.Equal(1, callCount); - - // Remove handler. - style.GridLineStyleChanged -= handler; - style.OnGridLineStyleChanged(eventArgs); - Assert.Equal(1, callCount); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetEventArgsTheoryData))] - public void DataGridTableStyle_OnHeaderBackColorChanged_Invoke_CallsHeaderBackColorChanged(EventArgs eventArgs) - { - var style = new SubDataGridTableStyle(); - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(style, sender); - Assert.Same(eventArgs, e); - callCount++; - }; - - // Call with handler. - style.HeaderBackColorChanged += handler; - style.OnHeaderBackColorChanged(eventArgs); - Assert.Equal(1, callCount); - - // Remove handler. - style.HeaderBackColorChanged -= handler; - style.OnHeaderBackColorChanged(eventArgs); - Assert.Equal(1, callCount); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetEventArgsTheoryData))] - public void DataGridTableStyle_OnHeaderFontChanged_Invoke_CallsHeaderFontChanged(EventArgs eventArgs) - { - var style = new SubDataGridTableStyle(); - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(style, sender); - Assert.Same(eventArgs, e); - callCount++; - }; - - // Call with handler. - style.HeaderFontChanged += handler; - style.OnHeaderFontChanged(eventArgs); - Assert.Equal(1, callCount); - - // Remove handler. - style.HeaderFontChanged -= handler; - style.OnHeaderFontChanged(eventArgs); - Assert.Equal(1, callCount); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetEventArgsTheoryData))] - public void DataGridTableStyle_OnHeaderForeColorChanged_Invoke_CallsHeaderForeColorChanged(EventArgs eventArgs) - { - var style = new SubDataGridTableStyle (); - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(style, sender); - Assert.Same(eventArgs, e); - callCount++; - }; - - // Call with handler. - style.HeaderForeColorChanged += handler; - style.OnHeaderForeColorChanged(eventArgs); - Assert.Equal(1, callCount); - - // Remove handler. - style.HeaderForeColorChanged -= handler; - style.OnHeaderForeColorChanged(eventArgs); - Assert.Equal(1, callCount); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetEventArgsTheoryData))] - public void DataGridTableStyle_OnLinkColorChanged_Invoke_CallsLineColorChanged(EventArgs eventArgs) - { - var style = new SubDataGridTableStyle(); - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(style, sender); - Assert.Same(eventArgs, e); - callCount++; - }; - - // Call with handler. - style.LinkColorChanged += handler; - style.OnLinkColorChanged(eventArgs); - Assert.Equal(1, callCount); - - // Remove handler. - style.LinkColorChanged -= handler; - style.OnLinkColorChanged(eventArgs); - Assert.Equal(1, callCount); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetEventArgsTheoryData))] - public void DataGridTableStyle_OnLinkHoverColorChanged_Invoke_CallsLinkHoverColorChanged(EventArgs eventArgs) - { - var style = new SubDataGridTableStyle(); - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(style, sender); - Assert.Same(eventArgs, e); - callCount++; - }; - - // Call with handler. - style.LinkHoverColorChanged += handler; - style.OnLinkHoverColorChanged(eventArgs); - Assert.Equal(1, callCount); - - // Remove handler. - style.LinkHoverColorChanged -= handler; - style.OnLinkHoverColorChanged(eventArgs); - Assert.Equal(1, callCount); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetEventArgsTheoryData))] - public void DataGridTableStyle_OnMappingNameChanged_Invoke_CallsMappingNameChanged(EventArgs eventArgs) - { - var style = new SubDataGridTableStyle(); - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(style, sender); - Assert.Same(eventArgs, e); - callCount++; - }; - - // Call with handler. - style.MappingNameChanged += handler; - style.OnMappingNameChanged(eventArgs); - Assert.Equal(1, callCount); - - // Remove handler. - style.MappingNameChanged -= handler; - style.OnMappingNameChanged(eventArgs); - Assert.Equal(1, callCount); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetEventArgsTheoryData))] - public void DataGridTableStyle_OnPreferredColumnWidthChanged_Invoke_CallsPreferredColumnWidthChanged(EventArgs eventArgs) - { - var style = new SubDataGridTableStyle(); - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(style, sender); - Assert.Same(eventArgs, e); - callCount++; - }; - - // Call with handler. - style.PreferredColumnWidthChanged += handler; - style.OnPreferredColumnWidthChanged(eventArgs); - Assert.Equal(1, callCount); - - // Remove handler. - style.PreferredColumnWidthChanged -= handler; - style.OnPreferredColumnWidthChanged(eventArgs); - Assert.Equal(1, callCount); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetEventArgsTheoryData))] - public void DataGridTableStyle_OnPreferredRowHeightChanged_Invoke_CallsPreferredRowHeightChanged(EventArgs eventArgs) - { - var style = new SubDataGridTableStyle(); - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(style, sender); - Assert.Same(eventArgs, e); - callCount++; - }; - - // Call with handler. - style.PreferredRowHeightChanged += handler; - style.OnPreferredRowHeightChanged(eventArgs); - Assert.Equal(1, callCount); - - // Remove handler. - style.PreferredRowHeightChanged -= handler; - style.OnPreferredRowHeightChanged(eventArgs); - Assert.Equal(1, callCount); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetEventArgsTheoryData))] - public void DataGridTableStyle_OnReadOnlyChanged_Invoke_CallsReadOnlyChanged(EventArgs eventArgs) - { - var style = new SubDataGridTableStyle(); - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(style, sender); - Assert.Same(eventArgs, e); - callCount++; - }; - - // Call with handler. - style.ReadOnlyChanged += handler; - style.OnReadOnlyChanged(eventArgs); - Assert.Equal(1, callCount); - - // Remove handler. - style.ReadOnlyChanged -= handler; - style.OnReadOnlyChanged(eventArgs); - Assert.Equal(1, callCount); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetEventArgsTheoryData))] - public void DataGridTableStyle_OnRowHeadersVisibleChanged_Invoke_CallsRowHeadersVisibleChanged(EventArgs eventArgs) - { - var style = new SubDataGridTableStyle(); - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(style, sender); - Assert.Same(eventArgs, e); - callCount++; - }; - - // Call with handler. - style.RowHeadersVisibleChanged += handler; - style.OnRowHeadersVisibleChanged(eventArgs); - Assert.Equal(1, callCount); - - // Remove handler. - style.RowHeadersVisibleChanged -= handler; - style.OnRowHeadersVisibleChanged(eventArgs); - Assert.Equal(1, callCount); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetEventArgsTheoryData))] - public void DataGridTableStyle_OnRowHeaderWidthChanged_Invoke_CallsRowHeaderWidthChanged(EventArgs eventArgs) - { - var style = new SubDataGridTableStyle(); - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(style, sender); - Assert.Same(eventArgs, e); - callCount++; - }; - - // Call with handler. - style.RowHeaderWidthChanged += handler; - style.OnRowHeaderWidthChanged(eventArgs); - Assert.Equal(1, callCount); - - // Remove handler. - style.RowHeaderWidthChanged -= handler; - style.OnRowHeaderWidthChanged(eventArgs); - Assert.Equal(1, callCount); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetEventArgsTheoryData))] - public void DataGridTableStyle_OnSelectionBackColorChanged_Invoke_CallsSelectionBackColorChanged(EventArgs eventArgs) - { - var style = new SubDataGridTableStyle(); - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(style, sender); - Assert.Same(eventArgs, e); - callCount++; - }; - - // Call with handler. - style.SelectionBackColorChanged += handler; - style.OnSelectionBackColorChanged(eventArgs); - Assert.Equal(1, callCount); - - // Remove handler. - style.SelectionBackColorChanged -= handler; - style.OnSelectionBackColorChanged(eventArgs); - Assert.Equal(1, callCount); - } - - [Theory] - [CommonMemberData(nameof(CommonTestHelper.GetEventArgsTheoryData))] - public void DataGridTableStyle_OnSelectionForeColorChanged_Invoke_CallsSelectionForeColorChanged(EventArgs eventArgs) - { - var style = new SubDataGridTableStyle(); - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(style, sender); - Assert.Same(eventArgs, e); - callCount++; - }; - - // Call with handler. - style.SelectionForeColorChanged += handler; - style.OnSelectionForeColorChanged(eventArgs); - Assert.Equal(1, callCount); - - // Remove handler. - style.SelectionForeColorChanged -= handler; - style.OnSelectionForeColorChanged(eventArgs); - Assert.Equal(1, callCount); - } - - [Fact] - public void DataGridTableStyle_ResetAlternatingBackColor_Invoke_GetReturnsExpected() - { - var style = new DataGridTableStyle(); - - // Reset default. - style.ResetAlternatingBackColor(); - Assert.Equal(SystemColors.Window, style.AlternatingBackColor); - - // Reset custom. - style.AlternatingBackColor = Color.Red; - Assert.Equal(Color.Red, style.AlternatingBackColor); - style.ResetAlternatingBackColor(); - Assert.Equal(SystemColors.Window, style.AlternatingBackColor); - } - - [Fact] - public void DataGridTableStyle_ResetAlternatingBackColor_InvokeWithDataGrid_CallsInvalidate() - { - var dataGrid = new DataGrid(); - var style = new DataGridTableStyle - { - DataGrid = dataGrid - }; - int invalidatedCallCount = 0; - dataGrid.Invalidated += (sender, e) => invalidatedCallCount++; - Assert.NotEqual(IntPtr.Zero, dataGrid.Handle); - - // Reset default. - style.ResetAlternatingBackColor(); - Assert.Equal(SystemColors.Window, style.AlternatingBackColor); - Assert.Equal(0, invalidatedCallCount); - - // Reset custom. - style.AlternatingBackColor = Color.Red; - Assert.Equal(Color.Red, style.AlternatingBackColor); - Assert.Equal(1, invalidatedCallCount); - style.ResetAlternatingBackColor(); - Assert.Equal(SystemColors.Window, style.AlternatingBackColor); - Assert.Equal(3, invalidatedCallCount); - } - - [Fact] - public void DataGridTableStyle_ResetAlternatingBackColor_InvokeWithHandler_CallsAlternatingBackColorChanged() - { - var style = new DataGridTableStyle(); - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(sender, sender); - Assert.Same(EventArgs.Empty, e); - callCount++; - }; - style.AlternatingBackColorChanged += handler; - - // Reset default. - style.ResetAlternatingBackColor(); - Assert.Equal(SystemColors.Window, style.AlternatingBackColor); - Assert.Equal(0, callCount); - - // Reset custom. - style.AlternatingBackColor = Color.Red; - Assert.Equal(Color.Red, style.AlternatingBackColor); - Assert.Equal(1, callCount); - style.ResetAlternatingBackColor(); - Assert.Equal(SystemColors.Window, style.AlternatingBackColor); - Assert.Equal(2, callCount); - } - - [Fact] - public void DataGridTableStyle_ResetBackColor_Invoke_GetReturnsExpected() - { - var style = new DataGridTableStyle(); - - // Reset default. - style.ResetBackColor(); - Assert.Equal(SystemColors.Window, style.BackColor); - - // Reset custom. - style.BackColor = Color.Red; - Assert.Equal(Color.Red, style.BackColor); - style.ResetBackColor(); - Assert.Equal(SystemColors.Window, style.BackColor); - } - - [Fact] - public void DataGridTableStyle_ResetBackColor_InvokeWithDataGrid_CallsInvalidate() - { - var dataGrid = new DataGrid(); - var style = new DataGridTableStyle - { - DataGrid = dataGrid - }; - int invalidatedCallCount = 0; - dataGrid.Invalidated += (sender, e) => invalidatedCallCount++; - Assert.NotEqual(IntPtr.Zero, dataGrid.Handle); - - // Reset default. - style.ResetBackColor(); - Assert.Equal(SystemColors.Window, style.BackColor); - Assert.Equal(0, invalidatedCallCount); - - // Reset custom. - style.BackColor = Color.Red; - Assert.Equal(Color.Red, style.BackColor); - Assert.Equal(1, invalidatedCallCount); - style.ResetBackColor(); - Assert.Equal(SystemColors.Window, style.BackColor); - Assert.Equal(2, invalidatedCallCount); - } - - [Fact] - public void DataGridTableStyle_ResetBackColor_InvokeWithHandler_CallsBackColorChanged() - { - var style = new DataGridTableStyle(); - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(sender, sender); - Assert.Same(EventArgs.Empty, e); - callCount++; - }; - style.BackColorChanged += handler; - - // Reset default. - style.ResetBackColor(); - Assert.Equal(SystemColors.Window, style.BackColor); - Assert.Equal(0, callCount); - - // Reset custom. - style.BackColor = Color.Red; - Assert.Equal(Color.Red, style.BackColor); - Assert.Equal(1, callCount); - style.ResetBackColor(); - Assert.Equal(SystemColors.Window, style.BackColor); - Assert.Equal(2, callCount); - } - - [Fact] - public void DataGridTableStyle_ResetForeColor_Invoke_GetReturnsExpected() - { - var style = new DataGridTableStyle(); - - // Reset default. - style.ResetForeColor(); - Assert.Equal(SystemColors.WindowText, style.ForeColor); - - // Reset custom. - style.ForeColor = Color.Red; - Assert.Equal(Color.Red, style.ForeColor); - style.ResetForeColor(); - Assert.Equal(SystemColors.WindowText, style.ForeColor); - } - - [Fact] - public void DataGridTableStyle_ResetForeColor_InvokeWithDataGrid_CallsInvalidate() - { - var dataGrid = new DataGrid(); - var style = new DataGridTableStyle - { - DataGrid = dataGrid - }; - int invalidatedCallCount = 0; - dataGrid.Invalidated += (sender, e) => invalidatedCallCount++; - Assert.NotEqual(IntPtr.Zero, dataGrid.Handle); - - // Reset default. - style.ResetForeColor(); - Assert.Equal(SystemColors.WindowText, style.ForeColor); - Assert.Equal(0, invalidatedCallCount); - - // Reset custom. - style.ForeColor = Color.Red; - Assert.Equal(Color.Red, style.ForeColor); - Assert.Equal(1, invalidatedCallCount); - style.ResetForeColor(); - Assert.Equal(SystemColors.WindowText, style.ForeColor); - Assert.Equal(2, invalidatedCallCount); - } - - [Fact] - public void DataGridTableStyle_ResetForeColor_InvokeWithHandler_CallsForeColorChanged() - { - var style = new DataGridTableStyle(); - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(sender, sender); - Assert.Same(EventArgs.Empty, e); - callCount++; - }; - style.ForeColorChanged += handler; - - // Reset default. - style.ResetForeColor(); - Assert.Equal(SystemColors.WindowText, style.ForeColor); - Assert.Equal(0, callCount); - - // Reset custom. - style.ForeColor = Color.Red; - Assert.Equal(Color.Red, style.ForeColor); - Assert.Equal(1, callCount); - style.ResetForeColor(); - Assert.Equal(SystemColors.WindowText, style.ForeColor); - Assert.Equal(2, callCount); - } - - [Fact] - public void DataGridTableStyle_ResetHeaderBackColor_Invoke_GetReturnsExpected() - { - var style = new DataGridTableStyle(); - - // Reset default. - style.ResetHeaderBackColor(); - Assert.Equal(SystemColors.Control, style.HeaderBackColor); - - // Reset custom. - style.HeaderBackColor = Color.Red; - Assert.Equal(Color.Red, style.HeaderBackColor); - style.ResetHeaderBackColor(); - Assert.Equal(SystemColors.Control, style.HeaderBackColor); - } - - [Fact] - public void DataGridTableStyle_ResetHeaderBackColor_InvokeWithDataGrid_DoesNotCallInvalidate() - { - var dataGrid = new DataGrid(); - var style = new DataGridTableStyle - { - DataGrid = dataGrid - }; - int invalidatedCallCount = 0; - dataGrid.Invalidated += (sender, e) => invalidatedCallCount++; - Assert.NotEqual(IntPtr.Zero, dataGrid.Handle); - - // Reset default. - style.ResetHeaderBackColor(); - Assert.Equal(SystemColors.Control, style.HeaderBackColor); - Assert.Equal(0, invalidatedCallCount); - - // Reset custom. - style.HeaderBackColor = Color.Red; - Assert.Equal(Color.Red, style.HeaderBackColor); - Assert.Equal(0, invalidatedCallCount); - style.ResetHeaderBackColor(); - Assert.Equal(SystemColors.Control, style.HeaderBackColor); - Assert.Equal(0, invalidatedCallCount); - } - - [Fact] - public void DataGridTableStyle_ResetHeaderBackColor_InvokeWithHandler_CallsHeaderBackColorChanged() - { - var style = new DataGridTableStyle(); - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(sender, sender); - Assert.Same(EventArgs.Empty, e); - callCount++; - }; - style.HeaderBackColorChanged += handler; - - // Reset default. - style.ResetHeaderBackColor(); - Assert.Equal(SystemColors.Control, style.HeaderBackColor); - Assert.Equal(0, callCount); - - // Reset custom. - style.HeaderBackColor = Color.Red; - Assert.Equal(Color.Red, style.HeaderBackColor); - Assert.Equal(1, callCount); - style.ResetHeaderBackColor(); - Assert.Equal(SystemColors.Control, style.HeaderBackColor); - Assert.Equal(2, callCount); - } - - [Fact] - public void DataGridTableStyle_ResetHeaderFont_Invoke_GetReturnsExpected() - { - var style = new DataGridTableStyle(); - var font = new Font(SystemFonts.MessageBoxFont.FontFamily, 10); - - // Reset default. - style.ResetHeaderFont(); - Assert.Same(Control.DefaultFont, style.HeaderFont); - - // Reset custom. - style.HeaderFont = font; - Assert.Same(font, style.HeaderFont); - style.ResetHeaderFont(); - Assert.Same(Control.DefaultFont, style.HeaderFont); - } - - [Fact] - public void DataGridTableStyle_ResetHeaderFont_InvokeWithDataGrid_DoesNotCallInvalidate() - { - var font1 = new Font(SystemFonts.MessageBoxFont.FontFamily, 10); - var font2 = new Font(SystemFonts.MessageBoxFont.FontFamily, 11); - var dataGrid = new DataGrid - { - Font = font1 - }; - var style = new DataGridTableStyle - { - DataGrid = dataGrid - }; - int invalidatedCallCount = 0; - dataGrid.Invalidated += (sender, e) => invalidatedCallCount++; - Assert.NotEqual(IntPtr.Zero, dataGrid.Handle); - - // Reset default. - style.ResetHeaderFont(); - Assert.Same(font1, style.HeaderFont); - Assert.Equal(0, invalidatedCallCount); - - // Reset custom. - style.HeaderFont = font2; - Assert.Same(font2, style.HeaderFont); - Assert.Equal(0, invalidatedCallCount); - style.ResetHeaderFont(); - Assert.Same(font1, style.HeaderFont); - Assert.Equal(0, invalidatedCallCount); - } - - [Fact] - public void DataGridTableStyle_ResetHeaderFont_InvokeWithHandler_CallsHeaderFontChanged() - { - var style = new DataGridTableStyle(); - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(sender, sender); - Assert.Same(EventArgs.Empty, e); - callCount++; - }; - style.HeaderFontChanged += handler; - var font = new Font(SystemFonts.MessageBoxFont.FontFamily, 10); - - // Reset default. - style.ResetHeaderFont(); - Assert.Same(Control.DefaultFont, style.HeaderFont); - Assert.Equal(0, callCount); - - // Reset custom. - style.HeaderFont = font; - Assert.Same(font, style.HeaderFont); - Assert.Equal(1, callCount); - style.ResetHeaderFont(); - Assert.Same(Control.DefaultFont, style.HeaderFont); - Assert.Equal(2, callCount); - } - - [Fact] - public void DataGridTableStyle_ResetHeaderForeColor_Invoke_GetReturnsExpected() - { - var style = new DataGridTableStyle(); - - // Reset default. - style.ResetHeaderForeColor(); - Assert.Equal(SystemColors.ControlText, style.HeaderForeColor); - - // Reset custom. - style.HeaderForeColor = Color.Red; - Assert.Equal(Color.Red, style.HeaderForeColor); - style.ResetHeaderForeColor(); - Assert.Equal(SystemColors.ControlText, style.HeaderForeColor); - } - - [Fact] - public void DataGridTableStyle_ResetHeaderForeColor_InvokeWithDataGrid_DoesNotCallInvalidate() - { - var dataGrid = new DataGrid(); - var style = new DataGridTableStyle - { - DataGrid = dataGrid - }; - int invalidatedCallCount = 0; - dataGrid.Invalidated += (sender, e) => invalidatedCallCount++; - Assert.NotEqual(IntPtr.Zero, dataGrid.Handle); - - // Reset default. - style.ResetHeaderForeColor(); - Assert.Equal(SystemColors.ControlText, style.HeaderForeColor); - Assert.Equal(0, invalidatedCallCount); - - // Reset custom. - style.HeaderForeColor = Color.Red; - Assert.Equal(Color.Red, style.HeaderForeColor); - Assert.Equal(0, invalidatedCallCount); - style.ResetHeaderForeColor(); - Assert.Equal(SystemColors.ControlText, style.HeaderForeColor); - Assert.Equal(0, invalidatedCallCount); - } - - [Fact] - public void DataGridTableStyle_ResetHeaderForeColor_InvokeWithHandler_CallsHeaderForeColorChanged() - { - var style = new DataGridTableStyle(); - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(sender, sender); - Assert.Same(EventArgs.Empty, e); - callCount++; - }; - style.HeaderForeColorChanged += handler; - - // Reset default. - style.ResetHeaderForeColor(); - Assert.Equal(SystemColors.ControlText, style.HeaderForeColor); - Assert.Equal(0, callCount); - - // Reset custom. - style.HeaderForeColor = Color.Red; - Assert.Equal(Color.Red, style.HeaderForeColor); - Assert.Equal(1, callCount); - style.ResetHeaderForeColor(); - Assert.Equal(SystemColors.ControlText, style.HeaderForeColor); - Assert.Equal(2, callCount); - } - - [Fact] - public void DataGridTableStyle_ResetLinkColor_Invoke_GetReturnsExpected() - { - var style = new DataGridTableStyle(); - - // Reset default. - style.ResetLinkColor(); - Assert.Equal(SystemColors.HotTrack, style.LinkColor); - Assert.Equal(SystemColors.HotTrack, style.LinkHoverColor); - - // Reset custom. - style.LinkColor = Color.Red; - Assert.Equal(Color.Red, style.LinkColor); - Assert.Equal(Color.Red, style.LinkHoverColor); - style.ResetLinkColor(); - Assert.Equal(SystemColors.HotTrack, style.LinkColor); - Assert.Equal(SystemColors.HotTrack, style.LinkHoverColor); - } - - [Fact] - public void DataGridTableStyle_ResetLinkColor_InvokeWithDataGrid_DoesNotCallInvalidate() - { - var dataGrid = new DataGrid(); - var style = new DataGridTableStyle - { - DataGrid = dataGrid - }; - int invalidatedCallCount = 0; - dataGrid.Invalidated += (sender, e) => invalidatedCallCount++; - Assert.NotEqual(IntPtr.Zero, dataGrid.Handle); - - // Reset default. - style.ResetLinkColor(); - Assert.Equal(SystemColors.HotTrack, style.LinkColor); - Assert.Equal(SystemColors.HotTrack, style.LinkHoverColor); - Assert.Equal(0, invalidatedCallCount); - - // Reset custom. - style.LinkColor = Color.Red; - Assert.Equal(Color.Red, style.LinkColor); - Assert.Equal(Color.Red, style.LinkHoverColor); - Assert.Equal(0, invalidatedCallCount); - style.ResetLinkColor(); - Assert.Equal(SystemColors.HotTrack, style.LinkColor); - Assert.Equal(SystemColors.HotTrack, style.LinkHoverColor); - Assert.Equal(0, invalidatedCallCount); - } - - [Fact] - public void DataGridTableStyle_ResetLinkColor_InvokeWithHandler_CallsLinkColorChanged() - { - var style = new DataGridTableStyle(); - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(sender, sender); - Assert.Same(EventArgs.Empty, e); - callCount++; - }; - style.LinkColorChanged += handler; - - // Reset default. - style.ResetLinkColor(); - Assert.Equal(SystemColors.HotTrack, style.LinkColor); - Assert.Equal(SystemColors.HotTrack, style.LinkHoverColor); - Assert.Equal(0, callCount); - - // Reset custom. - style.LinkColor = Color.Red; - Assert.Equal(Color.Red, style.LinkColor); - Assert.Equal(1, callCount); - style.ResetLinkColor(); - Assert.Equal(SystemColors.HotTrack, style.LinkColor); - Assert.Equal(SystemColors.HotTrack, style.LinkHoverColor); - Assert.Equal(2, callCount); - } - - [Fact] - public void DataGridTableStyle_ResetLinkHoverColor_Invoke_Nop() - { - var style = new DataGridTableStyle(); - - // Reset default. - style.ResetLinkHoverColor(); - Assert.Equal(SystemColors.HotTrack, style.LinkColor); - Assert.Equal(SystemColors.HotTrack, style.LinkHoverColor); - - // Reset custom. - style.LinkColor = Color.Red; - Assert.Equal(Color.Red, style.LinkColor); - Assert.Equal(Color.Red, style.LinkHoverColor); - style.ResetLinkHoverColor(); - Assert.Equal(Color.Red, style.LinkColor); - Assert.Equal(Color.Red, style.LinkHoverColor); - } - - [Fact] - public void DataGridTableStyle_ResetLinkHoverColor_InvokeWithDataGrid_Nop() - { - var dataGrid = new DataGrid(); - var style = new DataGridTableStyle - { - DataGrid = dataGrid - }; - int invalidatedCallCount = 0; - dataGrid.Invalidated += (sender, e) => invalidatedCallCount++; - Assert.NotEqual(IntPtr.Zero, dataGrid.Handle); - - // Reset default. - style.ResetLinkHoverColor(); - Assert.Equal(SystemColors.HotTrack, style.LinkColor); - Assert.Equal(SystemColors.HotTrack, style.LinkHoverColor); - Assert.Equal(0, invalidatedCallCount); - - // Reset custom. - style.LinkColor = Color.Red; - Assert.Equal(Color.Red, style.LinkColor); - Assert.Equal(Color.Red, style.LinkHoverColor); - Assert.Equal(0, invalidatedCallCount); - style.ResetLinkHoverColor(); - Assert.Equal(Color.Red, style.LinkColor); - Assert.Equal(Color.Red, style.LinkHoverColor); - Assert.Equal(0, invalidatedCallCount); - } - - [Fact] - public void DataGridTableStyle_ResetLinkHoverColor_InvokeWithHandler_DoesNotCallLinkColorChanged() - { - var style = new DataGridTableStyle(); - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(sender, sender); - Assert.Same(EventArgs.Empty, e); - callCount++; - }; - style.LinkColorChanged += handler; - - // Reset default. - style.ResetLinkHoverColor(); - Assert.Equal(SystemColors.HotTrack, style.LinkColor); - Assert.Equal(SystemColors.HotTrack, style.LinkHoverColor); - Assert.Equal(0, callCount); - - // Reset custom. - style.LinkColor = Color.Red; - Assert.Equal(Color.Red, style.LinkColor); - Assert.Equal(Color.Red, style.LinkHoverColor); - Assert.Equal(1, callCount); - style.ResetLinkHoverColor(); - Assert.Equal(Color.Red, style.LinkColor); - Assert.Equal(Color.Red, style.LinkHoverColor); - Assert.Equal(1, callCount); - } - - [Fact] - public void DataGridTableStyle_ResetPreferredRowHeight_Invoke_GetReturnsExpected() - { - var style = new DataGridTableStyle(); - PropertyDescriptor property = TypeDescriptor.GetProperties(typeof(DataGridTableStyle))[nameof(DataGridTableStyle.PreferredRowHeight)]; - - // Reset default. - Assert.False(property.CanResetValue(style)); - property.ResetValue(style); - Assert.Equal(Control.DefaultFont.Height + 3, style.PreferredRowHeight); - - // Reset custom. - style.PreferredRowHeight = 1; - Assert.Equal(1, style.PreferredRowHeight); - Assert.True(property.CanResetValue(style)); - property.ResetValue(style); - Assert.Equal(Control.DefaultFont.Height + 3, style.PreferredRowHeight); - } - - [Fact] - public void DataGridTableStyle_ResetPreferredRowHeight_InvokeWithDataGrid_DoesNotCallInvalidate() - { - var dataGrid = new DataGrid(); - PropertyDescriptor property = TypeDescriptor.GetProperties(typeof(DataGridTableStyle))[nameof(DataGridTableStyle.PreferredRowHeight)]; - var style = new DataGridTableStyle - { - DataGrid = dataGrid - }; - int invalidatedCallCount = 0; - dataGrid.Invalidated += (sender, e) => invalidatedCallCount++; - Assert.NotEqual(IntPtr.Zero, dataGrid.Handle); - - // Reset default. - Assert.False(property.CanResetValue(style)); - property.ResetValue(style); - Assert.Equal(Control.DefaultFont.Height + 3, style.PreferredRowHeight); - Assert.Equal(0, invalidatedCallCount); - - // Reset custom. - style.PreferredRowHeight = 1; - Assert.Equal(1, style.PreferredRowHeight); - Assert.Equal(0, invalidatedCallCount); - Assert.True(property.CanResetValue(style)); - property.ResetValue(style); - Assert.Equal(Control.DefaultFont.Height + 3, style.PreferredRowHeight); - Assert.Equal(0, invalidatedCallCount); - } - - [Fact] - public void DataGridTableStyle_ResetPreferredRowHeight_InvokeWithHandler_CallsPreferredRowHeightChanged() - { - var style = new DataGridTableStyle(); - PropertyDescriptor property = TypeDescriptor.GetProperties(typeof(DataGridTableStyle))[nameof(DataGridTableStyle.PreferredRowHeight)]; - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(sender, sender); - Assert.Same(EventArgs.Empty, e); - callCount++; - }; - style.PreferredRowHeightChanged += handler; - - // Reset default. - Assert.False(property.CanResetValue(style)); - property.ResetValue(style); - Assert.Equal(Control.DefaultFont.Height + 3, style.PreferredRowHeight); - Assert.Equal(0, callCount); - - // Reset custom. - style.PreferredRowHeight = 1; - Assert.Equal(1, style.PreferredRowHeight); - Assert.Equal(1, callCount); - Assert.True(property.CanResetValue(style)); - property.ResetValue(style); - Assert.Equal(Control.DefaultFont.Height + 3, style.PreferredRowHeight); - Assert.Equal(2, callCount); - } - - [Fact] - public void DataGridTableStyle_ResetSelectionBackColor_Invoke_GetReturnsExpected() - { - var style = new DataGridTableStyle(); - - // Reset default. - style.ResetSelectionBackColor(); - Assert.Equal(SystemColors.ActiveCaption, style.SelectionBackColor); - - // Reset custom. - style.SelectionBackColor = Color.Red; - Assert.Equal(Color.Red, style.SelectionBackColor); - style.ResetSelectionBackColor(); - Assert.Equal(SystemColors.ActiveCaption, style.SelectionBackColor); - } - - [Fact] - public void DataGridTableStyle_ResetSelectionBackColor_InvokeWithDataGrid_CallsInvalidate() - { - var dataGrid = new DataGrid(); - var style = new DataGridTableStyle - { - DataGrid = dataGrid - }; - int invalidatedCallCount = 0; - dataGrid.Invalidated += (sender, e) => invalidatedCallCount++; - Assert.NotEqual(IntPtr.Zero, dataGrid.Handle); - - // Reset default. - style.ResetSelectionBackColor(); - Assert.Equal(SystemColors.ActiveCaption, style.SelectionBackColor); - Assert.Equal(0, invalidatedCallCount); - - // Reset custom. - style.SelectionBackColor = Color.Red; - Assert.Equal(Color.Red, style.SelectionBackColor); - Assert.Equal(1, invalidatedCallCount); - style.ResetSelectionBackColor(); - Assert.Equal(SystemColors.ActiveCaption, style.SelectionBackColor); - Assert.Equal(2, invalidatedCallCount); - } - - [Fact] - public void DataGridTableStyle_ResetSelectionBackColor_InvokeWithHandler_CallsSelectionBackColorChanged() - { - var style = new DataGridTableStyle(); - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(sender, sender); - Assert.Same(EventArgs.Empty, e); - callCount++; - }; - style.SelectionBackColorChanged += handler; - - // Reset default. - style.ResetSelectionBackColor(); - Assert.Equal(SystemColors.ActiveCaption, style.SelectionBackColor); - Assert.Equal(0, callCount); - - // Reset custom. - style.SelectionBackColor = Color.Red; - Assert.Equal(Color.Red, style.SelectionBackColor); - Assert.Equal(1, callCount); - style.ResetSelectionBackColor(); - Assert.Equal(SystemColors.ActiveCaption, style.SelectionBackColor); - Assert.Equal(2, callCount); - } - - [Fact] - public void DataGridTableStyle_ResetSelectionForeColor_Invoke_GetReturnsExpected() - { - var style = new DataGridTableStyle(); - - // Reset default. - style.ResetSelectionForeColor(); - Assert.Equal(SystemColors.ActiveCaptionText, style.SelectionForeColor); - - // Reset custom. - style.SelectionForeColor = Color.Red; - Assert.Equal(Color.Red, style.SelectionForeColor); - style.ResetSelectionForeColor(); - Assert.Equal(SystemColors.ActiveCaptionText, style.SelectionForeColor); - } - - [Fact] - public void DataGridTableStyle_ResetSelectionForeColor_InvokeWithDataGrid_CallsInvalidate() - { - var dataGrid = new DataGrid(); - var style = new DataGridTableStyle - { - DataGrid = dataGrid - }; - int invalidatedCallCount = 0; - dataGrid.Invalidated += (sender, e) => invalidatedCallCount++; - Assert.NotEqual(IntPtr.Zero, dataGrid.Handle); - - // Reset default. - style.ResetSelectionForeColor(); - Assert.Equal(SystemColors.ActiveCaptionText, style.SelectionForeColor); - Assert.Equal(0, invalidatedCallCount); - - // Reset custom. - style.SelectionForeColor = Color.Red; - Assert.Equal(Color.Red, style.SelectionForeColor); - Assert.Equal(1, invalidatedCallCount); - style.ResetSelectionForeColor(); - Assert.Equal(SystemColors.ActiveCaptionText, style.SelectionForeColor); - Assert.Equal(2, invalidatedCallCount); - } - - [Fact] - public void DataGridTableStyle_ResetSelectionForeColor_InvokeWithHandler_CallsSelectionForeColorChanged() - { - var style = new DataGridTableStyle(); - int callCount = 0; - EventHandler handler = (sender, e) => - { - Assert.Same(sender, sender); - Assert.Same(EventArgs.Empty, e); - callCount++; - }; - style.SelectionForeColorChanged += handler; - - // Reset default. - style.ResetSelectionForeColor(); - Assert.Equal(SystemColors.ActiveCaptionText, style.SelectionForeColor); - Assert.Equal(0, callCount); - - // Reset custom. - style.SelectionForeColor = Color.Red; - Assert.Equal(Color.Red, style.SelectionForeColor); - Assert.Equal(1, callCount); - style.ResetSelectionForeColor(); - Assert.Equal(SystemColors.ActiveCaptionText, style.SelectionForeColor); - Assert.Equal(2, callCount); - } - - [Fact] - public void DataGridTableStyle_ShouldSerializeAlternatingBackColor_Invoke_ReturnsExpected() - { - var style = new SubDataGridTableStyle(); - Assert.False(style.ShouldSerializeAlternatingBackColor()); - - style.AlternatingBackColor = Color.Red; - Assert.Equal(Color.Red, style.AlternatingBackColor); - Assert.True(style.ShouldSerializeAlternatingBackColor()); - } - - [Fact] - public void DataGridTableStyle_ShouldSerializeBackColor_Invoke_ReturnsExpected() - { - var style = new SubDataGridTableStyle(); - Assert.False(style.ShouldSerializeBackColor()); - - style.BackColor = Color.Red; - Assert.Equal(Color.Red, style.BackColor); - Assert.True(style.ShouldSerializeBackColor()); - } - - [Fact] - public void DataGridTableStyle_ShouldSerializeForeColor_Invoke_ReturnsExpected() - { - var style = new SubDataGridTableStyle(); - Assert.False(style.ShouldSerializeForeColor()); - - style.ForeColor = Color.Red; - Assert.Equal(Color.Red, style.ForeColor); - Assert.True(style.ShouldSerializeForeColor()); - } - - [Fact] - public void DataGridTableStyle_ShouldSerializeGridLineColor_Invoke_ReturnsExpected() - { - var style = new SubDataGridTableStyle(); - Assert.False(style.ShouldSerializeGridLineColor()); - - style.GridLineColor = Color.Red; - Assert.Equal(Color.Red, style.GridLineColor); - Assert.True(style.ShouldSerializeGridLineColor()); - } - - [Fact] - public void DataGridTableStyle_ShouldSerializeHeaderBackColor_Invoke_ReturnsExpected() - { - var style = new SubDataGridTableStyle(); - Assert.False(style.ShouldSerializeHeaderBackColor()); - - style.HeaderBackColor = Color.Red; - Assert.Equal(Color.Red, style.HeaderBackColor); - Assert.True(style.ShouldSerializeHeaderBackColor()); - } - - [Fact] - public void DataGridTableStyle_ShouldSerializeHeaderFont_Invoke_ReturnsExpected() - { - var style = new DataGridTableStyle(); - var font = new Font(SystemFonts.MessageBoxFont.FontFamily, 10); - PropertyDescriptor property = TypeDescriptor.GetProperties(typeof(DataGridTableStyle))[nameof(DataGridTableStyle.HeaderFont)]; - Assert.False(property.ShouldSerializeValue(style)); - - style.HeaderFont = font; - Assert.Same(font, style.HeaderFont); - Assert.True(property.ShouldSerializeValue(style)); - } - - [Fact] - public void DataGridTableStyle_ShouldSerializeHeaderForeColor_Invoke_ReturnsExpected() - { - var style = new SubDataGridTableStyle(); - Assert.True(style.ShouldSerializeHeaderForeColor()); - - style.HeaderForeColor = Color.Red; - Assert.Equal(Color.Red, style.HeaderForeColor); - Assert.True(style.ShouldSerializeHeaderForeColor()); - } - - [Fact] - public void DataGridTableStyle_ShouldSerializeLinkColor_Invoke_ReturnsExpected() - { - var style = new SubDataGridTableStyle(); - Assert.False(style.ShouldSerializeLinkColor()); - - style.LinkColor = Color.Red; - Assert.Equal(Color.Red, style.LinkColor); - Assert.Equal(Color.Red, style.LinkHoverColor); - Assert.True(style.ShouldSerializeLinkColor()); - } - - [Fact] - public void DataGridTableStyle_ShouldSerializeLinkHoverColor_Invoke_ReturnsFalse() - { - var style = new SubDataGridTableStyle(); - Assert.False(style.ShouldSerializeLinkHoverColor()); - - style.LinkColor = Color.Red; - Assert.Equal(Color.Red, style.LinkColor); - Assert.Equal(Color.Red, style.LinkHoverColor); - Assert.False(style.ShouldSerializeLinkHoverColor()); - } - - [Fact] - public void DataGridTableStyle_ShouldShouldSerializePreferredRowHeight_Invoke_ReturnsExpected() - { - var style = new SubDataGridTableStyle(); - Assert.False(style.ShouldSerializePreferredRowHeight()); - - style.PreferredRowHeight = 1; - Assert.Equal(1, style.PreferredRowHeight); - Assert.True(style.ShouldSerializePreferredRowHeight()); - } - - [Fact] - public void DataGridTableStyle_ShouldSerializeSelectionBackColor_Invoke_ReturnsExpected() - { - var style = new SubDataGridTableStyle(); - Assert.False(style.ShouldSerializeSelectionBackColor()); - - style.SelectionBackColor = Color.Red; - Assert.Equal(Color.Red, style.SelectionBackColor); - Assert.True(style.ShouldSerializeSelectionBackColor()); - } - - [Fact] - public void DataGridTableStyle_ShouldSerializeSelectionForeColor_Invoke_ReturnsExpected() - { - var style = new SubDataGridTableStyle(); - Assert.False(style.ShouldSerializeSelectionForeColor()); - - style.SelectionForeColor = Color.Red; - Assert.Equal(Color.Red, style.SelectionForeColor); - Assert.True(style.ShouldSerializeSelectionForeColor()); - } - - private class SubDataGridTableStyle : DataGridTableStyle - { - public SubDataGridTableStyle() : base() - { - } - - public SubDataGridTableStyle(bool isDefaultTableStyle) : base(isDefaultTableStyle) - { - } - - public SubDataGridTableStyle(CurrencyManager listManager) : base(listManager) - { - } - - public new bool CanRaiseEvents => base.CanRaiseEvents; - - public new bool DesignMode => base.DesignMode; - - public new EventHandlerList Events => base.Events; - - public new DataGridColumnStyle CreateGridColumn(PropertyDescriptor prop) => base.CreateGridColumn(prop); - - public new DataGridColumnStyle CreateGridColumn(PropertyDescriptor prop, bool isDefault) => base.CreateGridColumn(prop, isDefault); - - public new void Dispose(bool disposing) => base.Dispose(disposing); - - public new void OnAllowSortingChanged(EventArgs e) => base.OnAllowSortingChanged(e); - - public new void OnAlternatingBackColorChanged(EventArgs e) => base.OnAlternatingBackColorChanged(e); - - public new void OnBackColorChanged(EventArgs e) => base.OnBackColorChanged(e); - - public new void OnColumnHeadersVisibleChanged(EventArgs e) => base.OnColumnHeadersVisibleChanged(e); - - public new void OnForeColorChanged(EventArgs e) => base.OnForeColorChanged(e); - - public new void OnGridLineColorChanged(EventArgs e) => base.OnGridLineColorChanged(e); - - public new void OnGridLineStyleChanged(EventArgs e) => base.OnGridLineStyleChanged(e); - - public new void OnHeaderBackColorChanged(EventArgs e) => base.OnHeaderBackColorChanged(e); - - public new void OnHeaderFontChanged(EventArgs e) => base.OnHeaderFontChanged(e); - - public new void OnHeaderForeColorChanged(EventArgs e) => base.OnHeaderForeColorChanged(e); - - public new void OnLinkColorChanged(EventArgs e) => base.OnLinkColorChanged(e); - - public new void OnLinkHoverColorChanged(EventArgs e) => base.OnLinkHoverColorChanged(e); - - public new void OnMappingNameChanged(EventArgs e) => base.OnMappingNameChanged(e); - - public new void OnPreferredColumnWidthChanged(EventArgs e) => base.OnPreferredColumnWidthChanged(e); - - public new void OnPreferredRowHeightChanged(EventArgs e) => base.OnPreferredRowHeightChanged(e); - - public new void OnReadOnlyChanged(EventArgs e) => base.OnReadOnlyChanged(e); - - public new void OnRowHeadersVisibleChanged(EventArgs e) => base.OnRowHeadersVisibleChanged(e); - - public new void OnRowHeaderWidthChanged(EventArgs e) => base.OnRowHeaderWidthChanged(e); - - public new void OnSelectionBackColorChanged(EventArgs e) => base.OnSelectionBackColorChanged(e); - - public new void OnSelectionForeColorChanged(EventArgs e) => base.OnSelectionForeColorChanged(e); - - public new bool ShouldSerializeAlternatingBackColor() => base.ShouldSerializeAlternatingBackColor(); - - public new bool ShouldSerializeBackColor() => base.ShouldSerializeBackColor(); - - public new bool ShouldSerializeForeColor() => base.ShouldSerializeForeColor(); - - public new bool ShouldSerializeGridLineColor() => base.ShouldSerializeGridLineColor(); - - public new bool ShouldSerializeHeaderBackColor() => base.ShouldSerializeHeaderBackColor(); - - public new bool ShouldSerializeHeaderForeColor() => base.ShouldSerializeHeaderForeColor(); - - public new bool ShouldSerializeLinkColor() => base.ShouldSerializeLinkColor(); - - public new bool ShouldSerializeLinkHoverColor() => base.ShouldSerializeLinkHoverColor(); - - public new bool ShouldSerializePreferredRowHeight() => base.ShouldSerializePreferredRowHeight(); - - public new bool ShouldSerializeSelectionBackColor() => base.ShouldSerializeSelectionBackColor(); - - public new bool ShouldSerializeSelectionForeColor() => base.ShouldSerializeSelectionForeColor(); - } - - private class SubDataGridColumnStyle : DataGridColumnStyle - { - public Action AbortAction { get; set; } - - protected internal override void Abort(int rowNum) - { - AbortAction(rowNum); - } - - public Func CommitAction { get; set; } - - protected internal override bool Commit(CurrencyManager dataSource, int rowNum) - { - return CommitAction(dataSource, rowNum); - } - - public Action EditAction { get; set; } - - protected internal override void Edit(CurrencyManager source, int rowNum, Rectangle bounds, bool readOnly, string displayText, bool cellIsVisible) - { - EditAction(source, rowNum, bounds, readOnly, displayText, cellIsVisible); - } - - protected internal override Size GetPreferredSize(Graphics g, object value) - { - throw new NotImplementedException(); - } - - protected internal override int GetMinimumHeight() - { - throw new NotImplementedException(); - } - - protected internal override int GetPreferredHeight(Graphics g, object value) - { - throw new NotImplementedException(); - } - - protected internal override void Paint(Graphics g, Rectangle bounds, CurrencyManager source, int rowNum) - { - throw new NotImplementedException(); - } - - protected internal override void Paint(Graphics g, Rectangle bounds, CurrencyManager source, int rowNum, bool alignToRight) - { - throw new NotImplementedException(); - } - - public Action SetDataGridInColumnAction { get; set; } - - protected override void SetDataGridInColumn(DataGrid value) - { - if (SetDataGridInColumnAction == null) - { - base.SetDataGridInColumn(value); - } - else - { - SetDataGridInColumnAction(value); - } - } - - public Action DisposeAction { get; set; } - - protected override void Dispose(bool disposing) - { - DisposeAction?.Invoke(disposing); - } - } - - private class NullGridColumnStylesDataGridTableStyle : DataGridTableStyle - { - public override GridColumnStylesCollection GridColumnStyles => null; - - public new void Dispose(bool disposing) => base.Dispose(disposing); - } - - private class SubDataGrid : DataGrid - { - public new void ColumnStartedEditing(Rectangle bounds) => base.ColumnStartedEditing(bounds); - - public new void OnPaint(PaintEventArgs pe) => base.OnPaint(pe); - } - - private class DataClass - { - public string Value1 { get; set; } - - public string Value2 { get; set; } - } - - - private class ClassWithProperties - { - public bool BoolProperty { get; set; } - - public string StringProperty { get; set; } - - public DateTime DateTimeProperty { get; set; } - - public sbyte SByteProperty { get; set; } - - public short ShortProperty { get; set; } - - public int IntProperty { get; set; } - - public long LongProperty { get; set; } - - public byte ByteProperty { get; set; } - - public ushort UShortProperty { get; set; } - - public uint UIntProperty { get; set; } - - public ulong ULongProperty { get; set; } - - public char CharProperty { get; set; } - - public decimal DecimalProperty { get; set; } - - public double DoubleProperty { get; set; } - - public float FloatProperty { get; set; } - - public object ObjectProperty { get; set; } - } - } -} diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridTests.cs deleted file mode 100644 index 79b6b90c7c8..00000000000 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridTests.cs +++ /dev/null @@ -1,145 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.ComponentModel; -using System.Drawing; -using WinForms.Common.Tests; -using Xunit; - -namespace System.Windows.Forms.Tests -{ - public class DataGridTests - { - [Fact] - public void DataGrid_Ctor_Default() - { - var dataGrid = new SubDataGrid(); - Assert.True(dataGrid.AllowNavigation); - Assert.True(dataGrid.AllowSorting); - Assert.Equal(SystemColors.Window, dataGrid.AlternatingBackColor); - Assert.Equal(SystemColors.Window, dataGrid.BackColor); - Assert.Equal(SystemColors.AppWorkspace, dataGrid.BackgroundColor); - Assert.Null(dataGrid.BackgroundImage); - Assert.Equal(ImageLayout.Tile, dataGrid.BackgroundImageLayout); - Assert.Equal(BorderStyle.Fixed3D, dataGrid.BorderStyle); - Assert.Equal(new Rectangle(0, 0, 130, 80), dataGrid.Bounds); - Assert.Equal(80, dataGrid.Bottom); - Assert.Equal(SystemColors.ActiveCaption, dataGrid.CaptionBackColor); - Assert.Equal(Control.DefaultFont.Name, dataGrid.CaptionFont.Name); - Assert.Equal(FontStyle.Bold, dataGrid.CaptionFont.Style); - Assert.Equal(SystemColors.ActiveCaptionText, dataGrid.CaptionForeColor); - Assert.Empty(dataGrid.CaptionText); - Assert.True(dataGrid.CaptionVisible); - Assert.Equal(new Rectangle(0, 0, 130, 80), dataGrid.ClientRectangle); - Assert.Equal(new Size(130, 80), dataGrid.ClientSize); - Assert.True(dataGrid.ColumnHeadersVisible); - Assert.Equal(0, dataGrid.CurrentCell.RowNumber); - Assert.Equal(0, dataGrid.CurrentCell.ColumnNumber); - Assert.Equal(-1, dataGrid.CurrentRowIndex); - Assert.Same(Cursors.Default, dataGrid.Cursor); - Assert.Empty(dataGrid.DataMember); - Assert.Null(dataGrid.DataSource); - Assert.Equal(new Rectangle(0, 0, 130, 80), dataGrid.DisplayRectangle); - Assert.Equal(Size.Empty, dataGrid.DefaultMaximumSize); - Assert.Equal(Size.Empty, dataGrid.DefaultMinimumSize); - Assert.Equal(Padding.Empty, dataGrid.DefaultPadding); - Assert.Equal(new Size(130, 80), dataGrid.DefaultSize); - Assert.Equal(0, dataGrid.FirstVisibleColumn); - Assert.False(dataGrid.FlatMode); - Assert.Equal(SystemColors.WindowText, dataGrid.ForeColor); - Assert.Equal(SystemColors.Control, dataGrid.GridLineColor); - Assert.Equal(DataGridLineStyle.Solid, dataGrid.GridLineStyle); - Assert.Equal(SystemColors.Control, dataGrid.HeaderBackColor); - Assert.Same(Control.DefaultFont, dataGrid.HeaderFont); - Assert.Equal(SystemColors.ControlText, dataGrid.HeaderForeColor); - Assert.Equal(SystemColors.ControlText, dataGrid.HeaderForeColor); - Assert.Equal(80, dataGrid.Height); - Assert.NotNull(dataGrid.HorizScrollBar); - Assert.Same(dataGrid.HorizScrollBar, dataGrid.HorizScrollBar); - Assert.Equal(0, dataGrid.Left); - Assert.Equal(SystemColors.HotTrack, dataGrid.LinkColor); - Assert.Equal(SystemColors.HotTrack, dataGrid.LinkHoverColor); - Assert.Null(dataGrid.ListManager); - Assert.Equal(Point.Empty, dataGrid.Location); - Assert.Equal(new Padding(3, 3, 3, 3), dataGrid.Margin); - Assert.Equal(Size.Empty, dataGrid.MaximumSize); - Assert.Equal(Size.Empty, dataGrid.MinimumSize); - Assert.Equal(Padding.Empty, dataGrid.Padding); - Assert.Equal(SystemColors.Control, dataGrid.ParentRowsBackColor); - Assert.Equal(SystemColors.WindowText, dataGrid.ParentRowsForeColor); - Assert.Equal(DataGridParentRowsLabelStyle.Both, dataGrid.ParentRowsLabelStyle); - Assert.True(dataGrid.ParentRowsVisible); - Assert.Equal(75, dataGrid.PreferredColumnWidth); - Assert.Equal(Control.DefaultFont.Height + 3, dataGrid.PreferredRowHeight); - Assert.Equal(new Size(130, 80), dataGrid.PreferredSize); - Assert.False(dataGrid.ReadOnly); - Assert.True(dataGrid.RowHeadersVisible); - Assert.Equal(35, dataGrid.RowHeaderWidth); - Assert.Equal(SystemColors.ActiveCaption, dataGrid.SelectionBackColor); - Assert.Equal(SystemColors.ActiveCaptionText, dataGrid.SelectionForeColor); - Assert.Null(dataGrid.Site); - Assert.Equal(new Size(130, 80), dataGrid.Size); - Assert.Empty(dataGrid.TableStyles); - Assert.Same(dataGrid.TableStyles, dataGrid.TableStyles); - Assert.Empty(dataGrid.Text); - Assert.Equal(0, dataGrid.Top); - Assert.NotNull(dataGrid.VertScrollBar); - Assert.Same(dataGrid.VertScrollBar, dataGrid.VertScrollBar); - Assert.Equal(0, dataGrid.VisibleColumnCount); - Assert.Equal(0, dataGrid.VisibleRowCount); - Assert.Equal(130, dataGrid.Width); - } - - [Fact] - public void DataGrid_ColumnStartedEditing_ValidControl_Success() - { - var dataGrid = new DataGrid(); - var control = new Control(); - dataGrid.ColumnStartedEditing(control); - } - - [Fact] - public void DataGrid_ColumnStartedEditing_NullControl_Nop() - { - var dataGrid = new DataGrid(); - dataGrid.ColumnStartedEditing(null); - } - - private class SubDataGridTableStyle : DataGridTableStyle - { - public SubDataGridTableStyle() : base() - { - } - - public SubDataGridTableStyle(bool isDefaultTableStyle) : base(isDefaultTableStyle) - { - } - - public SubDataGridTableStyle(CurrencyManager listManager) : base(listManager) - { - } - - public new bool CanRaiseEvents => base.CanRaiseEvents; - - public new bool DesignMode => base.DesignMode; - - public new EventHandlerList Events => base.Events; - } - - private class SubDataGrid : DataGrid - { - public new Size DefaultMaximumSize => base.DefaultMaximumSize; - - public new Size DefaultMinimumSize => base.DefaultMinimumSize; - - public new Padding DefaultPadding => base.DefaultPadding; - - public new Size DefaultSize => base.DefaultSize; - - public new ScrollBar HorizScrollBar => base.HorizScrollBar; - - public new ScrollBar VertScrollBar => base.VertScrollBar; - } - } -} diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ErrorProviderTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ErrorProviderTests.cs index fec31a3afd6..6b3d72d9714 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ErrorProviderTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ErrorProviderTests.cs @@ -836,7 +836,6 @@ public static IEnumerable CanExtend_TestData() yield return new object[] { null, false }; yield return new object[] { new object(), false }; yield return new object[] { new Component(), false }; - yield return new object[] { new ToolBar(), false }; yield return new object[] { new Form(), false }; yield return new object[] { new Control(), true }; } diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/GridColumnStylesCollectionTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/GridColumnStylesCollectionTests.cs deleted file mode 100644 index 3631f332c1f..00000000000 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/GridColumnStylesCollectionTests.cs +++ /dev/null @@ -1,66 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Drawing; -using Xunit; - -namespace System.Windows.Forms.Tests -{ - public class GridColumnStylesCollectionTests - { - [Fact] - public void GridColumnStylesCollection_Add_DataGridColumnStyle_Success() - { - var tableStyle = new DataGridTableStyle(); - GridColumnStylesCollection collection = tableStyle.GridColumnStyles; - var style = new SubDataGridColumnStyle(); - Assert.Equal(0, collection.Add(style)); - Assert.Same(style, Assert.Single(collection)); - Assert.Same(tableStyle, style.DataGridTableStyle); - } - - private class SubDataGridColumnStyle : DataGridColumnStyle - { - protected internal override void Abort(int rowNum) - { - throw new NotImplementedException(); - } - - protected internal override bool Commit(CurrencyManager dataSource, int rowNum) - { - throw new NotImplementedException(); - } - - protected internal override void Edit(CurrencyManager source, int rowNum, Rectangle bounds, bool readOnly, string displayText, bool cellIsVisible) - { - throw new NotImplementedException(); - } - - protected internal override Size GetPreferredSize(Graphics g, object value) - { - throw new NotImplementedException(); - } - - protected internal override int GetMinimumHeight() - { - throw new NotImplementedException(); - } - - protected internal override int GetPreferredHeight(Graphics g, object value) - { - throw new NotImplementedException(); - } - - protected internal override void Paint(Graphics g, Rectangle bounds, CurrencyManager source, int rowNum) - { - throw new NotImplementedException(); - } - - protected internal override void Paint(Graphics g, Rectangle bounds, CurrencyManager source, int rowNum, bool alignToRight) - { - throw new NotImplementedException(); - } - } - } -} diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/GridTableStylesCollectionTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/GridTableStylesCollectionTests.cs deleted file mode 100644 index 8bce55296b5..00000000000 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/GridTableStylesCollectionTests.cs +++ /dev/null @@ -1,22 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using Xunit; - -namespace System.Windows.Forms.Tests -{ - public class GridTableStylesCollectionTests - { - [Fact] - public void GridTableStylesCollection_Add_DataGridTableStyle_Success() - { - var dataGrid = new DataGrid(); - GridTableStylesCollection collection = dataGrid.TableStyles; - var style = new DataGridTableStyle(); - Assert.Equal(0, collection.Add(style)); - Assert.Same(style, Assert.Single(collection)); - Assert.Same(dataGrid, style.DataGrid); - } - } -} diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/GridTablesFactoryTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/GridTablesFactoryTests.cs deleted file mode 100644 index 5b34cf2bc30..00000000000 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/GridTablesFactoryTests.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Collections.Generic; -using System.Drawing; -using Xunit; - -namespace System.Windows.Forms.Tests -{ - public class GridTablesFactoryTests - { - public static IEnumerable CreateGridTables_TestData() - { - yield return new object[] { null, null, null, null, new DataGridTableStyle[] { null } }; - var style = new DataGridTableStyle(); - yield return new object[] { style, new object(), string.Empty, new BindingContext(), new DataGridTableStyle[] { style } }; - yield return new object[] { style, new object(), "dataMember", new BindingContext(), new DataGridTableStyle[] { style } }; - } - - [Theory] - [MemberData(nameof(CreateGridTables_TestData))] - public void GridTablesFactory_CreateGridTables_Invoke_ReturnsExpected(DataGridTableStyle gridTable, object dataSource, string dataMember, BindingContext bindingManager, DataGridTableStyle[] expected) - { - Assert.Equal(expected, GridTablesFactory.CreateGridTables(gridTable, dataSource, dataMember, bindingManager)); - } - } -} diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ToolBarButtonClickEventArgsTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ToolBarButtonClickEventArgsTests.cs deleted file mode 100644 index 1e843078c6e..00000000000 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ToolBarButtonClickEventArgsTests.cs +++ /dev/null @@ -1,37 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Collections.Generic; -using Xunit; - -namespace System.Windows.Forms.Tests -{ - public class ToolBarButtonClickEventArgsTests - { - public static IEnumerable ToolBarButton_TestData() - { - yield return new object[] { null }; - yield return new object[] { new ToolBarButton() }; - } - - [Theory] - [MemberData(nameof(ToolBarButton_TestData))] - public void Ctor_ToolBarButton(ToolBarButton button) - { - var e = new ToolBarButtonClickEventArgs(button); - Assert.Equal(button, e.Button); - } - - [Theory] - [MemberData(nameof(ToolBarButton_TestData))] - public void Button_Set_GetReturnsExpected(ToolBarButton value) - { - var e = new ToolBarButtonClickEventArgs(new ToolBarButton()) - { - Button = value - }; - Assert.Equal(value, e.Button); - } - } -} diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/TreeNodeCollectionTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/TreeNodeCollectionTests.cs index b40b2b31088..86435c2b585 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/TreeNodeCollectionTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/TreeNodeCollectionTests.cs @@ -26,7 +26,6 @@ public void TreeNodeCollection_Add_String_Success(string text, string expectedTe Assert.True(treeNode.Bounds.Width > 0); Assert.True(treeNode.Bounds.Height > 0); Assert.False(treeNode.Checked); - Assert.Null(treeNode.ContextMenu); Assert.Null(treeNode.ContextMenuStrip); Assert.Null(treeNode.FirstNode); Assert.Equal(Color.Empty, treeNode.ForeColor); diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/TreeNodeTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/TreeNodeTests.cs index c410c963027..136d6139ee7 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/TreeNodeTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/TreeNodeTests.cs @@ -18,7 +18,6 @@ public void TreeNode_Ctor_Default() Assert.Equal(Color.Empty, treeNode.BackColor); Assert.Equal(Rectangle.Empty, treeNode.Bounds); Assert.False(treeNode.Checked); - Assert.Null(treeNode.ContextMenu); Assert.Null(treeNode.ContextMenuStrip); Assert.Null(treeNode.FirstNode); Assert.Equal(Color.Empty, treeNode.ForeColor); @@ -59,7 +58,6 @@ public void TreeNode_Ctor_String(string text, string expectedText) Assert.Equal(Color.Empty, treeNode.BackColor); Assert.Equal(Rectangle.Empty, treeNode.Bounds); Assert.False(treeNode.Checked); - Assert.Null(treeNode.ContextMenu); Assert.Null(treeNode.ContextMenuStrip); Assert.Null(treeNode.FirstNode); Assert.Equal(Color.Empty, treeNode.ForeColor);