wpf - 如何将列表框选定的项目内容绑定(bind)到文本框?

标签 wpf linq binding

当 TextName 内容更改时,我有一个列表框被此查询绑定(bind):

var players =
    from p in context.Player
    where p.GivenName.StartsWith(TextName.Text.Trim())
    select p;

listNames.ItemsSource = players.ToList();

它显示以文本框中的文本开头的玩家姓名。现在,当我从列表框中单击任何项​​目(名称)时,我需要 TextName 显示在列表框中选择的玩家名称。我尝试这样绑定(bind)它:

<TextBox ... Text="{Binding Source=listNames, Path=SelectedItem.Content}" ... />

但是当我单击 ListboxItem 时,文本框只是被清除并且不显示任何内容。我是否必须像设置 DisplayMemeberPath 时对列表框所做的那样设置文本框???我需要一种单向绑定(bind)! 我能做什么??

最佳答案

您的绑定(bind)有 2 个问题:

  1. 您正在使用 Source 属性而不是 ElementName 来指定列表框名称
  2. 您正在尝试绑定(bind)到您的 Player 对象上不存在的 Content 属性(我假设)。发生这种情况是因为当您指定 ItemsSource 时,ListBoxSelectedItem 属性是 Player 的实例

要解决此问题,您应该将绑定(bind)更改为以下内容:

<TextBox ... Text="{Binding ElementName=listNames, Path=SelectedItem.GivenName}" ... />

关于wpf - 如何将列表框选定的项目内容绑定(bind)到文本框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7504361/

相关文章:

c# - 寻找最小值时避免魔数(Magic Number)

c# - Linq 在 C# Lambda 表达式中使用 Distinct()

WPF:绑定(bind)到 ComboBox SelectedItem

c# - TreeViewItem 中的背景不是全宽

c# - 从另一个集合更新 ObservableCollection

c# - 与 LINQ 中的集合集合相交

c# - 动态生成列 mvvm

c# - RegisterPointerInputTarget() 函数给出 false

c# - 当 ViewModel 改变时如何让 View 更新

wpf - 如何将对象 bool 属性绑定(bind)到 CheckBox IsChecked 属性?