如何解决如何从父视图自定义子视图? 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);
}
我期望的是家长,您好!。 但是我你好,孩子!。
如何在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;
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。