在WPF中,我有一个DataGrid
绑定到DataView
类的ViewModel
。这是一个触摸面板嵌入式项目,因此每当我触摸并滑动面板时,它会不断向我发送值并将这些值保存到DataTable
并将其分配给绑定的DataView
,其中它只能显示5或10数据更新时的行(预定义)。每当我得到一个新行时,我会删除最后一行,直到总DataTable
行数为5/10。
这里的问题是,DataGrid
需要比平时更长的时间来绑定最后的值。当我将手从面板上抬起时,我希望网格绑定到这些值,但是用户必须等待它完成此操作需要大约6到10秒。
为此,我在IsAysnc
使用了XAML
属性。正如预期的那样,这使得DataGrid
快速绑定,但每次数据更新时,DataGrid
都会闪烁。我怎样才能克服DataGrid
中的闪烁问题?或者还有其他方法可以做到这一点。我们遵循MVVM模式进行绑定。提前致谢。
XAML:
<DataGrid Grid.Row="1" HorizontalAlignment="Center"
VerrticalAlignment="Top" Height="Auto" Width="Auto"
BorderThickness="1" BorderBrush="Black" ColumnHeaderHeight="35"
RowHeight="30" HorizontalContentAlignment="Center"
VerticalContentAlignment="Center"AlternationCount="2"
AlternatingRowBackground="WhiteSmoke"CanUserSortColumns="False"
CanUserResizeRows="False" HorizontalScrollBarVisibility="Hidden"
VerticalScrollBarVisibility="Hidden"ItemsSource="{Binding Path =
View,IsAsync=True,UpdateSourceTrigger=PropertyChanged}"
Margin="0,20,0,0"AutoGenerateColumns="True" EnableColumnVirtualization="True"
EnableRowVirtualization="True" CanUserAddRows="False" >
查看型号:
private void InsertCollection(List<string> values)
{
if (values == null || !values.Any()) return;
try
{
var dataRow = ObjectMessageDataTable.NewRow();
int columnCount = ObjectMessageDataTable.Columns.Count;
var inputs = values.Select(y => y as object).ToArray();
for (var i = 0; i < inputs.Count() && i < columnCount; i++)
dataRow[i] = values[i];
ObjectMessageDataTable.Rows.InsertAt(dataRow, 0);
var count = ObjectMessageDataTable.Rows.Count;
while (count > NumOfRows)
{
ObjectMessageDataTable.Rows.RemoveAt(NumOfRows);
count = ObjectMessageDataTable.Rows.Count;
}
ObjectMessageDataTable.AcceptChanges();
View = ObjectMessageDataTable.DefaultView;
}
catch (Exception ex)
{
}
}
我试过你的代码。直接对数据表进行数据绑定非常简单,闪烁就会消失:)。只需使用ObjectMessageDataTable.DefaultView而不是View。因为每次创建View时都会创建View对象本身,这会导致datagrid从头开始初始化。
ItemsSource="{Binding Path=ObjectMessageDataTable.DefaultView, IsAsync=True, UpdateSourceTrigger=PropertyChanged}"
所以改为
<DataGrid
Grid.Row="1"
Width="Auto"
Height="Auto"
Margin="0,20,0,0"
HorizontalAlignment="Center"
VerticalAlignment="Top"
HorizontalContentAlignment="Center"
VerticalContentAlignment="Center"
AlternatingRowBackground="WhiteSmoke"
AlternationCount="2"
AutoGenerateColumns="True"
BorderBrush="Black"
BorderThickness="1"
CanUserAddRows="False"
CanUserResizeRows="False"
CanUserSortColumns="False"
ColumnHeaderHeight="35"
EnableColumnVirtualization="True"
EnableRowVirtualization="True"
HorizontalScrollBarVisibility="Hidden"
ItemsSource="{Binding Path=ObjectMessageDataTable.DefaultView, IsAsync=True, UpdateSourceTrigger=PropertyChanged}"
RowHeight="30"
VerticalScrollBarVisibility="Hidden" />
希望能帮助到你。