我想将 ChildProperty 绑定到 xaml 中的 TextBox。
XAML:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="auto"/>
</Grid.ColumnDefinitions>
<TextBlock Text="ChildProperty" Grid.Column="0" Grid.Row="0"/>
<TextBox Text="{Binding Path=ChildProperty}" Grid.Column="1" Grid.Row="0" Width="50"/>
<TextBlock Text="ParentProperty" Grid.Column="0" Grid.Row="1"/>
<TextBox Text="{Binding Path=ParentProperty}" Grid.Column="1" Grid.Row="1" Width="50"/>
</Grid>
数据上下文:
public NotifyParentChangePropertyInChildClass()
{
InitializeComponent();
this.DataContext = new ParentClass();
}
亲子班:
public class ParentClass :INotifyPropertyChanged
{
private int parentProperty;
public int ParentProperty
{
get { return parentProperty; }
set
{
parentProperty = value;
RaisePropertyChanged("ParentProperty");
}
}
public ParentClass()
{
ChildClass obj = new ChildClass();
obj.ChildProperty = 100;
parentProperty = 200;
}
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
public class ChildClass : INotifyPropertyChanged
{
private int childProperty;
public int ChildProperty
{
get { return childProperty; }
set
{
childProperty = value;
RaisePropertyChanged("ChildProperty");
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
当我运行上面的代码时,输入输出窗口消息"System.Windows.Data Error: 40 : BindingExpression path error: 'ChildProperty' property not found on 'object' ''ParentClass' (HashCode=59593954)'. BindingExpression:Path=ChildProperty; DataItem='ParentClass' (HashCode=59593954); target element is 'TextBox' (Name=''); target property is 'Text' (type 'String')"