【问题标题】:Using icons in UWP header template with xamarin.froms将 UWP 标头模板中的图标与 xamarin.forms 一起使用
【发布时间】:2017-08-16 06:38:13
【问题描述】:

我正在使用 Xamarin.Forms 编写应用程序,并且我想在 UWP 应用程序的选项卡式页面中显示图标。为了实现这一点,我正在尝试使用自定义渲染器。自定义渲染器代码是

class TabbedPageWithIconsRenderer : TabbedPageRenderer
{
    protected override void OnElementChanged(VisualElementChangedEventArgs e)
    {
        base.OnElementChanged(e);

        if (e.NewElement != null && Control != null)
        {
            Control.HeaderTemplate = App.Current.Resources["TabHeaderTemplate"] as DataTemplate;
        }
    }
}

而数据模板样式为:

<forms:ImageConverter x:Key="imageConverter" />

    <DataTemplate x:Key="TabHeaderTemplate">
        <StackPanel >
            <Image
                HorizontalAlignment="Center"
                Margin="0,12,0,0"
                Height="24"
                Width="24"
                Source="{Binding Icon, Converter={StaticResource imageConverter}}" />
            <TextBlock
                FontFamily="Segoe UI"
                Text="{Binding Title}"
                Style="{StaticResource CaptionTextBlockStyle}"
                LineStackingStrategy="BlockLineHeight"
                LineHeight="14"
                MaxLines="2"
                IsTextScaleFactorEnabled="False"
                TextAlignment="Center"
                HorizontalAlignment="Center"
                Margin="2,5,2,7" />
        </StackPanel>
    </DataTemplate>

问题是标题工作正常,但图标从不出现,但它们已正确分配给 Forms.Xaml 中的每个页面。

我做错了什么?

【问题讨论】:

    标签: xaml uwp xamarin.forms xamarin.uwp


    【解决方案1】:

    我已经测试了您的代码并重现了您的问题。我通过自定义新图像转换器解决了这个问题,如以下代码。

    public class MyImageConverter:Windows.UI.Xaml.Data.IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            var temp = (value as FileImageSource).File;
            Windows.UI.Xaml.Media.ImageSource source = new BitmapImage(new Uri(temp));
            return source;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            throw new NotImplementedException();
        }
    }
    

    Source="{Binding Icon,Converter={StaticResource imageConverter}}"设置绑定时Icon的返回类型为Xamarin.Forms.FileImageSource(虽然使用了imageConverter,但没有达到预期的效果)。而您使用Windows.UI.Xaml.Controls.Image 作为您的TabHeaderTemplateImage.Source 只接受 Windows.UI.Xaml.Media.ImageSource 类型值。 因此,您可以像上面的代码一样自定义转换器。

    【讨论】:

    • 您的转换器示例有效。似乎无法为 HeaderTemplate 使用标准的 Xamarin.Forms 图像转换器。
    猜你喜欢
    • 1970-01-01
    • 2018-05-22
    • 2017-09-27
    • 2017-09-14
    • 2014-03-05
    • 2018-05-05
    • 2018-08-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多