【问题标题】:Binding to a ListBox SelectedItem绑定到 ListBox SelectedItem
【发布时间】:2014-06-16 12:51:15
【问题描述】:

我有一个窗口,左侧是 ListBox,右侧是 TextBox。文本框绑定到列表框的选定项。文本框有一个 SaveContentCommand。

如果您使用 Enter 或 Tab 离开文本框,则 SaveContentCommand 将正确执行。但是,如果我使用鼠标选择其他内容,则所选项目会被更改,然后执行 SaveContentCommand。这意味着 SaveContentCommand 用于另一个项目。

我试图破解类似 RenameLastSelectedItem() 但是有没有正确/更好的方法?

我的清单:

<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}">

我的文本框:

<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}"

【问题讨论】:

  • 你能发布你的绑定语法吗?
  • 您是如何执行 SaveContentCommand 的?
  • 是的,因为您的 Selected Item 与 Textbox 绑定,因此当您的 SelectedItem 更改时,您的文本框内容更改并且 SaveContentCommand 触发
  • 我知道,但我认为 savecontent 应该在更改所选项目之前执行。
  • 在 selecteditem 更改 savecontent 调用后没有。这是正确的流程

标签: c# wpf mvvm binding selecteditem


【解决方案1】:

在SelectedItem的set方法中,保存上一项。当使用鼠标选择新项目时更改所选项目时,此代码将运行..

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

【讨论】:

  • 这个 defentley 工作,但它看起来不是一个非常干净的解决方案:)
猜你喜欢
  • 2010-12-26
  • 2011-01-02
  • 2019-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-26
  • 2011-02-01
  • 1970-01-01
相关资源
最近更新 更多