【问题标题】:Is it possible to create a multi-platform custom user control without having to use custom renders in Xamarin.Forms?是否可以创建多平台自定义用户控件而无需在 Xamarin.Forms 中使用自定义呈现?
【发布时间】:2019-11-27 10:35:02
【问题描述】:

总的来说,我对 Xamarin 很陌生,我正在使用 Xamarin.Forms。我需要创建在 Android 和 iOS 上看起来相同的单个可重用控件/ui 组件。以下图为例:

我需要一个在 Android 和 iOS 上看起来都像这样的按钮。经过一些研究后我发现的方法是创建自定义渲染。这样看来,控件的某些内容可以根据平台进行修改。

但是我想知道是否有另一种方法不需要在特定于平台的项目中使用额外的逻辑。我可以在 Xamarin.Forms 项目中完全实现这一点吗?另外,按钮只是一个例子,我需要这样做来输入字段、标签、日历、单选按钮、复选框等。

【问题讨论】:

    标签: xaml xamarin mobile xamarin.forms custom-renderer


    【解决方案1】:

    取决于功能,但通常您只能在 XAML(和代码)中创建跨平台控件,而不能使用自定义渲染器。

    例如,像这样的按钮可能如下所示:(此代码示例将仅在 XAML 中创建圆形按钮)

    <ContentView xmlns="http://xamarin.com/schemas/2014/forms" 
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 xmlns:models="clr-namespace:XamDevSummit.Models"            
                 x:Class="XamDevSummit.Controls.FabButton">
        <ContentView.Content>
            <Grid RowSpacing="0" ColumnSpacing="0"
                  HeightRequest="50" WidthRequest="50"
                  VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
                <Button x:Name="Fab"
                        CornerRadius="25" BackgroundColor="Olive"
                        Text="{x:Static models:IconFont.XamarinOutline}"
                        Command="{Binding ChatCommand}"
                        Style="{StaticResource MaterialButton}" />
            </Grid>
        </ContentView.Content>
    </ContentView>
    

    关于您列出的其他控件,就像我说的那样,这一切都取决于外观和感觉的需求。有些事情只有使用自定义渲染器才能实现。

    【讨论】:

    • 我明白了。我能够在 Xamarin.Forms 中执行类似的操作,但由于在禁用按钮状态时我必须控制颜色(背景和文本),因此我必须创建自定义渲染器。困扰我的是,现在我无法在 XAML 上设置 CornerRadius,我必须在 Android 和 iOS 的自定义渲染器上进行设置。不过谢谢! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多