0

ここにあるのと同じ方法を使用した画像のリストボックスがあります

これは、画像とテキストブロックを持つアイテム テンプレートを含むリスト ボックスです。リストボックスの選択した値を取り戻すにはどうすればよいですか?

そのようです:

string x = listbox.SelectedValue.ToString();

それは私にテキストブロックの価値を与えません。何か案は?

答え:

答えは次のとおりです。

 listboxBinding_Master.Detail.SampleData selectedValue = (listboxBinding_Master.Detail.SampleData)listBox1.SelectedItem;
 string x = selectedValue.ListBoxText;

Sampledata は文字列を定義するために使用したクラスで、ListBoxText は TextBlock の名前です。

4

1 に答える 1

3

ListBox.SelectedValuePathを、必要な値を表す Binded クラスのメンバーの名前に設定します。このようにして、値を取得できるはずですListBox.SelectedValue

編集(例):

<ListBox x:Name="TestListBox" ItemsSource="{Binding}" SelectedValuePath="LastName" MouseDoubleClick="TestListBox_MouseDoubleClick">
  <ListBox.ItemTemplate>
    <DataTemplate>
      <StackPanel Orientation="Horizontal">
        <TextBlock Text="{Binding Path=FirstName}" Width="110" />
        <TextBlock Text="{Binding Path=Age}"/>
      </StackPanel>
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

分離コード:

public partial class MainWindow: Window
  {
    public MainWindow( )
    {
      InitializeComponent( );
      var persons = new System.Collections.ObjectModel.ObservableCollection<Person>();
      persons.Add( new Person( ) { FirstName = "Walter" , LastName = "Bishop" , Age = 63 } );
      persons.Add( new Person( ) { FirstName = "Peter" , LastName = "Bishop" , Age = 33 } );
      persons.Add( new Person( ) { FirstName = "Olivia" , LastName = "Dunham" , Age = 33 } );
      TestListBox.DataContext = persons;
    }
    private void TestListBox_MouseDoubleClick( object sender , MouseButtonEventArgs e )
    {
      if ( TestListBox.SelectedItem != null )
      {
        MessageBox.Show( (string)TestListBox.SelectedValue );
      }
    }
  }

  public class Person
  {
    public string FirstName { get; set; }
    public string LastName{get;set;}
    public int Age { get; set; }
  }
于 2012-03-13T20:26:29.487 に答える