Boa*_*rdy 5 c# wpf xaml listbox
我目前正在开发一个C#WPF应用程序,我正在尝试添加一个图像,然后在每个列表项中添加一些文本.
我有绑定工作的文本,但图像不显示.
以下是我的XAML:
<Window x:Class="ServerAdministrator.FtpDirectoryListing"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ServerAdministrator"
Title="FTP Directory Listing" Height="391" Width="599">
<Grid>
<StatusBar Height="30" Margin="0,322,0,0" Name="statusBar1" VerticalAlignment="Top" />
<ToolBar Height="26" Name="toolBar1" VerticalAlignment="Top" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="12,32,0,0" Name="textBox1" VerticalAlignment="Top" Width="517" />
<ListBox x:Name="lstDirecotryListing" Height="233" HorizontalAlignment="Left" Margin="12,61,0,0" VerticalAlignment="Top" Width="553">
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type local:DirectoryListing}">
<StackPanel>
<TextBlock Margin="3" Text="{Binding path}" />
<ContentControl Margin="3" Content="{Binding image}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)
下面是我的DirectoryListing类
class DirectoryListing
{
public string path {get; set;}
public Image image{get; set;}
public DirectoryListing(Image imgage, String path)
{
this.image = image;
this.path = path;
}
}
Run Code Online (Sandbox Code Playgroud)
以下是我如何将项目添加到列表框中
Image image = new Image();
BitmapImage bi = new BitmapImage(new Uri(@"C:\Users\Chris\Documents\Visual Studio 2010\Projects\ServerAdministrator\ServerAdministrator\bin\Debug\images\directory.png"));
image.Source = bi;
lstDirecotryListing.Items.Add(new DirectoryListing(image, "hello"));
Run Code Online (Sandbox Code Playgroud)
文字正在添加正常但不是图像.
我不确定它是否相关,但我在VS2010的控制台输出中得到以下内容
System.Windows.Data错误:4:无法找到绑定源,引用'RelativeSource FindAncestor,AncestorType ='System.Windows.Controls.ItemsControl',AncestorLevel ='1''.BindingExpression:路径= HorizontalContentAlignment; 的DataItem = NULL; target元素是'ComboBoxItem'(Name =''); target属性为'HorizontalContentAlignment'(类型'HorizontalAlignment')System.Windows.Data错误:4:无法找到绑定源,引用'RelativeSource FindAncestor,AncestorType ='System.Windows.Controls.ItemsControl',AncestorLevel ='1'' .BindingExpression:路径= VerticalContentAlignment; 的DataItem = NULL; target元素是'ComboBoxItem'(Name =''); target属性是'VerticalContentAlignment'(类型'VerticalAlignment')
感谢您的任何帮助,您可以提供
UPDATE
由于Clemens的回答我仍然使用它,仍然使用相同的两个变量,因为路径不是图像的路径,但无论如何,它现在正在显示图像和文本.
问题是它显示文本和图片在下面,我需要并排显示图片和文字,我该怎么办?
Cle*_*ens 13
将视图模型减少到:
public class DirectoryListing
{
public string Name { get; set; }
public string Path { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
并将您的DataTemplate更改为:
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Margin="3" Text="{Binding Name}"/>
<Image Margin="3" Source="{Binding Path}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
Run Code Online (Sandbox Code Playgroud)
内置类型转换将自动从文件路径字符串创建ImageSource.