【发布时间】:2012-12-16 09:53:52
【问题描述】:
使用 MVVM 将 ListBox 的项绑定到 ViewModel 时是否有约定?
在下面的 XAML 中,我正在创建一个按钮列表框。 ListBox 绑定到我的 ViewModel 中的一个可观察集合。然后我想将按钮的 Command 属性绑定到 ICommand。问题是当我添加该绑定时,我绑定的是数据对象,而不是 ViewModel。
我是否只是将 MyListOfDataObjects 属性更改为 ViewModel 列表?如果是这样,我在哪里实例化这些新对象?我更喜欢使用依赖注入,因为它们会有多个依赖项。我是否更改 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 ViewModel:
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 我的意思是按下按钮时调用的 ButtonPressedCommand 将是在 MyData 类中定义的,而不是在 MainViewModel 类中定义的。