Professional Documents
Culture Documents
Silverlight Chapter 7
Silverlight Chapter 7
Silverlight Chapter 7
Binding Object: Nh l mt xc tc giaBindingTarget v Binding Source Binding Source: Cha cc thuc tnh d liu, cn c th l i tng ca CLR Binding Target: L cc thuc tnh giao diu ngi dng c th hin th hoc thay i ti d liu. Binding target c th l DependencyProperty ca FramworkElement Value Converter: Thnh phn ty chn p dng cho nhng trng hp d liu cn phn tch hoc chuyn i
Microsoft Vietnam LLC DPE team | Chng VII: Lm vic vi d liu trong Silverlight
iu hng ca lung d liu: Quyt nh ti vic tng tc d liu qua li gia Binding Source v Binding Target (xem chi tit mc di)
M C# :
//To mt lp MyColors thc thi giao tip INotifyPropertyChanged. MyColors textcolor = new MyColors(); // Brush1 thit lp mt SolidColorBrush vi gi tr mu Red. textcolor.Brush1 = new SolidColorBrush(Colors.Red); // Thit lp DataContext ca MyTextBox. MyTextBox.DataContext = textcolor;
Khi s dng DataContext trong m C# trn y, n cho php cc th UI tha k thng tin v d liu ngun. V d ging nh trong ASP.NET bn s dng phng thc gn DataSouce hin th d liu trn mt Grid.
o Cc phng thc iu hng ca lung d liu
Mi mt kiu binding data u c mt phng thc iu hng lung d liu(Mode propery). Ci ny quyt nh khi no v lm th no d liu chy trn. C 3 phng thc iu hng lung d liu sau OneTime: binding d liu ti target (giao din ngi dng) mt ln v sau kt thc kt ni khng binding na. Phng thc ny ph hp khi hin th d liu m t khi hoc khng bao gi cn thay i. OneWay: Binding d liu ti target v gi n n khi Source (ngun d liu) thay i th target cng thay i theo. Phng thc ny ph hp khi trnh by d liu m ngi dng khng c php thay i TwoWay: Binding d liu ti target v gi n n khi source thay i th target cng thay i theo, nhng khi target thay i th source cng thay i theo. Phng thc ny ph hp khi trnh by d liu m cho php ngi dng thay i d liu ngun
Change Notification
cho hp l vi cc thay i gi tr gia Source object v Target objects th chng ta phi thc thi mt interface l InotifyPropertyChanged. Trong InotifyPropertyChanged c cung cp mt event PropertyChanged. Trong v d di y. Class MyColors thc thi giao tip InotifyPropertyChanged cho phng thc OneWay
namespace DataBinding { //Tao mot class thua ke interface INotifyPropertyChanged public class MyColors : INotifyPropertyChanged { private SolidColorBrush _Brush1; // Khai bao su kien PropertyChanged. public event PropertyChangedEventHandler PropertyChanged; //Tao thuoc tinh cua SolidColorBrush public SolidColorBrush Brush1 { get { return _Brush1; } Microsoft Vietnam LLC DPE team | Chng VII: Lm vic vi d liu trong Silverlight 2
set { _Brush1 = value; // Goi NotifyPropertyChanged khi thuoc tinh nguon duoc cap nhap NotifyPropertyChanged("Brush1"); } } public void NotifyPropertyChanged(string propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } }
Isolated Storage l mt thay th tuyt vi cho cookie, c bit l nu bn ang lm vic vi mt tp ln d liu. Mt s v d v kh nng ca Isolated Storage bao gm undo li mt s thao tc ca ng dng, hay gi hng, cc ci t v ca s hay bt k ci t no m bn mun truy cp vo ln np tip theo. Isolated Storage lu tr theo ngi dng cho php cc ng dng lu gi cc ci t cho tng ngi dng ring bit. Ngi qun tr c th t gii hn a trn mi ngi dng v assembly, khng c bt k cnh bo no v khng gian trng cn li. V l do ny, bn nn kim tra v bt cc ngoi l trong ng dng ca bn. D rng Isolated Storage c t trong mt th mc n trong h thng, nhng khng c ngha ngi dng khng th tm ra th mc ny, do vy Isolated Storage khng hon ton an ton v ngi dng c th thay i hoc xa cc file. Tuy nhin, nu mun ngi dng khng th thay i cc file, bn c th dng cc lp m ha m li cc file ny trc khi lu. Cc my tnh c th b kha bi cc chnh sch bo mt v cc ng dng s khng th lu c vo IsolatedStorage. C th hn, bn cn c IsolatedStorageFilePermission c th lm vic c vi IsolatedStorage
Mt s vn c th xy ra:
Gi hy xem qua v d v vic lu v c d liu t IsolatedStorage. Nh rng bn cn dng using tham chiu n namespace System.IO.IsolatedStorage cng nh l System.IO.
Microsoft Vietnam LLC DPE team | Chng VII: Lm vic vi d liu trong Silverlight
namespace Samples_Chap7 { public partial class Page : UserControl { public Page() { InitializeComponent(); //Luu du lieu vao file dulieu.txt SaveData("Day la du lieu cua toi", "dulieu.txt"); //Lay du lieu tu file dulieu.txt string test = LoadData("dulieu.txt"); } private void SaveData(string data, string fileName) { //Lay Isolated Storage cua nguoi dung danh cho ung dung using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication()) { using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(fileName, FileMode.Create, isf)) { using (StreamWriter sw = new StreamWriter(isfs)) { //Luu du lieu sw.Write(data); sw.Close(); } } } } private string LoadData(string fileName) { string data = String.Empty; //Lay Isolated Storage cua nguoi dung danh cho ung dung using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication()) { using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(fileName, FileMode.Open, isf)) { using (StreamReader sr = new StreamReader(isfs)) { string lineOfData = String.Empty; while ((lineOfData = sr.ReadLine()) != null) //Doc du lieu data += lineOfData; } } } return data; } } }
Microsoft Vietnam LLC DPE team | Chng VII: Lm vic vi d liu trong Silverlight
LINQ to XML cng ging nh Document Object Model(DOM) trong n em ti liu XML ny vo trong b nh. Bn c th truy vn v thay i ti liu ny, sau khi thay i n bn c th lu n v mt file hoc chuyn i ha n (Serialize) ri gi n thng qua mng Internet. Tuy nhin LINQ to XML khc bit so vi DOM ch: N cung cp mt i tng mi nh nhng hn v d dng lm vic vi chng hn, ngoi ra LINQ to XML cn l s ci tin ca ngn ng Visual C# 2008. Mt li th quan trng nht ca LINQ to XML l n tch hp vi Language-Integrated Query (LINQ). Vi s tch hp ny n cho php bn vit cu truy vn ti liu XML khi trong b nh tr v tp hp cc Element v attribute. LINQ to XML c th so snh c vi cc chc nng ca XPath v Xquery.
o To mt XAML ng vi LINQ to XML
Trong mc ny chng ta s ch r cc to mt control TextBlock bng LINQ to XML. Trc tin ty chnh project silverlight trong Visual Studio chng ta chy v d di y 1. Trong Solution Explorer, thm assembly reference ti System.Xml.Linq.dll 2. Thay i ni dung file page.xaml ca bn theo m di y
<UserControl x:Class="SilverlightApplication1.Page" xmlns="http://schemas.microsoft.com/client/2007" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="400" Height="300"> <Canvas x:Name="LayoutRoot" Background="White"> </Canvas> </UserControl>
) ), new XElement("Contact2", new XElement("Ten", "Tran Duy Bien"), new XElement("DienThoai", "0904 252 161"), new XElement("DiaChi", new XElement("DuongPho", "Pham Van Dong"), new XElement("ThanhPho", "HaNoi") ) ) ); // Tao TextBlock1 // Luu y rang Element nay phai khai bao 2 XAML namespace XElement textBlock1 = XElement.Parse( @"<TextBlock xmlns='http://schemas.microsoft.com/client/2007' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' TextWrapping= 'Wrap' Width = '400' Canvas.Top = '10' Text=''/>"); // Lay child Element cua contact1 XElement contact1 = contacts.Element("Contact1"); // Gan gia tri vao thuoc tinh Text o cuoi cung voi noi dung cua cac contact trong xml textBlock1.LastAttribute.SetValue(contact1.ToString()); // Lay child element thu hai XElement contact2 = contacts.Element("Contact2"); // Tao TextBlock2 // Luu y rang Element nay phai khai bao 2 XAML namespace XNamespace xmlns = "http://schemas.microsoft.com/client/2007"; XElement textBlock2 = new XElement(xmlns + "TextBlock", new XAttribute(XNamespace.Xmlns + "x", "http://schemas.microsoft.com/winfx/2006/xaml"), new XAttribute("Canvas.Top", 250), new XAttribute("Width", "600"), new XAttribute("Text", contact2.ToString()) );
// Them TextBlock1 vao trong trang LayoutRoot.Children.Add(XamlReader.Load(textBlock1.ToString()) as UIElement); // Them TextBlock2 vao trong trang LayoutRoot.Children.Add(XamlReader.Load(textBlock2.ToString()) as UIElement); o Cch load file XML t mt URI bt k
1. To mt i tng WebClient, thm trnh x l (handler), Gi phng thc OpenReadAsync. Lm theo m lnh di y
WebClient wc = new WebClient(); wc.OpenReadCompleted += wc_OpenReadCompleted; wc.OpenReadAsync(new Uri(uriString));
return; } //Neu khong co loi, Lay du lieu stream ve va phan tich chung toi XDocument thong qua phuong thuc Load using (Stream s = e.Result) { XDocument doc = XDocument.Load(s); OutputTextBlock.Text = doc.ToString(SaveOptions.OmitDuplicateNamespaces); } }
Kt ni ti mt WCF Web Service S dng LINQ truy vn v tr v d liu S dng Control DataGrid hin th d liu
To mt Project Web Application (File -> New ->Project -> Silverlight Application) . Chng ta t tn cho ng dng ny l SQLData
Microsoft Vietnam LLC DPE team | Chng VII: Lm vic vi d liu trong Silverlight
LINQ to SQL l mt phin bn hin thc ha ca O/RM (object relational mapping) c bn trong .NET Framework bn Orcas (nay l .NET 3.5), n cho php bn m hnh ha mt c s d liu dng cc lp .NET. Sau bn c th truy vn c s d liu (CSDL) dng LINQ, cng nh cp nht/thm/xa d liu t . LINQ to SQL h tr y transaction, view v cc stored procedure (SP). N cng cung cp mt cch d dng thm kh nng kim tra tnh hp l ca d liu v cc quy tc vo trong m hnh d liu ca bn. bit thm v cng ngh ny bn c th xem chi tit ti ScottGu's tutorial
o Thm LINQ to SQL Classes
Bng cch chut phi vo Server Project v chn Add -> New Item sau chn LINQ to SQL Classes. class ny c tn l DataClasses1.dbml
Microsoft Vietnam LLC DPE team | Chng VII: Lm vic vi d liu trong Silverlight
Chng ta m Server Explorer (View->Server Explorer) v chn c s d liu AdventureWorkLTs ( ci t sn trong SQL Server hoc c th download Microsoft.com)
Sau khi m kt ni ti CSDL AdventureWorkLTs, chng ta tip tc ko bng Customer vo DataClasses1.dbml trong m trong Designer
Microsoft Vietnam LLC DPE team | Chng VII: Lm vic vi d liu trong Silverlight
Sau khi ko vo vng trng ca DataClasses1.dbml s nhn thy c kh nng chuyn ha t i tng bng (Customer table) sang m hnh lp nh hnh v di y
Microsoft Vietnam LLC DPE team | Chng VII: Lm vic vi d liu trong Silverlight
10
Chut phi vo Web Project chn Add New, bn trong templates chn WCF Service
Microsoft Vietnam LLC DPE team | Chng VII: Lm vic vi d liu trong Silverlight
11
public List<Customer> GetCustomersByLastName(string lastName) { DataClasses1DataContext db = new DataClasses1DataContext(); var matchingCustomers = from cust in db.Customers where cust.LastName.StartsWith(lastName) select cust; return matchingCustomers.ToList(); }
<services>
</services>
Microsoft Vietnam LLC DPE team | Chng VII: Lm vic vi d liu trong Silverlight
12
Tuy nhin n ch h tr trong basic binding (SOAP 1.1, etc.), v vy bn cn thay i binding tng ng nh sau
<endpoint address="" binding="basicHttpBinding" contract="SQLData_Web.IService1">
To ng dng Silverlight
Tip theo chng ta s to mt ng dng Silverlight v tng tc vi web service WCF va to c. Chut phi vo references trong silverlight project v chn Add Service Reference
Sau khi chn Add Service Reference, bn bm chut vo Discover v chn Services in Solution. Service m bn va to s c tm thy v hin th. Bm OK
Service sau khi c thm vo project ca bn, bn c th truy cp vo Web service ny.
Microsoft Vietnam LLC DPE team | Chng VII: Lm vic vi d liu trong Silverlight
13
To XAML
<Grid x:Name="LayoutRoot" Background="White" ShowGridLines="True"> <Grid.RowDefinitions> <RowDefinition Height="10" /> <!--0 Margin--> <RowDefinition Height="50" /> <!--1 Prompts--> <RowDefinition Height="*" /> <!--2 DataGrid--> <RowDefinition Height="10" /> <!--3 Margin--> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="10" /> <!--0 Margin--> <ColumnDefinition Width="*" /> <!--1 Controls--> <ColumnDefinition Width="10" /> <!--2 Margin--> </Grid.ColumnDefinitions> </Grid>
Microsoft Vietnam LLC DPE team | Chng VII: Lm vic vi d liu trong Silverlight
14
<Border BorderBrush="Black" BorderThickness="2" Grid.Row="1" Grid.Column="1"/> <StackPanel Grid.Row="1" Grid.Column="1" Orientation="Horizontal"> <TextBlock Text="Last name to search for: " VerticalAlignment="Bottom" FontSize="18" Margin="15,0,0,0" /> <TextBox x:Name="LastName" Width="250" Height="30" Margin="2,0,0,4" VerticalAlignment="Bottom"/> <Button x:Name="Search" Width="75" Height="30" Margin="20,0,0,4" Content="Search" VerticalAlignment="Bottom" Background="Blue" FontWeight="Bold" FontSize="14" /> </StackPanel>
t cc Control sau y vo hng th nht ca Grid Ko th DataGrid trong toolbox vao trong XAML
<my:DataGrid x:Name="theDataGrid" AlternatingRowBackground="Beige" AutoGenerateColumns="True" Width="700" Height="500" Grid.Row="2" Grid.Column="1" CanUserResizeColumns="True" /> o Vit x l s kin cho nt Search
public Page() { InitializeComponent(); Loaded += new RoutedEventHandler(Page_Loaded); } void Page_Loaded(object sender, RoutedEventArgs e) { Search.Click += new RoutedEventHandler(Search_Click); } void Search_Click(object sender, RoutedEventArgs e) { //Gan Service1Client toi mot doi tuong o local l webService ServiceReference1.Service1Client webService SQLData.ServiceReference1.Service1Client();
new
//Cai dat trinh xu ly su kien webService.GetCustomersByLastNameCompleted += new EventHandler<SQLData.ServiceReference1. GetCustomersByLastNameCompletedEventArgs>(webService_GetCustomersByLastNameCompleted); //Goi asynchronous webService.GetCustomersByLastNameAsync(LastName.Text);
void webService_GetCustomersByLastNameCompleted(object SQLData.ServiceReference1.GetCustomersByLastNameCompletedEventArgs e) { //Trinh bay ket qua vao Datagrid theDataGrid.ItemsSource = e.Result; }
sender,
Microsoft Vietnam LLC DPE team | Chng VII: Lm vic vi d liu trong Silverlight
15
Kt qu hin th
Microsoft Vietnam LLC DPE team | Chng VII: Lm vic vi d liu trong Silverlight
16