这篇文章其实主要是介绍数据绑定,所以ListBox那些初级的最简单的使用方法,直接跳过,那个用Visual Studio点点鼠标就可以实现. 数据绑定,就是将C#数据类型或是UI里控件的属性值,同步到UI里的一个或多个控件的属性值. 举个例子,比如一个TextBlock,它的Text属性值不是固定的,值取决于另一个控件TextBox的Text属性,只要TextBox的Text属性发生变化,TextBlock的Text属性就会自动同步改变,效果相当于给TextBox加了TextChanged事件,然后实时改变TextBlock的Text属性. 首先是多个UI控件之间的绑定方法:
<TextBlock Height="49" HorizontalAlignment="Left" Margin="24,381,0,0" Name="textBlock1" Text="{Binding ElementName=textBox1,Path=Text}" VerticalAlignment="Top" Width="316" />
<TextBox Height="72" HorizontalAlignment="Left" Margin="12,303,0,0" Name="textBox1" Text="TextBox" VerticalAlignment="Top" Width="460" />
关键在于TextBlock控件的Text属性设置,ElementName即是数据源对象名,Path即该对象的属性,这里的意思就是textBlock1的Text属性等于textBox1的Text属性值.绑定以后,textBlock1的Text属性会随着textBox1的Text属性的改变实时更新. 接着是UI控件绑定C#类的方法,以ListBox为例: 我这里分两个例子,一个是最简单的显示一个TextBlock,另一个是稍稍复杂的显示图片与文本. 只显示文本:
<ListBox Height="100" HorizontalAlignment="Left" Margin="-10,6,0,0" Name="listBox1" VerticalAlignment="Top" Width="460" ItemsSource="{Binding}"></ListBox>
//ItemsSource="{Binding}"
C#代码:
string[] s = new string[] { "af","wdfsa","xcvfddsf"};
listBox1.ItemsSource = s;
上面的例子就是把string数组绑定到ListBox上. 接着是复杂的,加上图片: 我们需要先写个类来保一条item的数据,我这里是Car类
namespace PhoneApp1
{
public class Car
{
public string Name { get; set; }
public BitmapImage Pic { get; set; }
}
}
Name 名,Pic 图片 在XAML里增加命名空间:
xmlns:My="clr-namespace:PhoneApp1"
PhoneApp1即项目的默认命名空间. 新增资源引用(好像可以省略):
<phone:PhoneApplicationPage.Resources>
<My:Car x:Key="myCar"></My:Car>
</phone:PhoneApplicationPage.Resources>
ListBox绑定数据:
<ListBox Height="100" HorizontalAlignment="Left" Margin="0,0,0,348" Name="listBox2" VerticalAlignment="Bottom" Width="460" >
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Margin="0,0,0,0" HorizontalAlignment="Left" VerticalAlignment="Center">
<Image Name="Pic" Width="auto" Height="60" Source="{Binding Path=Pic}" HorizontalAlignment="Left" VerticalAlignment="Center"></Image>
<TextBlock Margin="90,0,0,0" Name="Text" Width="60" Height="30" Text="{Binding Name}" HorizontalAlignment="Left" VerticalAlignment="Center"></TextBlock>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
自定义了一个Item模板,一个Image控件,一个TextBlock控件,分别对Source和Text属性进行绑定. 下面是C#程序中添加Item的代码:
List carList = new List();
Car car1 = new Car();
car1.Name = "Car1";
BitmapImage myImage = new BitmapImage(new Uri("/PhoneApp1;component/Images/a.jpg", UriKind.Relative));
car1.Pic = myImage;
Car car2 = new Car();
car2.Name = "Car2";
myImage = new BitmapImage(new Uri("/PhoneApp1;component/Images/b.jpg", UriKind.Relative));
car2.Pic = myImage;
Car car3 = new Car();
car3.Name = "Car3";
myImage = new BitmapImage(new Uri("/PhoneApp1;component/Images/c.jpg", UriKind.Relative));
car3.Pic = myImage;
carList.Add(car1);
carList.Add(car2);
carList.Add(car3);
listBox2.ItemsSource = carList;
图片abc事先添加进Images目录. 上个效果图: 源码打包,原图片太大,我换了几张小图,是bmp格式的,所以源码中图片后缀不同: [download id=”26”]