【发布时间】:2019-08-14 08:24:35
【问题描述】:
在我的应用程序中,我使用MVVM 模式。我已将 DataContext 设置为我的 ViewModel 并声明了 CollectionViewSource:
<CollectionViewSource x:Key="collectionView"
Source="{Binding FiltredDataGridItems, Mode=TwoWay}">
<CollectionViewSource.GroupDescriptions>
<PropertyGroupDescription PropertyName="Parent.Name"/>
</CollectionViewSource.GroupDescriptions>
</CollectionViewSource>
我使用这个CollectionViewSource 作为我的DataGrid ItemsSource
<DataGrid AutoGenerateColumns="False"
ItemsSource="{Binding Source={StaticResource collectionView}}">
</DataGrid>
它工作正常,但我想使用在我的 ViewModel 中声明的ICommand
<DataGridTemplateColumn >
<DataGridTemplateColumn.Header>
<CheckBox x:Name="SelectAll"
Content="Select All">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Checked">
<i:InvokeCommandAction Command="{Binding CheckAllCommand}"/>
</i:EventTrigger>
<i:EventTrigger EventName="UnChecked">
<i:InvokeCommandAction Command="{Binding UnCheckAllCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</CheckBox>
</DataGridTemplateColumn.Header>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding IsSelected,
Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
我得到了这些错误
System.Windows.Data Error: 40 : BindingExpression path error: 'CheckAllCommand' property not found on 'object' ''CheckBox' (Name='SelectAll')'. BindingExpression:Path=CheckAllCommand; DataItem='CheckBox' (Name='SelectAll'); target element is 'InvokeCommandAction' (HashCode=39571581); target property is 'Command' (type 'ICommand')
System.Windows.Data Error: 40 : BindingExpression path error: 'UnCheckAllCommand' property not found on 'object' ''CheckBox' (Name='SelectAll')'. BindingExpression:Path=UnCheckAllCommand; DataItem='CheckBox' (Name='SelectAll'); target element is 'InvokeCommandAction' (HashCode=15035499); target property is 'Command' (type 'ICommand')
你们能帮帮我吗?如何从我的视图模型中访问命令
编辑:
我已经通过继承 BasePage 声明了 DataContext
public partial class LoginPage : BasePage<LoginViewModel>
BasePage 实现
public class BasePage<VM> : Page
where VM : BaseViewModel, new()
{
public VM ViewModel
{
get => _ViewModel;
set
{
if (_ViewModel == value)
return;
_ViewModel = value;
DataContext = _ViewModel;
}
}
public BasePage()
{
ViewModel = new VM();
}
}
【问题讨论】:
-
命令绑定在
collectionView项目中寻找命令,而不是在整个视图模型中。您已为列设置数据上下文或使用相对源绑定。你能用命令分享你的 ViewModel 吗?并将其设置为DataContext -
我的命令现在只实现输出到控制台,因为我想弄清楚如何获得访问权限。而且我的 DataContext 可以在我的页面的其他元素上工作,而不是在 DataGrid 中。
-
@PavelAnikhouski 我编辑问题并展示实现。
-
check和uncheck命令在哪里声明,page with grid的数据上下文是什么?