我正在尝试在代码中设置属性绑定(WPF)。代码编译得很好,但我绑定的属性从未设置。下面是一个最小的例子:
视图模型:
public class FooViewModel: INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string _value;
public string Value
{
get { return _value; }
set
{
_value = value;
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("Value"));
}
}
}
风景:
public class FooView: Window
{
public string Value
{
get { return Title; }
set
{
// Breakpoint here never hits!
Title = value;
}
}
public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(string), typeof(FooView));
public FooView()
{
Binding valueBinding = new Binding("Value");
valueBinding.Mode = BindingMode.OneWay;
SetBinding(ValueProperty, valueBinding);
}
}
主要的()”:
FooView view = new FooView();
FooViewModel model = new FooViewModel();
view.DataContext = model;
view.Show();
model.Value = "ABC";
我希望在设置FooView.Value
时调用 -setter model.Value
。我还尝试将Binding.Source
属性显式设置为模型。绑定应该如何设置?