【发布时间】:2018-12-30 01:55:20
【问题描述】:
在 HTML5 中,我可以通过执行以下操作来完成此操作:
lblTxt.Text = "For more info <a href='http://url.com1'>click here</a>, for contact <a href='mailto:contact@domain.com'>send an email</a>";
Tks
【问题讨论】:
标签: xaml xamarin xamarin.forms
在 HTML5 中,我可以通过执行以下操作来完成此操作:
lblTxt.Text = "For more info <a href='http://url.com1'>click here</a>, for contact <a href='mailto:contact@domain.com'>send an email</a>";
Tks
【问题讨论】:
标签: xaml xamarin xamarin.forms
链接不是 Xamarin.Forms 中的一等公民,因为它的结构与 HTML 根本不同。
如果您坚持使用链接,您可以创建一个 StackLayout,其中包含链接前后文本的每个标签以及链接的标签
<ContentPage ...>
<ContentPage.Resources>
<ResourceDictionary>
<Style x:Key="LinkLabel" TargetType="Label">
<Setter Property="TextColor" Value="Blue" />
</Style>
</ResourceDictionary>
</ContentPage.Resources>
<StackLayout Orientation="Horizontal">
<Label Text="For more info" />
<Label Text="click here" Style="{StaticResource LinkLabel}">
<Label.GestureRecognizers>
<!-- Add TapGestureRecognizer that invokes an action on your viewmodel -->
</Label.GestureRecognizers>
</Label>
<Label Text=", for contact">
<!-- and so on, I think you#ve got the gist -->
</StackLayout>
</ContentPage>
诚然,这不能很好地扩展,但可以基于 ContentView 创建自定义视图,并使用 Text 属性分解文本并动态添加标签。这在技术上可行。
但是:请不要这样做,如果你能避免的话。带有超链接的文本不是本机 UI 习惯用法。为了获得最佳 UX,您应该坚持使用经过验证的原生 UI 习惯用法。如果文本不够大,链接可能很难被点击,而且 - 老实说 - 很可能不是做你想做的最漂亮的选择。
【讨论】:
XAML 方法:
<Label
x:Name="LDescription"
HorizontalOptions="FillAndExpand"
TextColor="#000000">
<Label.FormattedText>
<FormattedString>
<Span Text="We have so much to offer."/>
<Span Text=" "/>
<Span Text="Learn More." TextColor="#CF9F24">
<Span.GestureRecognizers>
<TapGestureRecognizer Command="{Binding Command}" NumberOfTapsRequired="1"/>
</Span.GestureRecognizers>
</Span>
</FormattedString>
</Label.FormattedText>
</Label>
方法背后的代码:
XAML
<Label
x:Name="LDescription"
HorizontalOptions="FillAndExpand"
TextColor="#000000">
<Label.FormattedText>
<FormattedString>
<Span Text="We have so much to offer."/>
<Span Text=" "/>
<Span x:Name="SLearnMore" Text="Learn More." TextColor="#CF9F24"/>
</FormattedString>
</Label.FormattedText>
</Label>
代码背后
YourPage() //constructor
{
Appearing += YourPage_Appearing;
Disappearing += YourPage_Disappearing;
}
void YourPage_Appearing(object sender, EventArgs e)
{
var learnMore = new TapGestureRecognizer();
learnMore.Tapped += LearnMore_Tapped;
SLearnMore.GestureRecognizers.Add(learnMore);
}
void YourPage_Disappearing(object sender EventArgs e)
{
SLearnMore.GestureRecognizers.Clear();
}
void LearnMore_Tapped(object sender, EventArgs e)
{
// Your click logic
}
【讨论】:
根据您的想法,我最终得到了以下代码:
<Label>
<Label.FormattedText>
<FormattedString>
<Span Text="long bla bla bla..., "/>
<Span Text="click here" ForegroundColor="Blue"/>
<Span Text=" and more bla bla"/>
</FormattedString>
</Label.FormattedText>
<Label.GestureRecognizers>
<TapGestureRecognizer Command="{Binding ClickHereCommand}" NumberOfTapsRequired="1" />
</Label.GestureRecognizers>
</Label>
【讨论】: