Trong Tip of the Day #27
chúng ta có nói về cách thay đổi hình dạng con trỏ chuột (mouse cursor). Nhưng nếu chúng ta muốn thay đổi hình dạng chuột bằng một icon ta thích mà Silverlight không có hỗ trợ thì ta phải làm gì? Vâng, bài hướng dẫn này sẽ cho bạn biết làm thế nào để thực hiện được điều đó.
Demo (Yêu cầu phải có Silverlight 3 Beta 1 ):
<iframe style="width: 400px; height: 400px;" src="http://silverlight.services.live.com/invoke/66033/Custom%20Cursor/iframe.html" frameborder="1" scrolling="no"></iframe>
Điều đầu tiên mà bạn sẽ phải làm là làm ẩn đi hình dáng chuột gốc được hỗ trợ của ứng dụng Silverlight. Trong trang Page.xaml, chúng ta sẽ gán Canvas Mouse thành “None”:
MainPage.xaml:
<UserControl x:Class="CustomCursor.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300">
<Canvas x:Name="LayoutRoot" Cursor="None" Background="White">
</Canvas>
</UserControl>
Tiếp theo, tạo một control theo ý người dùng Silverlight gọi là
CustomCursor. Điều duy nhất mà control này cần được sử dụng là nó sẽ chứa một hình ảnh dùng thay thế hình dạng chuột cũ ( Image
control).
Trang Cursor.XAML:
<UserControl x:Class="CustomCursor.CustomCursor"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Image x:Name="MyCursor"></Image>
</UserControl>
Ở phần code phía sau lớp CustomCursor, ta sẽ thêm vào một phương thức để gán hình ảnh và ,một phương thức khác để định vị trí của công cụ (control).
Phần code của trang Cursor.XAML.cs:
namespace CustomCursor
{
public partial class CustomCursor : UserControl
{
public CustomCursor()
{
InitializeComponent();
}
public void SetCursor(string resource)
{
Uri uri = new Uri(resource, UriKind.Relative);
MyCursor.Source = new System.Windows.Media.Imaging.BitmapImage(uri);
}
public void MoveTo(Point pt)
{
this.SetValue(Canvas.LeftProperty, pt.X);
this.SetValue(Canvas.TopProperty, pt.Y);
}
}
}
Cuối cùng, quay trở lại trang MainPage.xaml.cs và thêm một thể hiện của
CustomCursor của bạn vào Canvas của bạn .Ngoài ra , kiểm tra sự kiện MouseMove event để bạn có thể định vị trí của con trỏ tại vị trí chuột của bạn:
namespace CustomCursor
{
public partial class MainPage : UserControl
{
CustomCursor customCursor = new CustomCursor();
public MainPage()
{
InitializeComponent();
customCursor.SetCursor("fireball.png");
LayoutRoot.Children.Add(customCursor);
this.MouseMove += new MouseEventHandler(MainPage_MouseMove);
}
void MainPage_MouseMove(object sender, MouseEventArgs e)
{
customCursor.MoveTo(e.GetPosition(null));
}
}
}
Thank you,
--Mike Snow