我正在使用PRISM使用MVVM设计模式开发我的Windows Phone应用程序。我需要将我的SelectedItem对象从我的LongListSelector通过我的委托命令传递给我的方法。
我能做到。问题是,我传递了错误的对象。我不知道这是设计问题还是我的约束不当。
我需要将对象作为Album对象。我得到的是null或我的ViewModel。 (我已经改变了几次代码,这是我能得到的唯一东西。)
XAML
<phone:LongListSelector x:Name="AlbumList" ItemsSource="{Binding Albums}"
Margin="10,0,0,0" LayoutMode="Grid" GridCellSize="200, 200"
ItemTemplate="{StaticResource AlbumTemplate}"
toolkit:TiltEffect.IsTiltEnabled="True"
>
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<i:InvokeCommandAction Command="{Binding DataContext.SelectAlbumCommand, ElementName=ContentPanel}"
CommandParameter="{Binding}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</phone:LongListSelector>
视图模型
private ObservableCollection<Album> _albums;
public ObservableCollection<Album> Albums
{
get { return _albums; }
set
{
if (value != null)
{
_albums = value;
NotifyPropertyChanged();
}
}
}
private Album _selectedAlbum;
public Album SelectedAlbum
{
get { return _selectedAlbum; }
// code removed as it is not needed; the object is null when trying to set.
}
public void AlbumSelected(object p)
{
App.Dispatcher.BeginInvoke(() =>
{
SelectedAlbum = (Album)p;
});
////Navigate("/Views/PhotosListPage.xaml");
}
//command that takes an object as parameter.
_selectAlbumCommand = new DelegateCommand<object>(this.AlbumSelected);
答案 0 :(得分:1)
如果您只是想通过SelectedAlbum
设置SelectAlbumCommand
,为什么不尝试将SelectedItem
绑定到SelectedAlbum
?
<phone:LongListSelector x:Name="AlbumList" ItemsSource="{Binding Albums}"
SelectedItem="{Binding SelectedAlbum}" />
如果您确实想将SelectedItem
传递给SelectedAlbumCommand
(由于某些其他原因),您应该将CommandParameter
绑定到SelectedItem
LongListSelector
1}}
<i:InvokeCommandAction Command="{Binding DataContext.SelectAlbumCommand, ElementName=ContentPanel}" CommandParameter="{Binding ElementName=AlbumList, Path=SelectedItem}"/>
答案 1 :(得分:0)
显然,你不能使用LongListSelector。我不得不将其更改为列表框,并且工作正常。
如果我更努力地搜索,我会发现:How to select an item in LongListSelector using the MVVM-pattern?