INotifyPropertyChanged 的基礎知識
如果你不僅希望顯示靜態物件,而是讓 UI 響應對關聯物件的更改,則需要了解 INotifyPropertyChanged
介面的基礎知識。
假設我們將 MainWindow
定義為
<Window x:Class="Application.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:vm="clr-namespace:Application.ViewModels>
<Window.DataContext>
<vm:MainWindowViewModel/>
</Window.DataContext>
<Grid>
<TextBlock Text={Binding Path=ApplicationStateText}" />
</Grid>
</Window>
我們的 Viewmodel-Class MainWindowViewModel
定義為
namespace Application.ViewModels
{
public class MainWindowViewModel
{
private string _applicationStateText;
public string ApplicationStateText
{
get { return _applicationStateText; }
set { _applicationStateText = value; }
}
public MainWindowViewModel()
{
ApplicationStateText = "Hello World!";
}
}
}
由於其繫結,我們的應用程式的 TextBlock 將顯示 Text Hello World 。如果我們的 ApplicationStateText 在執行時期間發生更改,則不會通知我們的 UI 此類更改。
為了實現這一點,我們的 DataSource,在本例中是我們的 MainWindowViewModel
,需要實現介面 INotifyPropertyChanged
。這將使我們的 Bindings
能夠訂閱 PropertyChangedEvent
。
我們需要做的就是每當我們更改 ApplicationStateText
屬性時呼叫 PropertyChangedEventHandler
:
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace Application.ViewModels
{
public class MainWindowViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged( [CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private string _applicationStateText;
public string ApplicationStateText
{
get { return _applicationStateText; }
set
{
if (_applicationStateText != value)
{
_applicationStateText = value;
NotifyPropertyChanged();
}
}
}
public MainWindowViewModel()
{
ApplicationStateText = "Hello World!";
}
}
}
並確保,我們的 Binding
實際上聽了一個 PropertyChangedEvent
:
<Window x:Class="Application.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:vm="clr-namespace:Application.ViewModels">
<Window.DataContext>
<vm:MainWindowViewModel/>
</Window.DataContext>
<Grid>
<TextBlock Text={Binding Path=ApplicationStateText, UpdateSourceTrigger=PropertyChanged }" />
</Grid>
</Window>