开发者

How to fix selected Item in a collection control on a user control (using the MVVM implementation) in WPF

开发者 https://www.devze.com 2022-12-17 11:26 出处:网络
I hope someone can help me... Josh Smith did a great article on \"WPF apps with the Model-View View-Model\", and included in his article was the following code sample.

I hope someone can help me...

Josh Smith did a great article on "WPF apps with the Model-View View-Model", and included in his article was the following code sample.

If you download the code sample and run the app and view all customers, then select a company (e.g. 4th company), then click "Create new customer" (which will open a tab of the new customer), and then click back on the "A开发者_运维技巧ll Customers" tab, and then using the keyboard try and move the selected item up one to the item directly over the current selected item, it doesn't! Instead the selector starts at the top again.

I am not sure why this happens, but I want it so that when you click up, it goes one item up, rather than starting at the top of the list. I suspect this has to do with FocusManager, but am not sure.

Does anyone know why the control behaves in this manner? Is it possible, and what approach I should take to modify this code and get it to not "reset" the selected item?

I have implemented a project based off this template and for functionality reasons I need to get the keyboard to move the selector up & down without it resetting.


in the example you've provided setting IsSelected property does not affect the logical focus so the focus is set by default. Workaround I have in mind currently is to force focus for the element in codebehind. As an example add handler to selectionchanged of the listview like this:

  private void ListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
  {
    if (e.AddedItems.Count == 0 || e.RemovedItems.Count > 0) return;
    var item = (CustomerViewModel) e.AddedItems[0];
    var container = (UIElement) listView1.ItemContainerGenerator.ContainerFromItem(item);
    container.Focus();
  }
0

精彩评论

暂无评论...
验证码 换一张
取 消