C# ListView加载图片,数据绑定和按钮。
在学习此功能时,百度发现,关于这块说的都不是特别完善。特此记录一下提醒自己。
界面代码
<ListView Name="list1" Height="200" Width="600" SelectionChanged="List1_SelectionChanged">
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Columns="4"/>
</ItemsPanelTemplate>
</ListView.ItemsPanel>
<ListView.View>
<GridView>
<GridViewColumn Header="列2" Width="96">
<GridViewColumn.CellTemplate>
<DataTemplate>
<Image Source="{Binding image}"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="列3" Width="50">
<GridViewColumn.CellTemplate>
<DataTemplate>
<Button Width="30" Content="..." Click="Button_Click" Margin="-50,0,0,0" Background="Transparent"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
然后需要把图片列表绑定到前台,这需要新建一个类:
public class TestListView: INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
=> PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName.Trim()));
protected bool Set<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
{
if (Equals(storage, value))
{
return false;
}
storage = value;
OnPropertyChanged(propertyName);
return true;
}
private BitmapImage _image;
public BitmapImage image
{
get { return _image; }
set
{
_image = value;
OnPropertyChanged("image");
}
}
public TestListView() { }
public TestListView(BitmapImage image)
{
this.image = image;
}
}
现在就开始绑定了:这块代码,我写在xaml文件对应的cs文件下。
public ObservableCollection<TestListView> testlist = new ObservableCollection<TestListView>();
public UserControl2()
{
InitializeComponent();
Listinit();
}
public void Listinit()
{
testlist.Add(new TestListView(GetImage("C:\\Users\\Public\\DOMA\\image\\age\\3.png")));
testlist.Add(new TestListView(GetImage("C:\\Users\\Public\\DOMA\\image\\age\\3.png")));
testlist.Add(new TestListView(GetImage("C:\\Users\\Public\\DOMA\\image\\age\\3.png")));
testlist.Add(new TestListView(GetImage("C:\\Users\\Public\\DOMA\\image\\age\\3.png")));
testlist.Add(new TestListView(GetImage("C:\\Users\\Public\\DOMA\\image\\age\\3.png")));
list1.ItemsSource = testlist;
}
public static BitmapImage GetImage(string imagePath)
{
BitmapImage bitmap = new BitmapImage();
//if (File.Exists(imagePath)) //永远返回false
//{
bitmap.BeginInit();
bitmap.CacheOption = BitmapCacheOption.OnLoad;
using (Stream ms = new MemoryStream(File.ReadAllBytes(imagePath)))
{
bitmap.StreamSource = ms;
bitmap.EndInit();
bitmap.Freeze();
}
//}
return bitmap;
}