【发布时间】:2020-01-30 14:14:39
【问题描述】:
在标签中使用项目符号点时,尝试设置一个非常简单的自定义控件来处理对齐。问题是,传递给自定义控件的 Spans 没有被识别,并且内容没有被呈现(并且 propertyChanged 函数没有被触发)。我错过了什么?
XAML:
<?xml version="1.0" encoding="UTF-8" ?>
<ContentView
x:Class="Sample.Controls.BulletPointItem"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<ContentView.Content>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="10" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Label x:Name="BulletPoint" Text="•" />
<Label x:Name="LabelContent" Grid.Column="1" />
</Grid>
</ContentView.Content>
</ContentView>
代码隐藏:
[ContentProperty(nameof(Spans))]
public partial class BulletPointItem : ContentView
{
// todo add bindable props for bullet point size and color, or even which character to use as the bullet point!
public static readonly BindableProperty SpansProperty =
BindableProperty.Create(
nameof(Spans),
typeof(ObservableCollection<Span>),
typeof(BulletPointItem),
new ObservableCollection<Span>(),
BindingMode.OneWay,
propertyChanged: OnSpansChanged);
public BulletPointItem()
{
InitializeComponent();
}
public ObservableCollection<Span> Spans
{
get => (ObservableCollection<Span>)GetValue(SpansProperty);
set => SetValue(SpansProperty, value);
}
private static void OnSpansChanged(BindableObject bindable, object oldValue, object newValue)
{
var control = (BulletPointItem)bindable;
var newSpansValue = (ObservableCollection<Span>)newValue;
var formattedString = new FormattedString();
if (control == null)
return;
if (newSpansValue == null || newSpansValue.Count == 0)
{
control.LabelContent.FormattedText = formattedString;
return;
}
foreach (var span in newSpansValue)
{
formattedString.Spans.Add(span);
}
control.LabelContent.FormattedText = formattedString;
}
}
尝试使用:
<controls:BulletPointItem>
<Span Text="Span 1." />
<Span FontAttributes="Italic" Text="Span 2." />
</controls:BulletPointItem>
【问题讨论】:
标签: c# xaml xamarin.forms controls