1
在我的ViewModel中,我拥有包含Observable Collection of Cards的基类和Deck类。下面是它是如何在XAML绑定通过MVVM命令访问集合
<GridView ItemsSource="{Binding DeckCollection}" IsItemClickEnabled="True" Grid.Row="0">
<GridView.ItemTemplate>
<DataTemplate>
<Button Command="{Binding Path=??}"
CommandParameter=??
<Button.Content>
<Grid>
<Image
Source="{Binding ImagePath}"
Stretch="None"/>
</Grid>
</Button.Content>
</Button>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
这里是我的班
class Deck
{
private ObservableCollection<Card> _deckCollection = new ObservableCollection<Card>();
public ObservableCollection<Card> DeckCollection
{
get { return _deckCollection; }
set { _deckCollection = value; }
}
public Deck()
{
ActionCommand = new MyCommand();
ActionCommand.CanExecuteFunc = obj => true;
ActionCommand.ExecuteFunc = AddToList;
}
public void AddToList(object parameter)
{
var clickedCard = this;
//add Card to list which in this case is not possible
//DeckCollection.Add(this) ?
}
}
class Card
{
public String Name { get; set; }
public int Cost { get; set; }
public String ImagePath { get; set; }
public MyCommand ActionCommand { get; set; }
}
而且还mycommand的类
public class MyCommand : ICommand
{
public Predicate<object> CanExecuteFunc { get; set; }
public Action<object> ExecuteFunc { get; set; }
public bool CanExecute(object parameter)
{
return CanExecuteFunc(parameter);
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
ExecuteFunc(parameter);
}
}
我做了修改建议,但现在ActionCommand不中可见集合,因为只有属于Card类的属性才能绑定。
编辑:我改变了我的XAML文件下却得到了一些错误
<Button Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:Deck}, Path=ActionCommand}}">
属性“AncestorType”型“的RelativeSource”没有被发现。
在'RelativeSource'类型中未找到'Path'属性。
成员“AncestorType”未被识别或无法访问。
成员“路径”未被识别或无法访问。
未知的成员元素“AncestorType“的RelativeSource”
未知的成员“路径”元素“的RelativeSource”
请帮
XAML的视图模型在哪里? CardCollection是在哪里定义的?从概念上讲,如果你有一个卡类,并且正在调用一个“添加到列表”的方法,我希望你将它传递给一个列表,否则该卡怎么知道要添加到什么地方?更合理的做法是在名单上添加一个名为“添加卡”的方法,通过卡片。尽管这两种方法都需要通过视图模型进行管理,视图模型正在协调这些操作。 – Mashton
我在代码中做了很多更改,现在我看到我离开了CardCollection,而不是将其更改为DeckCollection。所以基本上我的Deck类是我的ViewModel,它直接绑定为GridView中的ItemSource – user2847238
好了。那么让命令在你的viewmodel(deck)上作为一个命令并且作为命令的一个参数指定这个卡(或者在VM上有一个SelectedCard属性)。然后以这种方式添加到您的列表 - 从卡组中使用卡,而不是其他方式。 – Mashton