Reputation: 1494
I want to create customizable view like below.
<ParentView>
<ParentView.Child>
<ChildView Text="Hello, Parent!"/>
</ParentView.Child>
</ParentView>
<ContentView.Content>
<CustomizeView:ChildView
x:Name="NestedView" />
</ContentView.Content>
ParentView.xaml.cs
public static BindableProperty ChildProperty = BindableProperty.Create(
propertyName: nameof(Child),
returnType: typeof(ChildView),
declaringType: typeof(ParentView),
defaultValue: null,
propertyChanged: (b, o, n) =>
{
(b as ParentView).Child = (ChildView)n;
}
);
public ChildView Child
{
get => (ChildView)GetValue(ChildProperty);
set => SetValue(ChildProperty, value);
}
<ContentView.Content>
<Label x:Name="Label" Text="Hello, Child!" />
</ContentView.Content>
ChildView.xaml.cs
public static BindableProperty TextProperty = BindableProperty.Create(
propertyName: nameof(Text),
returnType: typeof(string),
declaringType: typeof(ChildView),
defaultValue: string.Empty,
propertyChanged: (b, o, n) =>
{
(b as ChildView).Label.Text = (string)n;
}
);
public string Text
{
get => (string)GetValue(TextProperty);
set => SetValue(TextProperty, value);
}
What I expect is Hello, Parent!. However I got Hello, Child!.
How can I create customizable View
inside like ContentView
?
Here is Github
Upvotes: 0
Views: 119
Reputation: 18861
In ParentView.xaml.cs , you invoked the line
(b as ParentView).Child= (ChildView)n;
You only change the value of Child , not the Content of the ParentView
So the fastest way is to modify it like following
(b as ParentView).Content= (ChildView)n;
In your case , it seems that you misunderstand the logic in your project .
When you define the following code in ContentPage
<Frame
HorizontalOptions="Center"
VerticalOptions="Center">
<CustomizeView:ParentView>
<CustomizeView:ParentView.Child>
<CustomizeView:ChildView
Text="Hello, Parent!"/>
</CustomizeView:ParentView.Child>
</CustomizeView:ParentView>
</Frame>
Even if you set the Text as Hello, Parent!
, the value will not been changed because we could not set the NestedView as a new ChildView (we can only change its property) .
like
propertyChanged: (b, o, n) =>
{
var childview = (b as ParentView).NestedView as ChildView;
childview.Text = (n as ChildView).Text;
});
Upvotes: 2