2

我有两个datagrid'(主/细节)。我DispatcherTimer每 5 秒刷新一次窗口。当我在我的主网格上选择任何行时,所选行上的焦点仅保留那 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">
4

1 回答 1

3

嗨,您需要在致电之前保留 DataGrid 的 SelectedItem

serversViewSource.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();
    }
于 2013-03-15T15:22:17.103 回答