在DataTemplate

时间:2015-08-04 03:26:11

标签: windows-store-apps winrt-xaml prism

我想我在Prism for Windows Runtime图书馆中发现了一个错误,但我想知道是否有解决问题的方法或解决问题的方法自己...

我试图在ItemsControl中显示项目列表。每个项目都有一个按钮,单击该按钮时,应在父控件的数据上下文中执行命令,并将项目ID作为命令参数传递。基本上,我尝试渲染项目列表并为每个项目设置删除按钮。为了实现这一目标,我跟随code sample,我迄今为止发现这是实现这一壮举的唯一干净方法。

不幸的是,Prism for Windows Runtime实现的DelegateCommand<T>类似乎与XAML绑定解析器不兼容。当所有东西都连接起来时,我在页面尝试渲染时收到此异常:

  

无法分配给属性&#39; Windows.UI.Xaml.Controls.Primitives.ButtonBase.Command&#39;。 [线:61位置:49]

我创建了一个新项目并简化了我的生产示例以测试我的理论,这是DelegateCommand<T>的问题(需要将参数传递给委托方法)。我实现了两个命令,一个使用DelegateCommand<T>,另一个使用DelegateCommand。使用DelegateCommand的人不会导致异常,但我无法接受命令参数,这意味着我无法识别要删除的项目。

XAML:

<ItemsControl Name="TestControl" Grid.Row="1" ItemsSource="{Binding MyItems}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Button Content="{Binding}" Command="{Binding DataContext.BrokenCommand, ElementName=TestControl}" CommandParameter="1" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

视图模型:

public DelegateCommand<int> BrokenCommand { get; set; }
public DelegateCommand WorkingCommand { get; set; }

public List<string> MyItems { get { return new List<string> {"A", "B", "C"}; } }

public MainPageViewModel(INavigationService navigationService)
{
    BrokenCommand = new DelegateCommand<int>(BrokenMethod);
    WorkingCommand = new DelegateCommand(WorkingMethod);
}

private void BrokenMethod(int i)
{
    throw new NotImplementedException();
}

private void WorkingMethod()
{
    throw new NotImplementedException();
}

2 个答案:

答案 0 :(得分:1)

我从另一个答案得到一点启发后,终于完成了这项工作。我不知道为什么,但委托命令的属性签名导致了异常。将DelegateCommand<int>更改为DelegateCommand<object>会使一切正常。现在我可以将对象转换为int并从那里开始。如果有人能解释为什么会出现这个问题,那就太棒了!

XAML:

<ItemsControl Name="TestControl" Grid.Row="1" ItemsSource="{Binding MyItems}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Button Content="{Binding}" Command="{Binding DataContext.WorkingCommand, ElementName=TestControl}" CommandParameter="1"></Button>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

查看型号:

public DelegateCommand<object> WorkingCommand { get; set; }

public List<string> MyItems { get { return new List<string> {"A", "B", "C"}; } }

public MainPageViewModel()
{
    WorkingCommand = new DelegateCommand<object>(WorkingMethod);
}

private void WorkingMethod(object id)
{
    throw new NotImplementedException();
}

答案 1 :(得分:0)

试试这个

    BrokenCommand = new DelegateCommand<string> 
    (id => BrokenMethod(Convert.ToInt32((id));

我刚测试了它,如果你将T改为字符串,它就可以工作了。

希望有人可以解释原因:)