c# - WPF ItemsControl 按钮命令绑定(bind)不起作用

标签 c# wpf mvvm

我有一个 ItemsControl 控件,它有一个 ObservableCollection 作为它的 ItemsSource。它还有一个位于其 DataTemplate 内部的按钮。按钮的 Command 属性绑定(bind)到 ViewModel 中的 RelayCommand(我使用的是 MVVM Light),CommandParameter 绑定(bind)到 ItemsSource 中的相应项目。
问题是由于某种原因,该命令永远不会触发。另一方面,代码隐藏工作正常。在调试鼠标单击事件处理程序时,我可以看到发送方(Button 类型)有一个填充了正确数据的 CommandParameter,而 Command 为空。

我在这里错过了什么?

XAML:

<ItemsControl ItemsSource="{Binding Users}"
              Margin="{StaticResource ContentMargin}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel Orientation="Horizontal" />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Button Margin="{StaticResource ImageButtonMargin}"
                    Style="{StaticResource ImageButtonStyle}"
                    Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}, Path=DataContext.UserSelectedCommand}"
                    CommandParameter="{Binding}">
                    <!--...-->

View 模型:

private ObservableCollection<User> _users;
private RelayCommand<User> _userSelectedCommand;

public ObservableCollection<User> Users
{
    get { return _users; }
    set
    {
        _users = value;
        RaisePropertyChanged();
    }
}

public RelayCommand<User> UserSelectedCommand
{
    get { return _userSelectedCommand; }
}

protected override sealed void SetCommands() // called in the constructor which is in turned called by SimpleIoc
{
     userSelectedCommand = new RelayCommand<User>((user) => UserSeriesSelected(user));
}

private void UserSelected(User selectedUser)
{

}

最佳答案

使用命名元素绑定(bind)作为数据模板中的绑定(bind)源,以访问来自根数据上下文的命令。您可以使用根网格或其他容器作为命名元素。也可以使用 ItemsControl 本身。

<ItemsControl x:Name="MyItems" ItemsSource="{Binding Users}"
              Margin="{StaticResource ContentMargin}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel Orientation="Horizontal" />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Button Margin="{StaticResource ImageButtonMargin}"
                    Style="{StaticResource ImageButtonStyle}"
                    Command="{Binding ElementName=MyItems,  Path=DataContext.UserSelectedCommand}"
                    CommandParameter="{Binding}">
                    <!--...-->

关于c# - WPF ItemsControl 按钮命令绑定(bind)不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32542283/

相关文章:

c# - 短代码正则表达式

c# - 您可以搜索所需的文件,而不是将 Directory.GetFiles() 放入列表中吗?

c# - 如何覆盖 DataGrid 选择行为?

c# - 如何在属性更新后调用方法

c# - 更新目标触发器

c# - 在 C# 中继承构造函数文档?

c# - 在 MembershipUserCollection 上使用 Linq

c# - 为什么自动选择列表框的最后一项?

wpf - telerik 忙指示器不可见

c# - 路径上的Window.DataContext错误不能为null