Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/294.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将按钮绑定到UWP中ViewModel中的命令_C#_Uwp - Fatal编程技术网

C# 将按钮绑定到UWP中ViewModel中的命令

C# 将按钮绑定到UWP中ViewModel中的命令,c#,uwp,C#,Uwp,我查阅了两篇类似的文章,但它们都在WPF上,我不太明白如何将datagrid中的按钮绑定到视图模型。我尝试过以下方法: <controls:DataGrid x:Name="DataGrid" ItemsSource="{x:Bind ViewModel.Items}" . . . <Button Command="{Binding ElementName=DataGrid, Path=DataContext.DeleteCommand}" CommandParamete

我查阅了两篇类似的文章,但它们都在WPF上,我不太明白如何将datagrid中的按钮绑定到视图模型。我尝试过以下方法:

<controls:DataGrid x:Name="DataGrid" ItemsSource="{x:Bind ViewModel.Items}"
.
.
. 
<Button 
  Command="{Binding ElementName=DataGrid, Path=DataContext.DeleteCommand}"
  CommandParameter="{Binding}"
/>

通常你会这样做

XAML:


在可视化树中是否有名为DataGrid的元素?如果你有它,它的数据上下文是什么?如果您将ViewModel/代码作为well@Gleb更新了绑定和数据上下文的ViewModel和代码隐藏。DataGrid呢?你真的有一个名为“DataGrid”的DataGrid作为
吗?是的,很抱歉忘了提到,我有一个名为
DataGrid
的元素,它们是在DeleteCommand的同一类中定义的吗?我对您将项目绑定到DataContext.ViewModel.items而将命令绑定到DataContext.DeleteCommand感到困惑。ViewModel类是否具有ViewModel属性?
public RelayCommand<MyClass> DeleteCommand { get; }
public ObservableCollection<MyClass> Items { get; }
public MyViewModel ViewModel { get; }

public MyPage()
{
  ViewModel = new ViewModel();
  this.DataContext = ViewModel;
  this.InitializeComponent();
}
<DataGrid x:Name="DataGrid" ItemsSource="{Binding Items}">
    <DataGrid.Columns>
        <!-- Your biuld-in button -->
        <DataGridTemplateColumn>
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Button Content="Button" Command="{Binding ElementName=DataGrid, Path=DataContext.DeleteCommand}" CommandParameter="{Binding}"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
        <!-- Your other columns -->
    </DataGrid.Columns>
</DataGrid>
public Class MyViewModel: INotifyPropertyChanged
{
    public ObservableCollection<MyClass> Items { get; }

    public RelayCommand<MyClass> DeleteCommand
    {
        get
        {
            return new RelayCommand<MyClass>((o) =>
                {
                    // ...
                });
        }
    }
}
public MyPage()
{
    this.InitializeComponent();
    this.DataContext = new ViewModel();
}