WPF Cannot unsubscribe from a RoutedEvent, not working. After unsubscribing it continues firing - wpf

I have an WPF User control in which I create a RoutedEventHandler. I want to raise an event notifying every time its height changes:
Wpfusercontrol.designer.cs:
public partial class Wpfusercontrol: System.Windows.Controls.UserControl
{
public static readonly RoutedEvent HeightChangedEvent = EventManager.RegisterRoutedEvent(
"HeightChanged", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(Wpfusercontrol));
public event RoutedEventHandler HeightChanged
{
add { AddHandler(HeightChangedEvent, value); }
remove { RemoveHandler(HeightChangedEvent, value); }
}
private void UserControl_SizeChanged(object sender, SizeChangedEventArgs e)
{
if (e.HeightChanged && HeightChangedEvent != null)
{
RaiseEvent(new RoutedEventArgs(HeightChangedEvent));
}
}
}
Then this WPF user control is hosted in an ElementHost
WindowsFormsHostControl.Designer.cs:
partial class WindowsFormsHostControl
{
private void InitializeComponent()
{
this.ElementHostFormControl = new System.Windows.Forms.Integration.ElementHost();
this.Wpfusercontrol= new Wpfusercontrol();
this.SuspendLayout();
//
// ElementHostFormControl
//
this.ElementHostFormControl.Dock = System.Windows.Forms.DockStyle.Fill;
this.ElementHostFormControl.Location = new System.Drawing.Point(0, 0);
this.ElementHostFormControl.Margin = new System.Windows.Forms.Padding(2);
this.ElementHostFormControl.Name = "ElementHostFormControl";
this.ElementHostFormControl.Size = new System.Drawing.Size(75, 78);
this.ElementHostFormControl.TabIndex = 0;
this.ElementHostFormControl.Child = this.Wpfusercontrol;
//
// WindowsFormsHostControl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.ElementHostFormControl);
this.Margin = new System.Windows.Forms.Padding(2);
this.Name = "WindowsFormsHostControl";
this.Size = new System.Drawing.Size(75, 78);
this.ResumeLayout(false);
}
private System.Windows.Forms.Integration.ElementHost ElementHostFormControl;
private Wpfusercontrol Wpfusercontrol;
}
WindowsFormsHostControl.cs:
public partial class WindowsFormsHostControl: System.Windows.Forms.UserControl
{
private RoutedEventHandler heightChangedEventHandler;
public WindowsFormsHostControl()
{
InitializeComponent();
}
public WindowsFormsHostControl(RoutedEventHandler heightChangedEventHandler) : this()
{
this.heightChangedEventHandler = heightChangedEventHandler;
this.Wpfusercontrol.HeightChanged += this.heightChangedEventHandler;
}
public void SubscribeHeightChanged()
{
this.Wpfusercontrol.HeightChanged += this.heightChangedEventHandler;
}
public void UnsubscribeHeightChanged()
{
this.Wpfusercontrol.HeightChanged -= this.heightChangedEventHandler;
}
}
This WindowsFormsHostControl is embedded within an UI object called custom task pane which is kind of UI container for VSTO Outlook Add-ins. This custom task pane has a button to resize its height but it does not provide an event to catch it. So when you resize the height of that custom task pane, the height of the wpf user control changes as well, so through the routed event in the wpf user control I know when the custom task pane is resized and I catch the event.
Now from one class in my VSTO Outlook Add-in application (which in fact is a winforms app), I perform below things:
private WindowsFormsHostControl windowsFormsHostControl = null;
this.windowsFormsHostControl = new WindowsFormsHostControl(this.WpfUserControl_HeightChanged);
System.Windows.Fomrs.Timer t;
private void WpfUserControl_HeightChanged(object sender, System.Windows.RoutedEventArgs e)
{
// Dome some stuff
...
t = new System.Windows.Fomrs.Timer();
t.Tick += new EventHandler(Update);
t.Interval = 100;
t.Enable = true;
}
private void Update(object sender, EventArgs e)
{
// Some more stuf....
....
// In below lines I update the height of the custom task pane (VSTO Outlook UI object) which in turn causes the WPF user control to resize its height as well. So then, I am trying to unsubscribe from the wpf routed event, then update the height for custom task pane, and finally subscribe again to the wpf routed event. I do this to prevent routed event in wpf user control fires again.
this.windowsFormsHostControl.UnsubscribeHeightChanged();
// here I update the height for custom task pane
this.windowsFormsHostControl.SubscribeHeightChanged();
}
The problem is that it looks like the line:
this.windowsFormsHostControl.UnsubscribeHeightChanged();
is not working because the routed event in the wpf user control continues raising each time I execute the line of code between UnsubscribeHeightChanged and SubscribeHeightChanged.
So what am i doing wrong?

