代码之家  ›  专栏  ›  技术社区  ›  user3007447

发送带有命令参数的对象

  •  1
  • user3007447  · 技术社区  · 11 年前

    我正在使用PRISM使用MVVM设计模式开发我的Windows Phone应用程序。我需要通过委托命令将我的SelectedItem对象从LongListSelector传递到我的方法中。

    我能做到。问题是,我传递了错误的对象。我不知道这是设计问题还是我绑定不当。

    我需要该对象是专辑对象。我得到的不是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);
    
    2 回复  |  直到 11 年前
        1
  •  2
  •   bit    11 年前

    如果您只想设置 SelectedAlbum 由您的 SelectAlbumCommand ,为什么不尝试绑定 SelectedItem 所选专辑 相反

    <phone:LongListSelector x:Name="AlbumList" ItemsSource="{Binding Albums}" 
     SelectedItem="{Binding SelectedAlbum}" />
    

    如果你真的想通过 所选项目 SelectedAlbumCommand (出于其他原因),您应该绑定 CommandParameter 所选项目 LongListSelector

     <i:InvokeCommandAction Command="{Binding DataContext.SelectAlbumCommand, ElementName=ContentPanel}" CommandParameter="{Binding ElementName=AlbumList, Path=SelectedItem}"/>   
    
        2
  •  0
  •   Community Mohan Dere    9 年前

    显然,您不能为此使用LongListSelector。我不得不把它改成一个列表框,而且效果很好。

    如果我更努力地搜索,我会发现: How to select an item in LongListSelector using the MVVM-pattern?

    并且: WP8 LongListSelector SelectedItem not bindable