24

我刚开始使用 Caliburn Micro。我想要一个带有字符串列表的组合框,当用户选择一个项目时,我想要调用一些通知方法。应该很简单吧?我很不耐烦,5 分钟的谷歌搜索还没有为我解决,所以 Stackers 来救援!

注意:我赞成向我展示如何将其放入视图模型的答案。避免复杂的 XAML 是 MVVM 框架的重点,恕我直言。

4

2 回答 2

62

Caliburn.Micro 已经加入了支持ItemsControl基于控件(例如 ComboBox 或 ListBox)的约定,这使得 View 中所需的 xaml 最小化。

首先,您有一个标准约定,其中控件内容将绑定到与控件同名的 ViewModel 属性。ItemsControl在控件内容属性的情况下是ItemsControl.ItemsSource. 使用 Caliburn.Micro 开箱即用的第二个约定是,将尝试绑定ItemsControl.SelectedItem到 ViewModel 属性,该属性具有控件的单数化名称,前缀为“Active”、“Selected”或“Current” (参见ConventionManagerCaliburn.Micro 源代码)。

记住这一点,您可以在视图中使用以下内容来实现您想要的:

<ComboBox x:Name="Strings"></ComboBox>

在您的 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
    }
}

第一个约定选择控件名称(“字符串”)并绑定ComboBox.ItemsSource到 ViewModel 属性Strings。第二个约定首先将“Strings”单数化为“String”,并在“Selected”前面加上要绑定的属性“SelectedString” ComboBox.SelectedItem

于 2011-05-02T05:14:36.067 回答
12
<ListBox x:Name="Items" ItemsSource="{Binding Path=Items}" cal:Message.Attach="[Event SelectionChanged]=[Action SelectedItemChanged($this.SelectedItem)]">
于 2011-04-29T21:28:07.153 回答