c# - 绑定(bind)到 ItemsControl 内的 Window.DataContext.ViewModelCommand

标签 c# .net wpf

我有一些窗口,例如:

<Window>
    <ItemsControl ItemsSource="{Binding MyItemList}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Button Command="{Binding ViewModelCommand}">My Button</Button>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</Window>

此窗口具有使用以下实例定义的 DataContext 属性:

public class MyVM
{
    public IEnumerable<FooType> MyItemList { get; set; }
    public ICommand ViewModelCommand { get; set; }
}

问题是 Button.Command 绑定(bind)不起作用。我猜测问题是因为我的按钮位于 ItemsControl 内部,因此绑定(bind)正在 FooType 对象内部查找 ViewModelCommand

那么我怎样才能正确绑定(bind)呢?

最佳答案

DataTemplate 内的 DataContext 将是 FooType 项;这就是 ItemTemplate 的用途:显示每个项目。

关于c# - 绑定(bind)到 ItemsControl 内的 Window.DataContext.ViewModelCommand,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37040712/

相关文章:

c# - 不传输文件的FileUpload

c# - 具有通用属性的类必须是通用的?

javascript - 是否可以使用 SignalR 传递函数?

c# - 如何在动态生成的C#代码中初始化各种类型变量?

c# - WPF 应用程序在第一次交互后停止/卡住,例如单击按钮

WPF 数据模板 - x :Key vs DataType ="{x:Type XXXX")

c# - 从托管代码调用 native 函数

c# - 链接到 C# GUI 的 C++ 程序

c# - PayU 集成网络服务 URL

c# - WPF DataGrid 上下文菜单绑定(bind)