【发布时间】:2018-07-31 22:00:27
【问题描述】:
这是我目前想出的方法。然而,这似乎不是一个干净的解决方案。
有没有人对我如何提出更好的解决方案提出任何建议?
<?xml version="1.0" encoding="utf-8"?>
<StackLayout xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:Japanese;assembly=Japanese"
x:Class="Japanese.Templates.HeaderTemplate"
x:Name="this" HorizontalOptions="FillAndExpand" Orientation="Vertical" Spacing="0" Margin="0">
<StackLayout IsVisible="{Binding HeaderType, Converter={StaticResource HeaderType1BoolConverter}, Source={x:Reference this} }" >
<!-- code -->
</StackLayout>
<StackLayout IsVisible="{Binding HeaderType, Converter={StaticResource HeaderType2BoolConverter}, Source={x:Reference this} }" >
<!-- code -->
</StackLayout>
</StackLayout>
在我的银行端 CS:
using System;
using System.Collections.Generic;
using Xamarin.Forms;
namespace Japanese.Templates
{
public partial class HeaderTemplate : StackLayout
{
public HeaderTemplate()
{
InitializeComponent();
}
public static readonly BindableProperty HeaderTypeProperty =
BindableProperty.Create(
nameof(HeaderType),
typeof(string),
typeof(DataViewCellTemplate),
default(string));
public string HeaderType
{
get { return (string)GetValue(HeaderTypeProperty); }
set { SetValue(HeaderTypeProperty, value); }
}
}
}
转换器代码:
public class HeaderType1BoolConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return object.Equals(value, "1");
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
public class HeaderType2BoolConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return object.Equals(value, "2");
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
在调用代码中:
<template:HeaderTemplate Header="Application" HeaderType="1" />
【问题讨论】:
-
严格根据我看到的代码,不需要值转换器(您可以只从模板中公开布尔属性,即
ShowTopContainer和ShowBottomContainer,这将绑定到@每个StackLayout的987654327@ 属性)。您是否可以提供更多详细信息,以便其他人更好地了解您要使用模板实现的目标?您是否希望基于HeaderType对模板进行其他自定义(除了隐藏/显示 2 个容器)。 -
你考虑过控制模板吗?
-
@Tiago_nes 你能给我一个例子,说明你所说的控制模板是什么意思,以及它如何适合我的代码。谢谢
-
@gannaway - 我的应用程序需要 3-4 个不同的模板,但模板的外部部分都是相同的。所以我想只拥有一个模板,在 3-4 个不同的 XAML 块中编写代码,并传递一个参数或类似于模板的东西,以便根据参数显示这 3-4 个代码块中的一个。
-
HeaderType是动态值(在运行时确定)还是在设计时知道?你会在 ListView 中使用这些模板吗?
标签: xamarin xamarin.forms