我有两个datagrid'
s(Master / detaiL)。我每隔5秒使用DispatcherTimer
刷新一次窗口。当我选择主网格上的任何一行时,所选行的焦点仅保留5秒,之后选择焦点移动到最顶行。
如何在XAML中克服这个问题?
修改
public partial class MyWindow : Window
{
ProdEntities _prodEntities = new ProdEntities();
public MyWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
try
{
RebindData();
SetTimer();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private void SetTimer()
{
DispatcherTimer dispatcherTimer = new DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0, 0, 5);
dispatcherTimer.Start();
}
protected void dispatcherTimer_Tick(object sender, EventArgs e)
{
RebindData();
}
private void RebindData()
{
CollectionViewSource serversViewSource = (CollectionViewSource)(FindResource("serversViewSource"));
IQueryable<Server> serversQuery = this.GetServersQuery(_prodEntities );
serversViewSource.Source = serversQuery.ToList();
//serversViewSource.View.Refresh();
}
private IQueryable<Server> GetServersQuery(ProdEntities _prodEntities)
{
var serversQuery = _prodEntities.Servers.Where(c => c.Components.Any());
return serversQuery;
}
private void SaveChanges_Click(object sender, RoutedEventArgs e)
{
_prodEntities.SaveChanges();
}
}
XAML
<DataGrid AutoGenerateColumns="False" Foreground="DarkBlue" DataContext="StaticResource serversComponentsViewSource}"
ItemsSource="{Binding}" Name="componentsDataGrid">
答案 0 :(得分:3)
您需要在调用
之前保留DataGrid的SelectedItemserversViewSource.Source = serversQuery.ToList();
然后将其分配回该DataGrid的SelectedItem。但是,在将该对象分配回SelectedItem之前,您必须在Collection中找到与保留的SelectedItem具有相同值的项目。
private void RebindData()
{
CollectionViewSource serversViewSource = (CollectionViewSource)(FindResource("serversViewSource"));
var selectedItem = (Server)componentsDataGrid.SelectedItem;
IQueryable<Server> serversQuery = this.GetServersQuery(_prodEntities);
serversViewSource.Source = serversQuery.ToList();
foreach (var item in (IEnumerable<Server>)serversViewSource.Source )
{
if (selectedItem.PropName == item.PropName)//Compare the values here
{
componentsDataGrid.SelectedItem = item;
break;
}
}
//serversViewSource.View.Refresh();
}