【发布时间】:2020-04-18 13:35:20
【问题描述】:
我刚刚开始使用 WPF 和 MVVM,并设法将我的 Datagrid 绑定到我的 DataContext ViewModel 类的列表 ProductList。但是,我现在正尝试将我的 DataGrid 中的按钮绑定到我的 DataContext 类的一些命令。
<DataGrid x:Name="myDataGrid" ItemsSource="{Binding ProductsList}" x:FieldModifier="public" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="No MAT" Binding="{Binding MATProductNumber}" Width="0.1*"/>
<DataGridTextColumn Header="Format" Binding="{Binding tblFormat.FormatName}" Width="0.1*"/>
<DataGridTextColumn Header="Nom produit" Binding="{Binding tblProduct.ProductName}" Width="0.1*"/>
<DataGridTextColumn x:Name="productGradeHeader" Header="Grade" Binding="{Binding tblGrade.GradeName}" Width="0.1*"/>
<DataGridTemplateColumn Width=".1*"
<DataGridTemplateColumn.HeaderTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Button x:Name="leftArrowSearchButton" Command="{Binding PreviousPageCommand}" CommandParameter="1">
<materialDesign:PackIcon Kind="ArrowLeftThick" Width="25" Height="25" VerticalAlignment="Center"/>
</Button>
<Button x:Name="rightArrowSearchButton" Command="{Binding NextPageCommand}" CommandParameter="1">
<materialDesign:PackIcon Kind="ArrowRightThick" Width="25" Height="25" VerticalAlignment="Center"/>
</Button>
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.HeaderTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
这里的这一行应该在我的数据上下文中绑定到 PreviousPageCommand
<Button x:Name="leftArrowSearchButton" Command="{Binding PreviousPageCommand}" CommandParameter="1" ToolTip="Voir la page précédente" Height="24" Width="53" Margin="0,0,20,0">
我已经调试并发现它甚至没有调用该函数。因此,我几乎可以肯定绑定存在问题。
似乎我的按钮正在尝试绑定到 ProductsList 的元素。有没有办法回到上一级?我已经尝试将我的按钮绑定到 DataContext.PreviousPageCommand
提前致谢!
编辑 1:这里是后端中要求的代码
public ObservableCollection<tblMATProduct> ProductsList { get; set; }
private void NextPageScrollCommand(string number)
{
Page++;
navigate(Page, Size);
}
public void navigate(int page, int size)
{
var result = new ObservableCollection<tblMATProduct>(db.tblMATProduct.Include(s => s.tblGrade).Include(s => s.tblProduct).Include(s => s.tblFormat).OrderBy(s => s.MATProductID).Skip(page * size).Take(size).ToList());
ProductsList = result;
}
ProductsList 正在更新,我可以在调试器中看到它。只是 UI 没有更新。
编辑 2: 现在运行良好!刚刚将此行添加到我的 ProductsList 设置器中:
set
{
SetProperty(ref _products, value);
}
【问题讨论】:
-
你可以绑定Source = mydatagrid.DataContext Path = PreviousPageCommand,基本上绑定到myDataGrid DataContext,也就是你的ViewModel
-
它说它无法读取 myDataGrid,即使我已将其设置为我的 Datagrid 的 x:Name,我还能如何引用它?
-
Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}, Path=DataContext.PreviousPageCommand}"
-
上一页似乎有点奇怪的命令与数据网格中的记录相关联。特定产品的上一页?无论如何。您还需要绑定数据网格的选定项,以便视图模型知道用户单击时按钮所在的行。或者将按钮的数据上下文绑定到命令参数。
-
哇,现在它开始工作了。不能感谢你!如果您想将其发布为答案,我会将其标记为解决方案
标签: c# wpf mvvm mvvm-light icommand