[英]How to customize child view from parent view?
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
?如何在
ContentView
内部创建可自定义的View
?
In ParentView.xaml.cs , you invoked the line在ParentView.xaml.cs 中,您调用了该行
(b as ParentView).Child= (ChildView)n;
You only change the value of Child , not the Content of the ParentView您只更改Child的值,而不是 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当您在 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!
即使您将Text设置为
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) . ,该值不会更改,因为我们无法将NestedView设置为新的 ChildView(我们只能更改其属性)。
like喜欢
propertyChanged: (b, o, n) =>
{
var childview = (b as ParentView).NestedView as ChildView;
childview.Text = (n as ChildView).Text;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.