XAML reuse specific UI elements

眉间皱痕 提交于 2019-12-24 14:12:08

问题


With Xamarin, I have a small UI element which acts as a content divider:

<BoxView StyleClass="contentDivider"
   HeightRequest="2"
   WidthRequest="1000"
   Margin="3, 0"/>

Since I use this a number of times I wanted to be able to have the code written down once, and reuse that code - just like a class with its instance (DRY). It's most likely me being a blind bat and not being able to find how it's done. So, how can I reuse XAML elements?


回答1:


You can do this with ContentViews (https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/controls/layouts#contentview), which probably works better for larger reuse cases (using more XAML in the ContentView).

Yet, for such a small single element example as yours, you could really just consider using a global style (https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/styles/xaml/application) which its looks like you already have with StyleClass="contentDivider", as long as you only want to override properties on a single element (like your BoxView).

Just add HeightRequest, WidthRequest and Margin to your style and your done.

<Style x:Key="contentDivider" TargetType="BoxView">
    <Setter Property="HeightRequest" Value="20" />
    <Setter Property="WidthRequest" Value="20" />
    <Setter Property="Margin" Value="0,99,0,0" />
    ... etc
</Style>


来源:https://stackoverflow.com/questions/55223100/xaml-reuse-specific-ui-elements

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!