查看我的 XAML,我注意到这些区域基本上是彼此重复的,因为我喜欢保持干净,所以我在想是否有一种方法可以减少 XAML 中的重复代码。
所以我想要做的是能够为 StackLayout、Grid、Frame 等控件设置内容。
我已经创建了页面级资源,但我不确定如何使用它。
<ContentPage.Resources>
<StackLayout x:Key="CommonDetails">
<Label Text="First Name"/>
<Label Text="Last Name"/>
</StackLayout>
</ContentPage.Resources>
<StackLayout>
<CommonDetails>
<Label Text="Extra Uncommon Data"/>
</StackLayout>
<StackLayout>
<CommonDetails>
<Label Text="Extra Uncommon Data"/>
<Label Text="Extra Uncommon Data"/>
<Label Text="Extra Uncommon Data"/>
</StackLayout>
最佳答案
在Resources
中,您可以定义一个ControlTemplete
:
<ContentPage.Resources>
<ControlTemplate x:Key="commonDetails">
<StackLayout>
<Label Text="First Name"/>
<Label Text="Last Name"/>
<ContentPresenter/>
</StackLayout>
</ControlTemplate>
</ContentPage.Resources>
这里是棘手的部分,因为为了使用它,您将需要一个 ContentView
,但在您的情况下,“正常”ContentView
不会这样做因为它们只接受一个 child
,所以这是一项工作:您必须创建一个特殊的 ContentView
来接受多个 View 。
您可以按如下方式执行此操作:
// Overriding the ContentProperty allows you
// to have a ContentView that accepts multiple childs.
[Xamarin.Forms.ContentProperty("Contents")]
public class View1 : ContentView
{
StackLayout contentStack { get; } = new StackLayout();
public IList<View> Contents { get => contentStack.Children; }
public View1()
{
Content = contentStack;
}
}
有了这些,剩下的就非常简单了,因为在任何 Page
中,您都可以定义自定义 ControlTemplate
并将其设置为您特殊的 ContentView
,如下
<local:View1 ControlTemplate="{StaticResource commonDetails}">
<Label Text="Occupation1"/>
<Label Text="Occupation2"/>
</local:View1>
就是这样,我觉得这很有用!
关于c# - 有没有办法从 StaticResource 设置 StackLayout 或 Grid 的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65412725/