我正在嘗試制作一個聊天頁面,其中訊息從左側(對話者)或右側(用戶)排列。因此,我將使用資料模板選擇器和串列視圖/集合視圖來保存訊息。如果我使用默認的“標簽”視圖,一切正常,但如果我將其更改為我自己的自定義“標簽”渲染器,它就不再起作用了。
這是我的自定義“標簽”渲染器的代碼。
共享檔案夾中的 CustomLabel.cs
public class CustomLabel : Label
{
public static readonly BindableProperty MaxWidthProperty = BindableProperty.Create(nameof(MaxWidth), typeof(int), typeof(CustomLabel));
public int MaxWidth
{
get { return (int)GetValue(MaxWidthProperty); }
set { SetValue(MaxWidthProperty, value); }
}
}
Android 中的 CustomLabelRenderer.cs
public class CustomLabelRenderer : LabelRenderer
{
public CustomLabelRenderer(Context context) : base(context)
{
AutoPackage = false;
}
protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
{
base.OnElementChanged(e);
if(Context != null)
{
var view = ((CustomLabel)Element);
Control.SetMaxWidth(view.MaxWidth);
}
}
}
這是我在資源字典中的資料模板選擇器代碼和結果圖片。為了使用自定義標簽,我只是用“local:CustomLabel”替換了“Label”。
使用標簽
<ResourceDictionary>
<DataTemplate x:Key="leftSideTemplate" x:DataType="model:Message">
<ViewCell>
<Label Text="{Binding Text}"
HorizontalTextAlignment="Start"
HorizontalOptions="StartAndExpand"
BackgroundColor="{StaticResource BgColorSecondaryUser}"/>
</ViewCell>
</DataTemplate>
<DataTemplate x:Key="rightSideTemplate" x:DataType="model:Message">
<ViewCell>
<Label Text="{Binding Text}"
HorizontalTextAlignment="End"
HorizontalOptions="EndAndExpand"
BackgroundColor="{StaticResource BgColorPrimaryUser}"/>
</ViewCell>
</DataTemplate>
<dt:ConversationTemplateSelector x:Key="conversationPageTemplateSelector"
LeftSideTemplate="{StaticResource leftSideTemplate}" RightSideTemplate="{StaticResource rightSideTemplate}"/>
</ResourceDictionary>
使用默認的“標簽”視圖
使用我的自定義“標簽”渲染器
uj5u.com熱心網友回復:
只有當視圖的 MaxWidth 屬性大于 0 時才設定 MaxWidth。否則,控制元件的寬度可能為零,因此什么也看不到:
if (view.MaxWidth > 0)
Control.SetMaxWidth(view.MaxWidth);
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/480363.html
標籤:C# xamarin xamarin.forms xamarin.android
