Note that there are some explanatory texts on larger screens.

plurals
  1. POGet name of selected listbox item (WPF C#)?
    primarykey
    data
    text
    <p>all. I have an app that scans a picture folder and displays the images along with their names in a listbox. Each image and image name (displayed in a textblock next to the image) is stored in a horizontal stackpanel inside the listbox.</p> <p>I've been trying all afternoon to find a way of displaying the image name in a textbox when the user selects it in the listbox. Sounds very simple, and I'm sure it is, but I can't seem to get it to work.</p> <p>Can anyone point me in the right direction as to the best way of doing this? Thanks.</p> <p>Here is my xaml if it helps:</p> <pre><code>&lt;Grid&gt; &lt;ListBox ItemsSource="{Binding AllImages}" Margin="0,0,262,0" Name="listBox1" MouseLeftButtonDown="listBox1_MouseLeftButtonDown"&gt; &lt;ListBox.ItemTemplate&gt; &lt;DataTemplate&gt; &lt;StackPanel Orientation="Horizontal"&gt; &lt;Image Source="{Binding Image}" Width="50" Height="50" Margin="6"/&gt; &lt;TextBlock Text="{Binding Name}" Margin="6" /&gt; &lt;/StackPanel&gt; &lt;/DataTemplate&gt; &lt;/ListBox.ItemTemplate&gt; &lt;/ListBox&gt; &lt;TextBox Height="23" HorizontalAlignment="Left" Margin="265,148,0,0" Name="textBox1" VerticalAlignment="Top" Width="198" /&gt; &lt;/Grid&gt; </code></pre> <p>And my code behind:</p> <pre><code>public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); DataContext = this; } public class MyImage { private ImageSource _image; private string _name; public MyImage(ImageSource image, string name) { _image = image; _name = name; } public override string ToString() { return _name; } public ImageSource Image { get { return _image; } } public string Name { get { return _name; } } } public List&lt;MyImage&gt; AllImages { get { List&lt;MyImage&gt; result = new List&lt;MyImage&gt;(); string filePath = @"D:\Projects\Visual Studio 2010\WpfApplication5\WpfApplication5\bin\Debug\ImageFolder"; string[] files = Directory.GetFiles(filePath); foreach (string filename in files) { try { result.Add( new MyImage( new BitmapImage( new Uri(filename)), System.IO.Path.GetFileNameWithoutExtension(filename))); } catch { } } return result; } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload