我试图绑定2种方式
在我的ViewModel中,我有
private Temporary _selectedCompany;
public Temporary SelectedCompany
{
get
{
return this._selectedCompany;
}
set
{
if (this._selectedCompany == value || value == null)
return;
this._selectedCompany = value;
this.SelectedCompany.CompanyName = "TestName";
base.OnPropertyChanged("SelectedCompany");
}
}
Temporary
实际上是一个类,类似于您为CompanyAddress(名称,国家/地区,电话等)所做的类,并且是由EntityFramework创建的。
在相应的视图中,XAML是
<local:CompanyDetail CompanyName="{Binding SelectedCompany.CompanyName}"/>
在自定义控件的代码后面
// Dependency Property
public static readonly DependencyProperty CompanyNameProperty =
DependencyProperty.Register("CompanyName", typeof(string),
typeof(CompanyDetail), null);
// .NET Property wrapper
public string CompanyName
{
get { return (string)GetValue(CompanyNameProperty); }
set { SetValue(CompanyNameProperty, value); }
}
ViewModel中没有任何内容。有以下XAML
<TextBox Text="{Binding CompanyName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, RelativeSource={RelativeSource AncestorType=UserControl, AncestorLevel=1, Mode=FindAncestor}}" />
因此,当加载控件并在屏幕上显示时,我会看到值&#34; TestName&#34;在TextBox
但是,如果我通过键入更改值,然后单击“确定”按钮,我可以看到该值尚未更新。
我假设它与INotifyPropertyChanged无关,因为我认为它无论如何都是引用类型?
我做错了什么?
答案 0 :(得分:1)
必须通过明确设置
双向进行CompanyName绑定<local:CompanyDetail
CompanyName="{Binding SelectedCompany.CompanyName, Mode=TwoWay}"/>
或通过声明依赖属性默认绑定双向
public static readonly DependencyProperty CompanyNameProperty =
DependencyProperty.Register(
"CompanyName", typeof(string), typeof(CompanyDetail),
new FrameworkPropertyMetadata(
null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));