Related

WinForms Button: draw as the default button without setting the form's AcceptButton property (custom drawing, IsDefault property, BS_DEFPUSHBUTTON)

Imagine the following construction in WinForms .NET. A WinForms form contains a custom control with several buttons, which are instances of the traditional Button class. One of these buttons is the default button for the form. The custom control executes the action associated with the default button when ENTER is pressed. This is done in the redefined ProcessCmdKey method:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == Keys.Return)
{
buttonOK_Click(null, EventArgs.Empty);
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
The default button must have an additional visual cue telling the user that this is the default button (an extra border inside the button). If we did this in a normal form, we would set its AcceptButton property. However, this approach is not applicable here. Even if we find the parent form using the Control.FindForm method or with an expression like (this.Parent as Form), we cannot set the AcceptButton property of the host form and then clear it the right way without resource leak or similar problems (a lot of technical details to place here and to bloat the question).
The first possible way to solve this task is to redefine or enhance the drawing of the button. Is there a relatively easy way to draw a button as the default button with the corresponding visual cue without implementing full custom painting? In my understanding, we might write a special class for our default button based on the following core:
internal class DefaultButton : Button
{
protected override void OnPaint(PaintEventArgs pevent)
{
Rectangle rc = new Rectangle(0, 0, this.Width, this.Height);
ButtonRenderer.DrawButton(pevent.Graphics, rc, System.Windows.Forms.VisualStyles.PushButtonState.Default);
}
}
However, it should take into account the focused state, whether another button on a form is focused (in this case the default button is not drawn with the visual cue), and the like. I could not find a good example of this to use as a basis for my development.
Another possible way to solve my problem could be setting the protected IsDefault property or/and specifying the BS_DEFPUSHBUTTON flag in the overridden CreateParams method in a class inherited from the Button class, for example:
internal class DefaultButton : Button
{
public DefaultButton() : base()
{
IsDefault = true;
}
protected override CreateParams CreateParams
{
get
{
const int BS_DEFPUSHBUTTON = 1;
CreateParams cp = base.CreateParams;
cp.Style |= BS_DEFPUSHBUTTON;
return cp;
}
}
}
But I could not make this code work. Buttons based on this class are always drawn as normal push buttons without the default button visual cue.
I'm not sure about the original requirement; for example I don't have any idea why a UserControl itself should set the AcceptButton of a Form, or what is the expected behavior if there are multiple instances of such controls on the form. It doesn't seem to be responsibility of the UserControl to set the AcceptButton of the Form and there might be better solutions, like relying on events and setting the AcceptButton.
Anyways, the following code example shows you how to set the AcceptButton of a Form; maybe it helps you to find a solutions. The highlights of the code:
The code uses dispose to set the AcceptButton to null.
The code implements ISupportInitialize to set the accept button after initialization of the control is done. If you create the control instance at run-time with code, don't forget to call EndInit, like this: ((System.ComponentModel.ISupportInitialize)(userControl11)).EndInit(); after adding it to the Form, but if you use designer, the designer will take care of that.
The code calls NotifyDefault(true) just for visual effect in design time when it's hosted on a form.
Here's the example:
using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public class UserControl1 : UserControl, ISupportInitialize
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.textBox1 = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(15, 57);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 0;
this.button1.Text = "button1";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// button2
//
this.button2.Location = new System.Drawing.Point(96, 57);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(75, 23);
this.button2.TabIndex = 1;
this.button2.Text = "button2";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(15, 17);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(100, 20);
this.textBox1.TabIndex = 2;
//
// UserControl1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.textBox1);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Name = "UserControl1";
this.Size = new System.Drawing.Size(236, 106);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TextBox textBox1;
public System.Windows.Forms.Button button1;
public System.Windows.Forms.Button button2;
public UserControl1()
{
InitializeComponent();
//Just for visual effect in design time when it's hosted on a form
button2.NotifyDefault(true);
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("1");
}
private void button2_Click(object sender, EventArgs e)
{
MessageBox.Show("2");
}
public void BeginInit()
{
}
public void EndInit()
{
var f = this.FindForm();
if (f != null)
f.AcceptButton = button2;
}
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
if (disposing)
{
var f = this.FindForm();
if (f != null)
f.AcceptButton = null;
}
base.Dispose(disposing);
}
}
}

