Sử Dụng ListBox trong Silverlight
I.Introduction
Trong bài này mình xin chia sẽ cách dùng ListBox Trong Silverlight
II.Creating Project and Coding
Mở Visual Studio 2010 lên và tạo mới Silverlight Project :
Chúng ta làm một giao diện đơn giản gồm 1 ListBox và Một TextBlock để khi chọn vào Item trên ListBox thì tên Item đó sẽ hiện ra ở TextBlock phía dưới:
Mình có code XAML của giao diện :
<Grid x:Name="LayoutRoot" Margin="0">
<Grid.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FF6E6EDB" Offset="0" />
<GradientStop Color="White" Offset="1" />
</LinearGradientBrush>
</Grid.Background>
<ListBox Margin="12,33,12,120" Name="lbx_Demo" SelectionMode="Multiple" SelectionChanged="lbx_Demo_SelectionChanged"/>
<TextBlock Name="lbl_select" Text="" Margin="55,195,30,78" />
<TextBlock Margin="12,198,324,75" Name="textBlock1" Text="Select: " />
</Grid>
</UserControl>
Ở đoạn Code trên chúng ta chọn SelectionMode=”Multiple” trong ListBox và tạo sự kiện SelectionChanged
Chúng Ta Có Một Số SelectionMode (tùy theo nhu cầu mà chọn cho hợp lý):
1.Multiple : Chọn được nhiều item cùng lúc
2.Single : Chỉ chọn được 1 Item 1 lần.
3.Extended : Giữ phím Ctrl có thể chọn được nhiều Item cùng Lúc.
Bây giờ chúng ta vào xử lý sự kiệ SelectionChanged :
namespace ListBox
{
public partial class MainPage : UserControl
{
List<string> myList = new List<string> { "C#","Silverlight","ADO.NET","WPF","WCF","Windows Fone 7","LINQ"};
public MainPage()
{
InitializeComponent();
lbx_Demo.ItemsSource = myList;
}
private void lbx_Demo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var get = lbx_Demo.SelectedItems;
lbl_select.Text = String.Empty;
foreach (var item in get)
{
if (lbl_select.Text.Length > 0)
{
lbl_select.Text += ",";
}
lbl_select.Text += item;
}
}
}
}
Chạy Chương trình và xem kết quả :
Single : (SelectionMode=”Single”)
Muliple:
Extended: Với SelectionMode này thì các bạn có thể chọn 1 Item, hoặc nhiều Item cùng lúc nếu bạn giữ Phím Ctrl