简体   繁体   中英

Binding to a ListBox SelectedItem

I have a Window with ListBox on the left Side and TextBox on the right Side. The Textbox is binding to the Selected Item of the ListBox. The Textbox has a SaveContentCommand.

If you leave the Textbox with Enter or the Tab the SaveContentCommand is executed correct. But if i use the mouse to select something else the selecteditem is changed and then the SaveContentCommand is executed. This means the SaveContentCommand is used on another item.

I have tried to hack something like RenameLastSelectedItem() But is there a correct/better way?

My List:

<customControls:MyListBox x:Name="UserListBox"
                          Grid.Row="1" 
                          Grid.Column="0" 
                          ItemsSource="{Binding Users}" 
                          SelectedItem="{Binding SelectedItem, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" 
                          VerticalAlignment="Top" 
                          Style="{DynamicResource MyListBoxStyle}" 
                          ItemContainerStyle="{DynamicResource MyListBoxItemUserListStyle}">

My TextBox:

<customControls:MyTextBox   x:Uid="textBoxName"
                            x:Name="textBoxNameOfSelectedItems"
                            Text="{Binding SelectedItem.Name, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=true, Mode=TwoWay}"
                            focus:FocusExtension.IsFocused="{Binding SelectedItem.IsNameFocused, Mode=TwoWay}"
                            focus:FocusExtension.EnableSelection="True"
                            UseKeyboardBinding="true"
                            Style="{DynamicResource MyTextBoxStyle}"
                            SaveContentCommand="{Binding SelectedItem.UpdateCommand}"

In the set method of the SelectedItem, save the previous item. This code will run when the selected item is changed when selecting a new item with the mouse..

SelectedItem
{get { return _selectedItem;}  
 set 
 {
  //null check
  SaveContent(_selectedItem);
  _selectedItem = value;
 }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM