C# 将按钮绑定到UWP中ViewModel中的命令
我查阅了两篇类似的文章,但它们都在WPF上,我不太明白如何将datagrid中的按钮绑定到视图模型。我尝试过以下方法: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
<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();
}