我有一个字典,MyClass中有一个int属性
public Dictionary<MyClass, BitmapImage> MyList = new Dictionary<MyClass, BitmapImage>();
我希望listbox显示来自此集合的图像(如ItemsSource?),并在每个图像附近的文本框中显示每个属性,这可能吗?
答案 0 :(得分:2)
示例背后的代码:
<强> C#:强>
public MainWindow()
{
InitializeComponent();
PopulatePeople();
}
private void PopulatePeople()
{
List<Person> persons = new List<Person>();
for (int i = 0; i < 10; i++)
{
persons.Add(new Person() { Name = "Bob " + i.ToString(), ImageAddress = "Images/peach.jpg" });
}
listBox.ItemsSource = persons;
}
<强> XAML:强>
<ListBox Name="listBox">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image Source="{Binding Path=ImageAddress}" Width="50" Height="50"/>
<TextBox Text="{Binding Path=Name}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
MVVM示例:
Download the example from OneDrive
最好在DataTemplate
中使用ListBox
来展示Image
和TextBox
。
<强>型号:强>
public class Person
{
public int IDPerson { get; set; }
public string Name { get; set; }
public string ImageAddress { get; set; }
}
您可以在ViewModel的构造函数中填充您的集合:
<强>视图模型:强>
public class YourViewModel:INotifyPropertyChanged
{
private ObservableCollection<Person> persons = new ObservableCollection<Person>();
public ObservableCollection<Person> Persons
{
get { return persons; }
set
{
persons = value;
OnPropertyChanged("Persons");
}
}
public YourViewModel()
{
FillThePersons();
}
private void FillThePersons()
{
for (int i = 0; i < 10; i++)
{
persons.Add(new Person() { Name = "Bob " + i.ToString(),
ImageAddress="Images/peach.jpg" });// Images is the name folder in your project
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
<强> XAML:强>
<ListBox ItemsSource="{Binding Persons}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image Source="{Binding Path=ImageAddress}" Width="50" Height="50"/>
<TextBox Text="{Binding Path=Name}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
以下示例将一个图像添加到所有项目:
<ListBox ItemsSource="{Binding Persons}">
<ListBox.Resources>
<BitmapImage x:Key="AnImage" UriSource="Images/yourImage.png" />
</ListBox.Resources>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image Source="{StaticResource AnImage}" Width="50" Height="50"/>
<TextBox Text="{Binding Path=Name}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
结果: