5 wpf checkbox select datagrid mvvm
我在WPF应用程序中将Caliburn Micro用作MVVM框架。我几乎没有问题如何在datagrid控件中选择所有复选框。每个datagrid行都有一个复选框。
我绑定到列表的datagrid属性类型。
模型:
public class Bill : INotifyPropertyChanged
{
public string CellPhoneNo
{
get { return _cellPhoneNo; }
set
{
_cellPhoneNo = value;
NotifyPropertyChanged("CellPhoneNo");
}
}
public bool IsSelected
{
get { return _isSelected; }
set
{
_isSelected = value;
NotifyPropertyChanged("IsSelected");
}
}
Run Code Online (Sandbox Code Playgroud)
ViewModel:
public IList<Bill> TmobileBill
{
get
{
return _tmobileBill;
}
set
{
_tmobileBill = value;
NotifyOfPropertyChange(()=>TmobileBill);
}
}
Run Code Online (Sandbox Code Playgroud)
视图:
<Controls:DataGrid ItemsSource="{Binding Path= TmobileBill,
Mode=OneWay,
UpdateSourceTrigger=PropertyChanged}"
Style="{StaticResource FinalBillsView_CallsDataGrid}"
Grid.Row="0"
CanUserResizeRows="False">
<Controls:DataGrid.RowHeaderTemplate>
<DataTemplate>
<Grid>
<CheckBox IsChecked="{Binding Path=IsSelected, Mode=TwoWay,
RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type Controls:DataGridRow}}}"/>
</Grid>
</DataTemplate>
</Controls:DataGrid.RowHeaderTemplate>
<Controls:DataGrid.Columns>
<Controls:DataGridTextColumn IsReadOnly="True"
CellStyle="{StaticResource FinalBillsView_DataGrid_CellStyle}"
Binding="{Binding Path=CellPhoneNo}"
HeaderStyle="{StaticResource FinalBillsView_DataGridColHeaderStyle}"
Header="Cell phone No"/>
</Controls:DataGrid.Columns>
</Controls:DataGrid>
Run Code Online (Sandbox Code Playgroud)
在datragrid行的datatemplate中,我绑定了checbox属性IsChecked属性IsSelected(来自Bill类)。
<Controls:DataGrid.RowHeaderTemplate>
<DataTemplate>
<Grid>
<CheckBox IsChecked="{Binding Path=IsSelected, Mode=TwoWay,
RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type Controls:DataGridRow}}}"/>
</Grid>
</DataTemplate>
</Controls:DataGrid.RowHeaderTemplate>
Run Code Online (Sandbox Code Playgroud)
问题是如果我将列表中的所有项目的属性IsSelected设置为true。
foreach (var row in TmobileBill)
{
row.IsSelected = true;
}
Run Code Online (Sandbox Code Playgroud)
未选中“视图”中的复选框。问题的根源是什么?
谢谢。
IList<Bill>为ObservableCollection<Bill><CheckBox IsChecked="{Binding Path=IsSelected, Mode=TwoWay}"/>出于调试目的,定义 CheckBox 下一个控件以查看实际绑定到 RowItem 的内容:
<TextBlock Text="{Binding}"></TextBlock>
Run Code Online (Sandbox Code Playgroud)