Professional Documents
Culture Documents
Lab 06. Liên kết dữ liệu
Lab 06. Liên kết dữ liệu
Lab 06. Liên kết dữ liệu
Mục tiêu
- Liên kết được giá trị của phần tử giao diện với property của lớp
Bài 1
Chuyển đổi các field của lớp UserInformation sang property. Có giới hạn tuổi
phải lớn hơn hoặc bằng 18 và ID phải nằm trong khoảng 1000 đến 9999. Viết method
public override string ToString() để hợp các property thành một chuỗi ký tự duy nhất.
Hướng dẫn
1
• Khai báo property public UserID để quản lý field userID, ID phải nằm trong
khoảng từ 1000 -> 9999 nếu không thì thông báo: “Error! ID must be
between 1000 and 9999”.
• Viết constructor: public UserInformation(string name, uint age,
uint id) để khởi tạo các properties trên.
Viết method public override string ToString() để hợp các property thành
một chuỗi duy nhất theo cú pháp sau:
Bài 2
Hướng dẫn
Bài 3
2
Code XAML:
<Grid>
<StackPanel Orientation="Vertical" HorizontalAlignment="Center"
VerticalAlignment="Center">
<TextBox x:Name="useNameTextBox" PlaceholderText="Nhập Username"
Width="200" Margin="0, 0, 0, 10"/>
<TextBox x:Name="userIDTextBox" PlaceholderText="Nhập User ID"
Width="200" Margin="0, 0, 0, 10"/>
<TextBlock x:Name="sliderValueTextBlock" Text="18"
HorizontalAlignment="Center"/>
<Slider x:Name="userAgeSlider" Minimum="0" Maximum="100" Value="18" />
<Button x:Name="createButton" Content="Create" Margin="0, 0, 0, 10"
Width="200"/>
<TextBlock x:Name="inforTextBlock" Text="User Information"
HorizontalAlignment="Center" Margin="0, 0, 0, 10"/>
</StackPanel>
</Grid>
a. Thực hiện liên kết dữ liệu giữa slider tuổi và TextBlock để hiển thị tuổi
b. Thực hiện liên kết dữ liệu giữa property OneLineInformation và TextBlock
User Information
Hướng dẫn
a. Thay đổi thuộc tính Text của sliderValueTextBlock sang nội dung sau
Text="{Binding ElementName=userAgeSlider, Path=Value, Mode=OneWay}"
Tạo 1 class UserInformationViewModel để khởi tạo đối tượng user mặc định trong đó
tạo 1 property chỉ đọc có tên là DefaultUser
public class UserInformationViewModel
{
private UserInformation defaultUser = new UserInformation(name: "ABC", age:
18, id: 1000);//Khởi tạo đối tượng mặc định
public UserInformation DefaultUser //Tạo property DefaultUser
{
get { return this.defaultUser; }
3
}
Trong MainPage, tạo thêm 1 property ViewModel có thể đọc ghi và khởi tạo
property này trong hàm dựng MainPage từ lớp UserInformationViewModel
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
this.ViewModel = new UserInformationViewModel();
}
public UserInformationViewModel ViewModel { get; set; } //Tạo property
}
Thực hiện Bind thuộc tính Text của inforTextBlock trong XAML code
với property OneLineInformation như sau
Bài 4
Chỉnh sửa lại chương trình để khi nhấn nút Create sẽ cập nhật thông tin lên
Textblock User Information