wpf中使用mvvm,解決checkbox全選問題
<DataGrid Name="dataGrid" IsReadOnly="False" Width="600" Height="400" AutoGenerateColumns="False" ItemsSource="{Binding GeneryModelList}" >
<DataGrid.Columns>
<DataGridTemplateColumn Width="150">
<DataGridTemplateColumn.Header>
<CheckBox Command="{ Binding DataContext.SelectOrUnSelectAll,RelativeSource={RelativeSource AncestorType=DataGrid}}" Content="全選"></CheckBox>
</DataGridTemplateColumn.Header>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding IsSelected,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"></CheckBox>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
開始原因是由於並不知道使用資料模板,需要加入資料來源,要找到資料來源的作用域。後面的命令部分程式碼如下:
public ICommand SelectOrUnSelectAll
{
get { return new GeneryModelSoft.Commands.Command(p => SelectAll()); }
}
protected void SelectAll()
{
if (generyModelList != null&&isSelectFlag==false)
{
for (int i = 0; i < generyModelList.Count; i++)
{
generyModelList[i].IsSelected = true;
}
isSelectFlag = true;
}
else if (generyModelList != null && isSelectFlag == true)
{
for (int i = 0; i < generyModelList.Count; i++)
{
generyModelList[i].IsSelected = false;
}
isSelectFlag = false;
}
}