如何从父视图自定义子视图? ParentView ChildView

问题描述

我想创建如下所示的可自定义视图。

<ParentView>
    <ParentView.Child>
        <ChildView Text="Hello,Parent!"/>
    </ParentView.Child>
</ParentView>

ParentView

ParentView.xaml
<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);
}

ChildView

ChildView.xaml
<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,n) =>
    {
        (b as ChildView).Label.Text = (string)n;
    }
);

public string Text
{
    get => (string)GetValue(TextProperty);
    set => SetValue(TextProperty,value);
}

我期望的是家长,您好!。 但是我你好,孩子!

Image

如何在View之类的内部创建可自定义ContentView

这里是Github

解决方法

ParentView.xaml.cs 中,您调用了该行

(b as ParentView).Child= (ChildView)n;

您只能更改 Child 的值,而不更改ParentView的内容

所以最快的方法是像下面这样修改它

(b as ParentView).Content= (ChildView)n;

更新

在您的情况下,您似乎误解了项目中的逻辑。

在ContentPage中定义以下代码时

<Frame
        HorizontalOptions="Center"
        VerticalOptions="Center">
        <CustomizeView:ParentView>
            <CustomizeView:ParentView.Child>
                <CustomizeView:ChildView
                    Text="Hello,Parent!"/>
            </CustomizeView:ParentView.Child>
        </CustomizeView:ParentView>
    </Frame>

即使将文本设置为Hello,Parent!,该值也不会更改,因为我们无法将 NestedView 设置为新的ChildView(我们可以只需更改其属性)。

喜欢

propertyChanged: (b,o,n) =>
{
   var childview = (b as ParentView).NestedView as ChildView;
   childview.Text = (n as ChildView).Text;
});