我们知道我们可以把控件的样式写到Style里面,直接套用就可以了。今天我们深入下,在ListBox里实现图片和文字的资源项。
这个就是我们今天要实现的。
打开Visual Studio,新建一个WPF应用程序。在窗体上拖一个ListBox。
<ListBox Height="184" HorizontalAlignment="Left" Margin="49,42,0,0" Name="listBox1" VerticalAlignment="Top" Width="384" />
我们看到ListBox1中有文字又有图片。我们可以猜到它可以用两个textblock 和一个image控件组成。那么我们要声明两个属性,一个Name,一个Image.
所以我们新建一个类:Users.cs
在类中写:
class Users { private string _name; private string _imagePath; public string Name { get { return _name; } set { _name = value; } } public string ImagePath { get { return _imagePath; } set { _imagePath = value; } } public Users(string name, string imagepath) { this._name = name; this._imagePath = imagepath; } public static Users[] user = { new Users("dingli", "Images/airplane.bmp"), new Users("Brenda Barret", "Images/astro.bmp"), new Users("Carl Christiansen", "Images/beach.bmp"), new Users("Delia Davis", "Images/butterfl.bmp"), new Users("Egbert Evesham", "Images/car.bmp"), new Users("Fenella Ferguson", "Images/cat.bmp"), new Users("Graham Garden", "Images/chess.bmp"), new Users("Val Vignette", "Images/snwflake.bmp"), new Users("William Watson", "Images/drip.bmp"), new Users("Xanthe Xardos", "Images/user.bmp"), new Users("Ybrahim Yavin", "Images/guest.bmp"), new Users("Zaphod Zacharzewski", "images/soccer.bmp") }; }
这里我们实例化了一个Users数组叫user
然后我们在MainWindow.xaml.cs里写:
这里的DataContext是MainWindow下的DataContext,Users.user是刚才的那个初始化的数组。
下面我们在Window.Resources里设置Style了。
这里我们给他一个Grid,在里面我们放三个控件,一个Image,两个TextBlock。这里用到了Binding 绑定的都是我们声明的两个属性,这里的属性是怎么来的呢? 就是我们红色边框框起来的这句代码 DataContext = Users.user;
然后我们在ListBox1中添加下绑定。
ItemsSource="{Binding}" Style="{StaticResource ListStyle1}"
加上这两个就可以了。
效果图:
<Border Margin="5" Grid.Row="0" Grid.Column="0" BorderThickness="3"> <Border.BorderBrush> <LinearGradientBrush StartPoint="0,0" EndPoint="0,1"> <GradientStop Offset="0" Color="Red"/> <GradientStop Offset="1" Color="Blue"/> </LinearGradientBrush> </Border.BorderBrush> <Grid> <Image Source="{Binding ImagePath}" /> </Grid> </Border>
看到边框了吧。
如果图片有透明的话,我们可以给他加个Rectangle
<Rectangle> <Rectangle.Fill> <LinearGradientBrush StartPoint="0,0" EndPoint="0,1"> <GradientStop Color="#444" Offset="0" /> <GradientStop Color="#fff" Offset="1" /> </LinearGradientBrush> </Rectangle.Fill> </Rectangle>
和上面张不是很明显,因为图片不透明。
结束。