全部。我有一个应用程序可以扫描图片文件夹,并在列表框中显示图片及其名称。每个图像和图像名称(显示在图像旁边的文本块中)都存储在列表框内的水平堆栈面板中。获取选定列表框项目的名称(WPF C#)?
我一直试图整个下午找到一种方式,当用户在列表框中选择它时,在文本框中显示图像名称。听起来很简单,我确定它是,但我似乎无法让它工作。
任何人都可以指出我正确的方向吗?谢谢。
这是我的XAML,如果有帮助:
<Grid>
<ListBox ItemsSource="{Binding AllImages}" Margin="0,0,262,0" Name="listBox1" MouseLeftButtonDown="listBox1_MouseLeftButtonDown">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image Source="{Binding Image}" Width="50" Height="50" Margin="6"/>
<TextBlock Text="{Binding Name}" Margin="6" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<TextBox Height="23" HorizontalAlignment="Left" Margin="265,148,0,0" Name="textBox1" VerticalAlignment="Top" Width="198" />
</Grid>
而且我后面的代码:
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<MyImage> AllImages
{
get
{
List<MyImage> result = new List<MyImage>();
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;
}
}
}
这实际上是我认为应该完成的,但我得到了异常错误:“TwoWay或OneWayToSource绑定无法在读取-only property'Name',类型为'WpfApplication5.MainWindow + MyImage'。“ - 如果有帮助,我已经在第一篇文章中列出了我的代码。谢谢。 – SkullJacker 2011-04-21 14:42:47
谷歌搜索会引导你到这:http://stackoverflow.com/questions/590269/a-twoway-or-onewaytosource-binding-cannot-work-on-the-read-only-property我期望这就是问题所在因为您的文本框会允许用户更改分配给它的值。无论如何,您可能想要使用某种标签,除非您希望人们能够更改名称? – 2011-04-21 14:51:18
啊,我明白了。非常感谢。我将它更改为:Text =“{Binding SelectedItem.Name,ElementName = listBox1,Mode = OneWay}”,它完美地工作。谢谢你帮助我理解。 – SkullJacker 2011-04-21 14:56:02