Editable Button in WPF

Editable Button in WPF

Today I am going to share a code snippet to create an Editable Button in WPF, where we can update the text of a Button at runtime. In this control the user would right-click a button and then click 'Edit' to make to control Editable, and later right-click
it to save/cancel the change.

First step to make the Button
editable is to change the Style of Button and add a TextBox inside it, which we will make visible when the user clicks on 'Edit'.

As you can see in the above code, I have added a "txtContent" textbox which is hidden. Also to make editing look like a part of the Button, the Background and BorderBrush properties of
textbox are transparent.

01.PublicClass
EditableButton

02.InheritsButton

03.PrivatemButtonContentPresenterAs
ContentPresenter

04.PrivatemButtonTextBoxAs
TextBox

05.

06.PublicSub
New()

07.Me.DefaultStyleKey
= GetType(EditableButton)

08.AddHandlerMe.Loaded,
New
RoutedEventHandler(AddressOfEditableButton_Loaded)

40.AddHandleritm.Click,
New
RoutedEventHandler(AddressOfitmSave_Click)

41.menu.Items.Add(itm)

42.

43.itm
= New
MenuItem()

44.itm.Header
= "Cancel"

45.AddHandleritm.Click,
New
RoutedEventHandler(AddressOfitmCancel_Click)

46.menu.Items.Add(itm)

47.

48.ContextMenuService.SetContextMenu(mButtonTextBox,
menu)

49.EndSub

50.

51.

52.

53.PrivateSub
CreateEditContextMenu()

54.Dimmenu AsNew
ContextMenu

55.Dimitm AsNew
MenuItem

56.itm.Header
= "Edit"

57.AddHandleritm.Click,
New
RoutedEventHandler(AddressOfitmEdit_Click)

58.menu.Items.Add(itm)

59.

60.ContextMenuService.SetContextMenu(mButtonContentPresenter,
menu)

61.EndSub

62.

63.PrivateSub
itmEdit_Click(sender
As
Object, e AsRoutedEventArgs)

64.mButtonContentPresenter.Visibility
= Visibility.Collapsed

65.mButtonTextBox.Visibility
= Visibility.Visible

66.IsEditMode
= True

67.EndSub

68.

69.PrivateSub
itmSave_Click(sender
As
Object, e AsRoutedEventArgs)

70.mButtonContentPresenter.Visibility
= Visibility.Visible

71.mButtonTextBox.Visibility
= Visibility.Collapsed

72.Me.Content
= mButtonTextBox.Text

73.IsEditMode
= False

74.EndSub

75.

76.PrivateSub
itmCancel_Click(sender
As
Object, e AsRoutedEventArgs)

77.mButtonContentPresenter.Visibility
= Visibility.Visible

78.mButtonTextBox.Visibility
= Visibility.Collapsed

79.IsEditMode
= False

80.EndSub

81.EndClass

In the above code we have an "IsEditMode" property which the user can use to know whether the control is in Edit Mode or not. Also, we have two different Context Menus, one to Edit the Control, and the
another to Save/Cancel the changes. Based on the
menuitems that are clicked, we are going to set the visibility of TextBox and ContentPresenter, defined in XAML.