[英]How can I create a new Xamarin Element based on a Frame with a StackLayout inside of it?
我有一個帶有StackLayout的Frame:
<Frame CornerRadius="1" HasShadow="false" Margin="10"
BackgroundColor="White" BorderColor="Silver" Padding="0" >
<StackLayout Orientation="Vertical" Spacing="0" Padding="0" >
<xaml:PtiXaml />
<template:LineTemplate />
<xaml:AtiXaml />
<template:LineTemplate />
<xaml:StiXaml />
</StackLayout>
</Frame>
我可以創建一個名為NewFrame的新對象,該對象與包含StackLayout的Frame相同嗎?
<template:NewFrame>
<xaml:PtiXaml />
<template:LineTemplate />
<xaml:AtiXaml />
<template:LineTemplate />
<xaml:StiXaml />
</template:NewFrame>
要么
<template:NewFrame>
<xaml:ABCXaml />
</template:NewFrame>
要么
<template:NewFrame>
<Label Text="X" />
</template:NewFrame>
有人建議我使用自定義視圖,但我看了,但是找不到其中包含其他元素的示例。
在解決方案資源管理器中右鍵單擊共享項目(或PCL)中的所需位置(我建議添加名為“Views”或“CustomViews”的文件夾並在該文件夾中創建項目),選擇“添加新項目”和選擇“內容視圖”(后面沒有(C#)。文件名應該類似於“View1.xaml”,你可以根據自己的喜好改變它,但重要的是xaml擴展就在那里。
這將創建一個帶有xaml和xaml.cs文件的新ContentView。 在xaml文件中,您可以聲明上面發布的xaml代碼,並將所需的任何代碼寫入xaml.cs文件中。
現在,您可以向要將視圖放入的頁面添加名稱空間聲明:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
...
xmlns:customs="clr-namespace:YourNamespace.Views;assembly=YourNamespace"
並聲明該頁面或任何布局內容中的元素:
<customs:CustomViewName ... />
如果您希望能夠控制元素的行為,可以在代碼隱藏中添加BindableProperties。
有關這方面的更多深入信息,您可能需要查看以下文章: https : //visualstudiomagazine.com/articles/2017/10/01/add-custom-controls.aspx
使用ContentView
和ControlTemplate
創建自定義控件。 這樣,您可以創建一個名為NewFrame
的新控件,為您的控件編寫XAML,然后使用<ControlTemplate>
的<ContentPresenter>
標記指定您希望內容的位置。
像這樣:
.
└── NewFrame
├── NewFrame.cs
└── NewFrame.xaml -> Is a ResourceDictionary
NewFrame.cs:
namespace TestApp.Controls
{
public partial class NewFrame : ContentView
{
}
}
NewFrame.xaml:
<ResourceDictionary
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:newFrame="clr-namespace:TestApp.Controls"
x:Class="Namespace.For.A.ResourceDictionary">
<Style TargetType="newFrame:NewFrame">
<Setter Property="ControlTemplate">
<Setter.Value>
<ControlTemplate>
<ContentView BackgroundColor="Transparent">
<Frame CornerRadius="1" HasShadow="false" Margin="10" BackgroundColor="White" BorderColor="Silver" Padding="0" >
<StackLayout Orientation="Vertical" Spacing="0" Padding="0">
<ContentPresenter/>
</StackLayout>
</Frame>
</ContentView>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
ConsumingYourControl.xaml:
<template:NewFrame>
<template:NewFrame.Content>
<xaml:PtiXaml />
<template:LineTemplate />
<xaml:AtiXaml />
<template:LineTemplate />
<xaml:StiXaml />
</template:NewFrame.Content>
</template:NewFrame>
<template:NewFrame>
<template:NewFrame.Content>
<xaml:ABCXaml />
</template:NewFrame.Content>
</template:NewFrame>
<template:NewFrame>
<template:NewFrame.Content>
<Label Text=""/>
</template:NewFrame.Content>
</template:NewFrame>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.