tags:

views:

37

answers:

1

I'm novice in the GUI development, in particular with WPF, and don't know related patterns. So I want to ask you about a problem which arises from time to time and I'm not sure about the best solution for it.

Let we have three user controls A, B, C and control A include control B, control B include control C. Let control C has a button. The click event for this must be tackled using data from class A. I see the following possible way to sort this situation out:

1) Add method InnerButtonClick(object sender, RoutedEventArgs e) to the class A which will struggle with bubbling event caused by our button. Minuses:

i) this method will catch all button.click events from A's children. So I will have to implement some conditional logic in the method in order to check that the event is caused by our button.

ii) It is not easy to get C's properties there. It may look like

        var btn = (Button)e.OriginalSource;
        string userName = ((ActionButtons)((UserControl)((StackPanel)btn.Parent).Parent)).UserName;

if the button is in the StackPanel and StackPanel in the user control C.

2) Provide access for the necessary data for the class C. For instance, pass data to the class B, and then to C. Minuses:

i) it is often not so easy.

ii) it causes extra methods/constructors parameters.

3) Create a static method in the class A, which may be called by class C methods. Minuses:

i) It looks a bit unpleasant. It is the way to singleton, the pattern from the 'dark side of the force')

A: 

RoutedCommands are precisely for this type of scenario. Set the command on the button in C, and add a CommandBinding to A, A doesn't need to know about C, and C doesn't need to know anything about A this way. When the button in C is clicked, the command will bubble up to the first commandbinding it finds, which will be A in your case.

edit:
You can use the CommandParameter property to pass the text from the TextBox. If you need to pass on more info than just 1 field, you could handle the button click event in C, gather the necessary data in a single object, and then trigger the command from code with that object as parameter.

Bubblewrap
Sorry, i misread that bit. See the edited response.
Bubblewrap
thank you. it sounds nice
Kirill Lykov