c# - 使用 MVVM 模式将项目添加到集合

标签 c# wpf xaml mvvm

我正在从附加到每个项目的命令中访问 ObservableCollection(这是我的 ItemsSource)。

我正在尝试制作两个列表,一个包含所有对象,第二个包含用户选择的对象。

这是我的 View 模型。

class ViewModel : VMBase
{
    private ObservableCollection<Card> _cardsCollection;
    public ObservableCollection<Card> CardsCollection
    {
        get { return _cardsCollection; }
        set { _cardsCollection = value; }
    }

    static private ObservableCollection<Card> _pickedCards;
    static public ObservableCollection<Card> PickedCards
    {
        get { return _pickedCards; }
        set { _pickedCards = value;
              NotifyPropertyChanged("PickedCards");
            }
    }
}
class Card : VMBase
{
    public string Name { get; set; }
    public Card(string name, int cost, CardType type, CardRarity rarity)
    {
        this.Name = name;
        this.BackgroundImage = String.Format("/Images/Cards/{0}.png", name);

        this.PickCardCommand = new MvvmCommand();
        this.PickCardCommand.CanExecuteFunc = obj => true;
        this.PickCardCommand.ExecuteFunction = PickCard;
    }
    public MvvmCommand PickCardCommand { get; set; }
    public void PickCard(object parameter)
    {
        PickedCards.Add(currentCard); 
        //Above Does not work, not accessible
        CreateDeckModel.PickedCards.Add(currentCard);
        //Above does work but only if Collection is static
        //but if collection is static I am unable to call NotifyPropertyChanged()
    }
}

这是我的带有绑定(bind)的 XAML 文件
<GridView Grid.Row="1" ItemsSource="{Binding CardsCollection, Mode=TwoWay}">
     <GridView.ItemTemplate>
         <DataTemplate>
             <Grid>
                  <Button Height="258" Width="180" Content="{Binding}" Margin="0,0,0,0" 
                          Command="{Binding PickCardCommand}" CommandParameter="{Binding}">
                      <Button.Template>
                          <ControlTemplate>
                              <StackPanel Orientation="Vertical">
                                  <Border BorderThickness="2" BorderBrush="White" Height="258" Width="180">
                                      <Border.Background>
                                          <ImageBrush ImageSource="{Binding BackgroundImage}" />
                                      </Border.Background>
                                   </Border>
                              </StackPanel>
                          </ControlTemplate>
                       </Button.Template>
                   </Button>
               </Grid>
           </DataTemplate>
       </GridView.ItemTemplate>
   </GridView>

这是我的 MvvmCommand 类
class MvvmCommand : ICommand
{
    public Predicate<object> CanExecuteFunc { get; set; }
    public Action<object> ExecuteFunction { get; set; }
    public void Execute(object parameter)
    {
        ExecuteFunction(parameter);
    }

    public event EventHandler CanExecuteChanged;
    public bool CanExecute(object parameter)
    {
        return CanExecuteFunc(parameter);
    }
}

}

有没有办法从 Item 或 DataContext 访问 ItemsSource 或者使 ViewModel 类可以访问命令?

最佳答案

您可以通过将 xaml 文件中的按钮更改为以下内容,将 Command 指向您的 ViewModel 类:

<Button Height="258" Width="180" Content="{Binding}" Margin="0,0,0,0" Command="{Binding DataContext.PickCardCommand,RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type vw:ViewClass}}}" CommandParameter="{Binding}">

在 RelativeSource 绑定(bind)中,您需要更改以下内容:

大众 是您的 View 的命名空间,这必须与您的 xaml 文件中的其他命名空间一起声明。

查看类 是你类(class)的名字。

然后,您显然需要将 Command 从 Card 类移至 ViewModel 类。

window 电话
<GridView x:Name="myGridView" Grid.Row="1" ItemsSource="{Binding CardsCollection, Mode=TwoWay}">
     <GridView.ItemTemplate>
         <DataTemplate>
             <Grid>
                  <Button Height="258" Width="180" Content="{Binding}" Margin="0,0,0,0" 
                          Command="{Binding ElementName=myGridView,
                   Path=DataContext.PickCardCommand}" CommandParameter="{Binding}">
                      <Button.Template>
                          <ControlTemplate>
                              <StackPanel Orientation="Vertical">
                                  <Border BorderThickness="2" BorderBrush="White" Height="258" Width="180">
                                      <Border.Background>
                                          <ImageBrush ImageSource="{Binding BackgroundImage}" />
                                      </Border.Background>
                                   </Border>
                              </StackPanel>
                          </ControlTemplate>
                       </Button.Template>
                   </Button>
               </Grid>
           </DataTemplate>
       </GridView.ItemTemplate>
   </GridView>

您会看到我现在已经命名了 GridView,然后在绑定(bind)中使用了 GridView 的名称作为 ElementName。我相信这应该有效。

关于c# - 使用 MVVM 模式将项目添加到集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28563660/

相关文章:

wpf - App.xaml 中的合并字典

c# - IHttpHandler Response.ContentType = "application/pdf"在 IE8 中损坏

c# - 未创建 MySQL Entity Framework 表

wpf - 在 Blend 设计时使用 Moq

c# - 空 TextBox 上的 int 验证失败

WPF - 将 RadioButton 样式设置为 ToggleButton 有效,但在 VS 中显示错误

c# - 如何从 StreamGeometry 中提取 Point 对象?

c# - Task.Run 下是否需要await/async 关键字?

c# - 当我打开 Excel 时出现第二个 Excel 插件(功能区)安装,为什么?

c# - 带有所有者的 MVVM showDialog 并在后台工作人员完成时关闭