Binding SelectionChanged to ViewModel using Caliburn.Micro

回眸只為那壹抹淺笑 提交于 2019-12-31 20:18:28

问题


We've using Caliburn.Micro on a new Silverlight project and everythings working great. The inbuilt conventions bind buttons click events to the viewModel, but I'm not sure what the best way to handle the selectionChanged event on datagrids and comboboxes is.

At the moment, I'm binding to the selected item and calling custom logic, but I feel like this is a bit of a code smell and that I should seperate the setting of the property and the selectedChange event. But if I seperate these, how do I bind the selection changed event to my viewModel, by commands? or an EventTrigger? Or is the code below acceptable? Its a small change but I do this logic everywhere.

private Foo _selectedFoo;
public Foo SelectedFoo
{
    get
    {
        return _Foo;
    }
    set
    {
        if (_Foo != null && _Foo.Equals(value)) return;
        _Foo = value;
        NotifyOfPropertyChange("SelectedFoo");
        NotifyOfPropertyChange("CanRemove");
        LoadRelatedBars();
    }
}

回答1:


I use this technique regularly and I feel very comfortable with it.
I find perfectly fine that the VM reacts to its own state change, without the need for the external actor (which incidentally is the View, but could be another component, too) to set the new state, THEN signal the VM that the state is changed.

If you really want to, however, you can use the Message.Attach attached property to hook an event in the View to an action in the VM:

cal:Message.Attach="[Event SelectionChanged] = [OnSelectionChangedAction]"

(see also https://caliburnmicro.com/documentation/actions)




回答2:


Here is a sample for MVVM and Caliburn.Micro using. Some actions like SelectionChanged should get an explicit a event arguments, so you should set it in caliburn event action part. Freqently first argument is passing $this (The actual ui element to which the action is attached.) and you gets in handler a datacontext for the row but to get to the Grid you should pass $source, as the first argument ($source - is the actual FrameworkElement that triggered the ActionMessage to be sent). According to the manual Caliburn manual.

XAML

cal:Message.Attach="[Event SelectionChanged]=[Action DataGrid_JobTypesSelectionChanged($source,$eventArgs)];"

Code:

public void DataGrid_JobTypesSelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        var grid = sender as DataGrid;
        JobTypesSelectedCollection = grid.SelectedItems.Cast<JobComplexModel>().ToList();
    }


来源:https://stackoverflow.com/questions/4041233/binding-selectionchanged-to-viewmodel-using-caliburn-micro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!