溫馨提示×

c# get set如何實現屬性變更通知

c#
小樊
118
2024-11-23 18:21:31
欄目: 編程語言

在C#中,可以使用INotifyPropertyChanged接口來實現屬性變更通知。這個接口要求實現一個名為PropertyChanged的事件,當屬性值發生變化時,會觸發此事件。以下是一個簡單的示例:

首先,創建一個名為INotifyPropertyChanged的接口:

public interface INotifyPropertyChanged
{
    event PropertyChangedEventHandler PropertyChanged;
}

然后,創建一個基類BaseViewModel,實現INotifyPropertyChanged接口:

public abstract class BaseViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

接下來,創建一個包含屬性的視圖模型類,繼承自BaseViewModel

public class MyViewModel : BaseViewModel
{
    private string _myProperty;

    public string MyProperty
    {
        get { return _myProperty; }
        set
        {
            if (_myProperty != value)
            {
                _myProperty = value;
                OnPropertyChanged();
            }
        }
    }
}

在這個例子中,當MyProperty的值發生變化時,會觸發PropertyChanged事件。你可以在XAML中綁定這個屬性到視圖,當屬性值發生變化時,視圖將自動更新。

例如,在XAML中創建一個TextBox,并將其綁定到MyProperty

<Window x:Class="YourNamespace.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:YourNamespace"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <TextBox Text="{Binding MyProperty}" />
    </Grid>
</Window>

在代碼中,將MyViewModel實例設置為窗口的數據上下文:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new MyViewModel();
    }
}

現在,當你在TextBox中更改文本時,MyProperty的值會發生變化,并觸發PropertyChanged事件,從而更新視圖。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女