New Video Tutorial: How to Use a Behavior to Fire Methods from Objects in Styles
Hello All!
Recently I had a developer ask me how he could fire an event from the CheckBox that I had put in the Style of the UserControl I gave him.
I thought about it and, the problem is that objects in a Style are not really part of the Visual Tree until the Style is attached at runtime.
After a lot of thought and many failures I developed a Behavior (IN CODE) that can be attached to objects in or out of Styles that allows you to specify what Method they need to fire. This Behavior uses Reflection to find and invoke the specificed method.
I made a video tutorial to show you how to do it too!
Enjoy!
Victor Gaudioso
Video: http://tinyurl.com/yhp96zr
Hi,
nice solution.
I did something similar with Behaviors but in a more declarative way from XAML, i think it should work for controls in styles also:
http://blog.roboblob.com/2010/01/26/binding-ui-events-from-view-to-commands-in-viewmodel-in-silverlight-4/
cheers,
Roboblob
Victor, there is a flaw in your implementation. The behavior creates a *new* instance of MainPage. I would think you would want to walk the visual tree and find the *existing* instance.
You know, I did quickly try to do exactly what you said but it didn’t work and I just went with the fast and quick solution. So, I think you are correct, maybe you could come up with the solution and I will implement it? Thanks for your close attention to detail! Victor
Hi Victor,
this is a reply to the comment from Rob.
I guess the follwing code might answer the question on how to get access to MainPage from the code behind of a behavior.
‘ Code in the behavior:
Protected Overrides Sub OnAttached()
MyBase.OnAttached()
AddHandler AssociatedObject.MouseLeftButtonUp, AddressOf AssociatedObject_MouseLeftButtonDown
End Sub
‘ OnDetached not displayed
Private Sub AssociatedObject_MouseLeftButtonDown(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs)
Dim myMain As MainPage = App.Current.RootVisual
Dim methodinvoke As MethodInfo = GetType(MainPage).GetMethod(“TestMethodMainPage”)
methodinvoke.Invoke(myMain, Nothing)
End Sub
‘ Code in MainPage.xaml.vb:
Public Sub TestMethodMainPage()
MessageBox.Show(“This is a MainPage method”)
End Sub
I implemented AssociatedObject_MouseLeftButtonDown in a behavior for a ChildWindow. The behavior inherits from class behavior.
Best regards,
Martin (LawBot/SilverLaw)
P.S.: You can download a ChildWindowMouseScrollResizeBehavior that I developed at the Expression Gallery.
… or slightly shorter:
Dim methodinvoke As MethodInfo = GetType(MainPage).GetMethod(“TestMethodMainPage”)
methodinvoke.Invoke(App.Current.RootVisual, Nothing)
Very Cool! Thanks Roboblob!