当我通过DataContext
修改值来设置CheckBox
的数据时,为什么向下或向上滚动时返回原始值?有办法恢复吗?
当我向下或向上滚动时,我希望它不会将复选框返回到原始值。
XAML代码
<DataGrid x:Name="list_account_instagram"
Background="#DDDDDD"
CanUserResizeColumns="False"
CanUserSortColumns="False"
CanUserAddRows="False">
<DataGrid.Columns>
<materialDesign:DataGridTextColumn Width="0.4*"
Binding="{Binding STT}"
Header="#" />
<DataGridCheckBoxColumn Width="0.35*" Binding="{Binding CHECK, Mode=OneTime}">
<DataGridCheckBoxColumn.Header>
<Border Background="Transparent">
<CheckBox Name="checkallins" Click="Checkallins_Click"/>
</Border>
</DataGridCheckBoxColumn.Header>
</DataGridCheckBoxColumn>
<materialDesign:DataGridTextColumn Binding="{Binding UID}" Width="*"
Header="UID" />
<materialDesign:DataGridTextColumn Binding="{Binding PASSWORD}" Width="*"
Header="Password"/>
<materialDesign:DataGridTextColumn Binding="{Binding COOKIE}" Width="*"
Header="Cookie"/>
<materialDesign:DataGridTextColumn Binding="{Binding TEN}" Width="*"
Header="Tên"/>
<materialDesign:DataGridTextColumn Binding="{Binding AVATAR}" Width="*"
Header="Avatar"/>
<materialDesign:DataGridTextColumn Binding="{Binding TT}" Width="*"
Header="Tình Trạng"/>
<materialDesign:DataGridTextColumn Binding="{Binding MESSAGE}" Width="*"
Header="Trạng Thái"/>
</DataGrid.Columns>
</DataGrid>
c#
private void Checkallins_Click(object sender, RoutedEventArgs e)
{
if (checkallins.IsChecked.Value)
{
if (list_account_instagram.Items.Count > 0)
{
for (int i = 0; i < list_account_instagram.Items.Count; i++)
{
GetCell(list_account_instagram, i, 1).DataContext = new { CHECK = true };
}
}
}
else
{
if (list_account_instagram.Items.Count > 0)
{
for (int i = 0; i < list_account_instagram.Items.Count; i++)
{
GetCell(list_account_instagram, i, 1).DataContext = null;
GetCell(list_account_instagram, i, 1).DataContext = new { CHECK = false };
}
}
}
}
为了更好地描述有问题的行为,有视频:https://files.fm/u/2xxgqrqra#/view/p4jw246e3
问题与使用OneTime
绑定有关. 这将导致数据只在初始化期间加载,但在任何更改(无论是UI还是代码)之后,它都不会影响集合本身。
当你在"ui"中看到不同的东西时,这会导致问题。在"代码背后"有不同的东西。如果您调试实际值(当按下DataGrid
的header时),您会惊讶于这些值是从哪里来的。
修复很简单,你必须更新Binding
模式。而不是:
Binding="{Binding CHECK, Mode=OneTime}">
你应该使用:
Binding="{Binding CHECK}">
<!-- or this -->
Binding="{Binding CHECK, Mode=TwoWay}">
编辑:从OP的评论来看,问题还在于为DataGrid
中的项目设置bool
值。您不应该在那里分配新对象,而应该使用DataGrid
的DataContext
。您可以这样做:
var isChecked = checkallins.IsChecked.Value;
foreach(var item in list_account_instagram.Items)
{
// Put instead of `MyClass` actual class you are using (prob. `InstagramAccount`)
var myItem = item as MyClass;
if(item != null)
{
myItem.CHECK = isChecked;
}
}