I am using the convention-based binding from Caliburn.Micro, but I have a small issue:
How do I set the property that my binding should bind to? If I create a control with x:Name="SomeProperty", how do I choose if the value of SomeProperty should be binded to the Value Property of my control, the OnClick Event of my control or something different, like the Content or the Tag property?
Example: I have this HyperlinkButton that I want to bind to a specific URL, and I want to bind the OnClick to an event handler in my ViewModel.
<HyperlinkButton x:Name="BookDetailsViewModel_InfoLink" Content="Read more" />
The Content property however is not filled with Read more but with the value of the URL. In this example, how do I:
- Set the navigation URI to the value of the URL in my ViewModel property
- Set the content to “Read more”
- Specify an event handler in my ViewModel that will handle the click
Can anyone help me please?
You can customise the ConventionManager per element type in CM. The default out-of-box implemententation is applied to any element which doesn’t have an explicit customisation
To add a new convention you just simply call ConventionManager.AddElementConvention
The method looks like this (from CM source)
As you can see, it takes a few args – you need to pass the default property for bindings, actions, and triggers e.g.
(assuming the click event is called Click)
Since you aren’t binding the
Contentproperty any more (because the convention is to now bind NavigateUri) you can just leave that as-is and it should remain ‘Read more…’So now you have a
HyperlinkButtoncontrol which should bind by convention to theNavigateUri, and call the method which shares it’s name when theClickevent is triggered.Edit:
I might make a clarification that I don’t think you can bind to both a method and a property on the same VM since you can’t have a method and a property that share the same name, but I’m sure CM would bubble the action message up the VM hierarchy if you didn’t have the appropriate method on the VM… not tried it though. To bind the actions see my other edit below
Don’t forget, you could always just use the explicit syntax for all of this!
but it’s probably better to go the convention route 🙂
Edit:
Might add how to get convention to grab the property value from the hyperlink –
CM knows that since you set
NavigateUrias the default action parameter, it should grab this and pass it to the method that you specified in the action binding. I’m wondering if$thiswill also work (you probably would need$this.NavigateUri). You can do this across controls e.g.The above would pass the
Textproperty of the textbox to theHyperlinkClickedmethod by default.