I am just starting with Caliburn Micro. I want to have a combo box with a list of strings, and when the user selects an item, I want to have some notify method called. It should be simple, right? I am impatient, and 5 minutes of Googling has not solved it for me, so Stackers to the rescue!
Note: I favor an answer that shows me how to put this into the view model. Avoiding complex XAML is the whole point of a MVVM framework, IMHO.
Caliburn.Micro has baked in conventions supporting ItemsControl
(e.g. ComboBox or ListBox) based controls which make the required xaml in you View minimal.
First you have the standard convention where a controls content will be bound to a ViewModel property with the same name as the control. In the case of ItemsControl
the controls content property is ItemsControl.ItemsSource
. And the second convention you get out of the box with Caliburn.Micro is that an attempt will be made to bind ItemsControl.SelectedItem
to a ViewModel property which has the singularized name of the control, with either "Active", "Selected" or "Current" prepended (see ConventionManager
in the Caliburn.Micro source).
This in mind you can achieve what you want with the following in your View:
<ComboBox x:Name="Strings"></ComboBox>
and in your ViewModel:
public BindableCollection<string> Strings
{
get
{
// silly example of the collection to bind to
return new BindableCollection<string>(
new string[]{ "one", "two", "three"});
}
}
private string _selectedString;
public string SelectedString
{
get { return _selectedString; }
set
{
_selectedString= value;
NotifyOfPropertyChange(() => SelectedString);
// and do anything else required on selection changed
}
}
The first convention picks up the control name ("Strings") and binds ComboBox.ItemsSource
to the ViewModel property Strings
. The second convention first singularizes "Strings" to "String" and prepends "Selected" to get the property "SelectedString" to bind ComboBox.SelectedItem
to.
<ListBox x:Name="Items" ItemsSource="{Binding Path=Items}" cal:Message.Attach="[Event SelectionChanged]=[Action SelectedItemChanged($this.SelectedItem)]">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With