Prevent RepositoryItemSearchLookUpEdit when Popup is Open When CloseUpKey.Key is pressed

I use a RepositoryItemSearchLookUpEdit. its CloseUpKey property is set to space
result.CloseUpKey = new DevExpress.Utils.KeyShortcut(System.Windows.Forms.Keys.Space);
I want to use this shortcut only for open popup and not for closing popup.
How can I achieve this?
UPDATE------------------------
First I create an RepositoryItemSearchLookUpEdit object
var result = new RepositoryItemSearchLookUpEdit();
result.CloseUpKey = new DevExpress.Utils.KeyShortcut(System.Windows.Forms.Keys.Space);
result.KeyDown += repositoryItemLookUpEdit_KeyDown;
result.CloseUp += repositoryItemLookUpEdit_CloseUp;
result.QueryCloseUp += repositoryItemLookUpEdit_QueryCloseUp;
private void repositoryItemLookUpEdit_QueryCloseUp(object sender, System.ComponentModel.CancelEventArgs e)
{
var edit = sender as SearchLookUpEdit;
KeyEventArgs k = new KeyEventArgs(edit.Properties.CloseUpKey.Key);
AttachKeyPressEvent(k);
if (k.KeyCode == edit.Properties.CloseUpKey.Key)
e.Cancel = true;
}
And pass it to a grid column:
grdListView.Columns["yyy"].ColumnEdit = result
How can I achieve that with these events, without creating a descendant SearchLookUpEdit
UPDATED:
The problem is that CloseUp event (where you could get the necessary info about the closeup key) occurs after the QueryCloseUp event (where you could precent the closing up event). Also the KeyPress, KeyDown and KeyUp events seem also NOT to occur when the QueryCloseUp occurs, as a result they couldn't be overridden. So I tried this, I created a custom KeyEventHandler and triggered him during QueryCloseUp event in order to get the necessary info of what key was pressed and cancel the event if the close key event was the one. Here is my codeTry it to see if it suits you
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
//Here you can add your grid control as you have created
DataTable dt = new DataTable();
dt.Columns.Add("ID"); //use your own names and types
gridControl1.DataSource = dt;
var result = new RepositoryItemSearchLookUpEdit();
result.CloseUpKey = new DevExpress.Utils.KeyShortcut(System.Windows.Forms.Keys.Space);
result.QueryCloseUp += new CancelEventHandler(repositoryItemLookUpEdit_QueryCloseUp);
((gridControl1.MainView as GridView).Columns["ID"] as GridColumn).ColumnEdit = result;
}
private static readonly object myQueryCloseUp = new object();
public event KeyEventHandler MyQueryCloseUp
{
add { Events.AddHandler(myQueryCloseUp, value); }
remove { Events.RemoveHandler(myQueryCloseUp, value); }
}
protected virtual void AttachKeyPressEvent(KeyEventArgs e)
{
KeyEventHandler handler = (KeyEventHandler)Events[myQueryCloseUp];
if (handler != null)
handler(this, e);
}
//Here you add your own Handler implementation
public void repositoryItemLookUpEdit_QueryCloseUp(object sender, CancelEventArgs e)
{
KeyEventArgs k = new KeyEventArgs((sender as SearchLookUpEdit).Properties.CloseUpKey.Key);
AttachKeyPressEvent(k);
if (k.KeyCode == (sender as SearchLookUpEdit).Properties.CloseUpKey.Key)
e.Cancel = true;
}
}

