在WPF中實現數據綁定的實時更新可以通過以下幾種方式實現:
public class ViewModel : INotifyPropertyChanged
{
private string _data;
public string Data
{
get { return _data; }
set
{
if (_data != value)
{
_data = value;
OnPropertyChanged(nameof(Data));
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class ViewModel : DependencyObject
{
public static readonly DependencyProperty DataProperty =
DependencyProperty.Register(nameof(Data), typeof(string), typeof(ViewModel),
new PropertyMetadata(null, OnDataPropertyChanged));
public string Data
{
get { return (string)GetValue(DataProperty); }
set { SetValue(DataProperty, value); }
}
private static void OnDataPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
// 更新數據
}
}
public class ViewModel
{
public ObservableCollection<string> DataCollection { get; set; }
public ViewModel()
{
DataCollection = new ObservableCollection<string>();
}
}
以上就是實現WPF數據綁定實時更新的幾種常用方法。根據具體的場景和需求,可以選擇適合的方式進行實現。