如何将列表框selecteditem内容绑定到文本框?

Max*_*Max 12 linq wpf binding

当TextName内容发生变化时,我有一个列表框可以通过此查询绑定:

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

listNames.ItemsSource = players.ToList();
Run Code Online (Sandbox Code Playgroud)

它显示了以文本框中的文本开头的玩家名称.现在,当我从列表框中单击任何项​​目(名称)时,我需要TextName显示在列表框中选择的玩家名称.我试着用这种方式绑定它:

<TextBox ... Text="{Binding Source=listNames, Path=SelectedItem.Content}" ... />
Run Code Online (Sandbox Code Playgroud)

但是,当我单击一个ListboxItem时,文本框才会被清除,并且不会显示任何内容..在设置DisplayMemeberPath时,我是否必须像设置列表框一样设置文本框?我只需要单向绑定!! 我能做什么??

Ste*_*rex 19

绑定有2个问题:

  1. 您正在使用Source属性而不是ElementName来指定列表框名称
  2. 您正在尝试绑定到您的Player对象上不存在(我假设)的Content属性.这是因为SelectedItem财产ListBox是一个实例Player,当你指定ItemsSource你有

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

<TextBox ... Text="{Binding ElementName=listNames, Path=SelectedItem.GivenName}" ... />
Run Code Online (Sandbox Code Playgroud)