Prism AnimatedTabControl customization

I have a user interface like Prism StockTrader RI application with some changes whrere
i put control panel in ResearchRegion contains list of items when i select one item
its details are displayed in the AnimatedTabControl in the main region.
I need to customize the AnimatedTabControl (from StockTrader RI) like this:
The AnimatedTabControl show tab header like normal tab control where header
will contain the selected item name
When new selection is applied from a control panel that resides in the ResearchRegion a
new tab open w/o removing the previous tab selection and w/o animation
Tab header contain close button to close any of the open tabs when required
Animation take place only when changing the control panel in the ResearchRegion
public class AnimatedTabControl : TabControl
{
public static readonly RoutedEvent SelectionChangingEvent = EventManager.RegisterRoutedEvent(
"SelectionChanging", RoutingStrategy.Direct, typeof(RoutedEventHandler), typeof (AnimatedTabControl));
private DispatcherTimer timer;
public AnimatedTabControl()
{
DefaultStyleKey = typeof(AnimatedTabControl);
}
public event RoutedEventHandler SelectionChanging
{
add { AddHandler(SelectionChangingEvent, value); }
remove { RemoveHandler(SelectionChangingEvent, value); }
}
protected override void OnSelectionChanged(SelectionChangedEventArgs e)
{
this.Dispatcher.BeginInvoke(
(Action)delegate
{
this.RaiseSelectionChangingEvent();
this.StopTimer();
this.timer = new DispatcherTimer { Interval = new TimeSpan(0, 0, 0, 0, 500) };
EventHandler handler = null;
handler = (sender, args) =>
{
this.StopTimer();
base.OnSelectionChanged(e);
};
this.timer.Tick += handler;
this.timer.Start();
});
}
// This method raises the Tap event
private void RaiseSelectionChangingEvent()
{
var args = new RoutedEventArgs(SelectionChangingEvent);
RaiseEvent(args);
}
private void StopTimer()
{
if (this.timer != null)
{
this.timer.Stop();
this.timer = null;
}
}
}
Thanks in Advance
I have answered part#3 of your question(Tab header contain close button to close any of the open tabs when required).
Have a look at my public folder in SkyDrive Account:-
(https://skydrive.live.com/redir?resid=656548C49A72B6CD!105)

Devexpress PopupContainerEdit popup always open

Im'm using winform DevExpress library.
Now need to create a control, basing on PopupContainerEdit but this control must have some behaviors like when it's focused, the popup opens and when lost focus the popup closes.
This is the code I'm using but the popup dessapears after getting focus.
public class HelpEdit : PopupContainerEdit {
private PopupContainerControl _container;
private GridControl _gridControl;
private GridView _gridView;
[DefaultValue("")]
[DXCategory("Data")]
[AttributeProvider(typeof(IListSource))]
public object Datasource {
get { return _gridControl.DataSource; }
set { _gridControl.DataSource = value; }
}
public HelpEdit() : base() {
_container = new PopupContainerControl();
this.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.Standard;
this._gridControl = new GridControl();
this._gridControl.Dock = DockStyle.Fill;
this._gridView = new GridView(_gridControl);
_container.Controls.Add(_gridControl);
_container.Size = new Size(this.Width, 250);
this.Properties.PopupControl = _container;
this.Properties.PopupControl.Size = new Size(this.Width, 250);
}
protected override void OnGotFocus(EventArgs e) {
base.OnGotFocus(e);
this.ShowPopup();
}
protected override void OnLostFocus(EventArgs e) {
base.OnLostFocus(e);
this.ClosePopup();
}
}
Your popup disappears because it closes by your code as soon as the popup container control(_container) got focus itself. You should not close popup within the OnLostFocus() override because the base.OnLostFocus method of PopupContainerEdit is already contains correct code for closing popup. Or close popup conditionally, using the following code:
protected override void OnLostFocus(EventArgs e) {
if(IsPopupOpen && !EditorContainsFocus)
ClosePopup(PopupCloseMode.Immediate);
base.OnLostFocus(e);
}

How do I provide designer support to a TabControl residing in a UserControl, so that I can drag/drop controls onto tab pages?

I have a user control, which contains both a Panel and a TabControl. I enabled design-time support for both. I can drag/drop controls from the toolbox onto the Panel control that resides within the user control. I can also add and remove tab pages via the designer on the TabControl. However, I am not able to drag/drop any controls onto the tab pages themselves.
Below is the code generated source code for my user control:
partial class TestUserControl
{
private System.ComponentModel.IContainer components = null;
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
private void InitializeComponent()
{
this.tabControl = new System.Windows.Forms.TabControl();
this.contentPanel = new System.Windows.Forms.Panel();
this.SuspendLayout();
//
// tabControl
//
this.tabControl.Dock = System.Windows.Forms.DockStyle.Fill;
this.tabControl.Location = new System.Drawing.Point(0, 0);
this.tabControl.Name = "tabControl";
this.tabControl.SelectedIndex = 0;
this.tabControl.Size = new System.Drawing.Size(306, 118);
this.tabControl.TabIndex = 0;
//
// contentPanel
//
this.contentPanel.Dock = System.Windows.Forms.DockStyle.Bottom;
this.contentPanel.Location = new System.Drawing.Point(0, 118);
this.contentPanel.Name = "contentPanel";
this.contentPanel.Size = new System.Drawing.Size(306, 73);
this.contentPanel.TabIndex = 0;
//
// TestUserControl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.tabControl);
this.Controls.Add(this.contentPanel);
this.Name = "TestUserControl";
this.Size = new System.Drawing.Size(306, 191);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.TabControl tabControl;
private System.Windows.Forms.Panel contentPanel;
}
Below is the source code I added to enable design-time support:
[Designer(typeof(TestUserControlDesigner))]
public partial class TestUserControl : UserControl
{
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public TabControl TabControl
{
get { return this.tabControl; }
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public Panel ContentPanel
{
get { return this.contentPanel; }
}
public TestUserControl()
{
InitializeComponent();
}
}
internal class TestUserControlDesigner : ParentControlDesigner
{
public override void Initialize(System.ComponentModel.IComponent component)
{
base.Initialize(component);
EnableDesignMode(
(this.Control as TestUserControl).TabControl, "TabControl");
EnableDesignMode(
(this.Control as TestUserControl).ContentPanel, "ContentPanel");
}
}
What do I need to do, so that I can drag/drop controls onto the tab pages of the TabControl?
You have to enable design mode on the existing tab pages as well:
internal class TestUserControlDesigner : ParentControlDesigner {
public override void Initialize(System.ComponentModel.IComponent component) {
base.Initialize(component);
var ctl = (this.Control as TestUserControl).TabControl as TabControl;
EnableDesignMode(ctl, "TabControl");
foreach (TabPage page in ctl.TabPages) EnableDesignMode(page, page.Name);
EnableDesignMode((this.Control as TestUserControl).ContentPanel, "ContentPanel");
}
}

Resources