的一个ObservableCollection是否有约定?绑定列表框的ViewModels
在下面的XAML中,我创建了一个ListBox的按钮。 ListBox绑定到我的ViewModel的可观察集合。然后我想将按钮的Command属性绑定到一个ICommand。问题是,当我添加绑定时,我绑定了数据对象,而不是ViewModel。
难道我只是改变MyListOfDataObjects属性为的ViewModels的名单?如果是这样,我在哪里实例化这些新对象?我宁愿使用依赖注入,因为它们会有几个依赖关系。我是否更改GetData lambda?
一般来说:这里认为什么是好的做法?我无法找到任何这种情况的例子,但我认为这很常见。
我使用MVVMLight框架,但我愿意看任何其他框架。
<Window x:Class="KeyMaster.MainWindow"
DataContext="{Binding Main, Source={StaticResource Locator}}">
<Window.Resources>
<ResourceDictionary>
<DataTemplate x:Key="MyDataTemplate">
<Button Command="{Binding ButtonPressedCommand}"
CommandParameter="{Binding .}"
Content="{Binding Name}" />
</DataTemplate>
</ResourceDictionary>
</Window.Resources>
<Grid x:Name="LayoutRoot">
<ListBox ItemsSource="{Binding MyListOfDataObjects}"
ItemTemplate="{StaticResource MyDataTemplate}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"
IsItemsHost="True" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ListBox>
</Grid>
</Window>
我使用标准MVVMLight视图模型:
using GalaSoft.MvvmLight;
using KeyMaster.Model;
using System.Collections.ObjectModel;
namespace KeyMaster.ViewModel
{
public class MainViewModel : ViewModelBase
{
private readonly IDataService _dataService;
private ObservableCollection<MyData> _myListOfDataObjects;
public MainViewModel(IDataService dataService)
{
_dataService = dataService;
_dataService.GetData(
(item, error) =>
{
if (error != null)
{
return;
}
MyListOfDataObjects = new ObservableCollection<MyData>(item);
});
}
public ObservableCollection<MyData> MyListOfDataObjects
{
get { return _myListOfDataObjects; }
set
{
if (_myListOfDataObjects == value) return;
_myListOfDataObjects = value;
RaisePropertyChanged(() => MyListOfDataObjects);
}
}
}
}
感谢。
你是什么意思*“我绑定数据对象,而不是ViewModel”*? – Blachshma
@Blachshma我的意思是按下按钮时调用的ButtonPressedCommand将是MyData类中定义的ButtonPressedCommand,而不是MainViewModel类中定义的。 – Josh