我想將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? –