我想将ChildProperty绑定到xaml中的TextBox。将嵌套对象绑定到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>
的DataContext:
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')"
我想有单独的类这些属性:
更改为文本框的结合。我无法在同一个类中定义两个属性。 – user2323308
如果属性是不同的类,绑定的唯一方法是使用RelativeSource或Element Name在可视树中跳转。 –
为什么不在ChildClass中派生类并将其设置为DataContext? –