【发布时间】:2020-06-10 21:35:14
【问题描述】:
正如标题所示,我试图将 Person 对象传递给自定义控件,而不是分别传递每个属性。
所以:
<controls:PersonControl
Person="{Binding Person}"
ControlTemplate="{StaticResource PersonControlTemplate}">
</controls:PersonControl>
而不是这个(基于this 实现)
<controls:PersonControl
Name="{Binding Person.Name}"
Age="{Binding Person.Age}"
ControlTemplate="{StaticResource PersonControlTemplate}">
</controls:PersonControl>
我已尝试更改 PersonControl 代码后面的可绑定属性签名,但它不起作用。我实际上只是得到一个空白屏幕。
所以: 1 - 这甚至可能吗(我知道它被称为 可绑定属性 但它也需要对象吗? 和 2 - 如果不是,推荐的方法是什么?
我想这样做的原因是人员对象可能会随着时间的推移而增长,我宁愿只更新自定义控件而不是消费页面和它的视图模型。
更新: 这是 PersonControl 代码:
public partial class PersonControl : ContentView
{
public static readonly BindableProperty PersonProperty = BindableProperty.Create(
nameof(Person),
typeof(Person),
typeof(PersonControl),
string.Empty);
public string Name
{
get { return this.Person.Name; }
}
public Person Person
{
get { return (Person)GetValue(PersonProperty); }
set { SetValue(PersonProperty, value); }
}
public PersonControl()
{
InitializeComponent();
}
}
这是 PersonControl xaml:
<ContentView.Content>
<StackLayout>
<Label Text="{TemplateBinding Person.Name, Mode=OneWay}"/>
</StackLayout>
</ContentView.Content>
最后是消费页面:
<ContentPage.Resources>
<ControlTemplate x:Key="PersonControlTemplate">
<controls:PersonControl></controls:PersonControl>
</ControlTemplate>
</ContentPage.Resources>
<ContentPage.Content>
<StackLayout Spacing="10" x:Name="layout">
<controls:PersonControl
Person="{Binding Person}"
ControlTemplate="{StaticResource PersonControlTemplate}"></controls:PersonControl>
</StackLayout>
</ContentPage.Content>
根据 mvvm 模式,person 对象是页面视图模型上的一个属性。 提前感谢您的帮助。
更新:我遵循了这个tutorial 并尝试用一个对象替换可绑定的字符串类型,但仍然没有乐趣
【问题讨论】:
-
是的,这是可能的。如果您向我们展示您遇到问题的实际代码会有所帮助
-
你需要修改你所有的代码,它为你工作的方式你会有“control.Name”和“control.Age”,但是当你绑定Person时你会得到类似“control.Age”的东西。 Person.Name”和“control.Person.Age”。这是所有假设,因为您尚未发布代码。
-
我已经用代码更新了这个问题。谢谢
-
您发布的 XAML 用于 ContentPage,而不是 ContentView
-
复制粘贴错误。我已经更新了代码
标签: c# mobile mvvm xamarin.forms user-controls