WPF(Windows Presentation Foundation)中的雙向綁定是一種機(jī)制,可以在界面控件和數(shù)據(jù)對象之間實(shí)現(xiàn)雙向的數(shù)據(jù)同步。下面是實(shí)現(xiàn)WPF雙向綁定的方法:
<TextBox Text="{Binding Path=PropertyName, Mode=TwoWay}" />
public class DataObject : INotifyPropertyChanged
{
private string _propertyName;
public string PropertyName
{
get { return _propertyName; }
set
{
if (_propertyName != value)
{
_propertyName = value;
OnPropertyChanged(nameof(PropertyName));
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public static readonly DependencyProperty PropertyNameProperty =
DependencyProperty.Register("PropertyName", typeof(string), typeof(CustomControl), new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
public string PropertyName
{
get { return (string)GetValue(PropertyNameProperty); }
set { SetValue(PropertyNameProperty, value); }
}
以上是幾種常見的實(shí)現(xiàn)WPF雙向綁定的方法。根據(jù)具體的需求和場景,可以選擇合適的方式來實(shí)現(xiàn)雙向綁定。