WPF(Windows Presentation Foundation)中的雙向綁定是一種機制,可以在界面控件和數據對象之間實現雙向的數據同步。下面是實現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); }
}
以上是幾種常見的實現WPF雙向綁定的方法。根據具體的需求和場景,可以選擇合適的方式來實現雙向綁定。