Bài viết
Kho tài liệu và bài viết được chia sẻ, đánh giá bởi cộng đồng
Interaction trong .NET core của WPF
Nội dung bài viết
Dẫn nhập
.NET Core là một nền tảng phát triển đa mục đích, mã nguồn mở được duy trì bởi Microsoft và cộng đồng .NET trên GitHub. Đó là nền tảng chéo (hỗ trợ Windows, macOS và Linux) và có thể được sử dụng để xây dựng các ứng dụng thiết bị, đám mây và IoT. Hôm nay, chúng ta sẽ cùng nhau tìm hiểu về cách khai báo cũng như cách sử dụng Interaction trong .NET core của WPF
Nội dung
Interaction là gì và tại sao phải sử dụng nó?
Interaction - theo thuật ngữ tiếng Anh có nghĩa là sự tương tác. Interaction giúp cho lập trình viên hay coder có thể binding bất kỳ sự kiện nào tù ViewModel lên View. Thay vì thời kỳ chưa có Mô hình MVVM xuất hiện, ta phải code các event (sự kiện) click, MouseMove, MouseLeftButtonDown,... dưới code behind, nhưng nay ta không cần. Ta thay tất cả các event bằng cái gọi là command, dưới ViewModel, ta chỉ cần viết các command và các command đó sẽ binding lên View. Chức năng của command y như khi bạn sử dụng event. Ví dụ như sự kiện click:
Dùng event
MainWindow.xaml:
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Button Content="Click" Click="Button_Click"></Button>
</Grid>
</Window>
MainWindow.xaml.cs (Code behind):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApp1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
//code của bạn
}
}
}
Dùng Command
MainWindow.xaml (View):
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Button Content="Click" Command="{Binding ClickCommand}"></Button>
</Grid>
</Window>
Class BaseViewModel.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace WpfApp1
{
public class BaseViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
class RelayCommand<T> : ICommand
{
private readonly Predicate<T> _canExecute;
private readonly Action<T> _execute;
public RelayCommand(Predicate<T> canExecute, Action<T> execute)
{
if (execute == null)
throw new ArgumentNullException("execute");
_canExecute = canExecute;
_execute = execute;
}
public bool CanExecute(object parameter)
{
try
{
return _canExecute == null ? true : _canExecute((T)parameter);
}
catch
{
return true;
}
}
public void Execute(object parameter)
{
_execute((T)parameter);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
}
}
Class MainViewModel.cs (ViewModel của MainWindow) kế thừa lại từ class BaseViewModel.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace WpfApp1
{
public class MainViewModel: BaseViewModel
{
public ICommand ClickCommand { get; set; }
public MainViewModel()
{
ClickCommand = new RelayCommand<object>((p) => { return true; }, (p) =>
{
//Code của bạn
});
}
}
}
Cách cài thư viện, khai báo và sử dụng interaction trong .NET core
Cài thư viện
Vào Tools -> Nuget Package Manager -> Package Manager Console, sau đó gõ:
Install-Package Microsoft.Xaml.Behaviors.Wpf
Khai báo
Trong code xaml, thêm dòng này:
xmlns:i= "http://schemas.microsoft.com/xaml/behaviors"
Đến đây là ta sử dụng interaction bình thường
Một số lưu ý
- Có những sự kiện không thể binding được như: MouseMove, MouseEnter,... mà chúng ta buộc phải sử dụng Interaction
- Interaction trên đây chỉ sử dụng với .NET core 3
Nội dung bài viết