的一個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