xamarin.forms - 可绑定属性更新未使用自定义渲染
问题描述
请考虑以下问题。
在我的 Xamarin.Forms 应用程序中,我有一个用于 UWP 的自定义渲染,它允许一个按钮有两行,并且是集中的。
问题中的按钮是 Listview 中绑定到对象的项目。最初生成它们时,它们会正确显示按钮中心的两行文本,但是如果我更新文本,它会更新,但似乎绕过了自定义呈现“居中”代码。
请参阅下面的代码片段和图像以进一步解释这种情况。
自定义渲染
[assembly: ExportRenderer(typeof(TwoLinedButton), typeof(TwoLinedButtonUWP))]
namespace aphiresawesomeproject.UWP
{
public class TwoLinedButtonUWP : ButtonRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
{
base.OnElementChanged(e);
if (Control != null && e.NewElement.Text != null)
{
var textBlock = new Windows.UI.Xaml.Controls.TextBlock
{
Text = e.NewElement.Text,
TextAlignment = Windows.UI.Xaml.TextAlignment.Center,
TextWrapping = TextWrapping.WrapWholeWords
};
Control.Content = textBlock;
}
}
}
}
XAML
<ListView x:Name="AphiresListView" CachingStrategy="RecycleElement" ItemsSource="{Binding ListViewItems}" Margin="0,20,0,0" RowHeight="130" SeparatorVisibility="None" VerticalOptions="FillAndExpand" Grid.Column="1" Grid.Row ="3" >
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<local:TwoLinedButton Command="{Binding ClickedCommand}" Margin="5,10,5,10" HorizontalOptions ="FillAndExpand" BackgroundColor="{Binding color_hex}" Grid.Column="1" TextColor="{StaticResource LightTextColor}" FontSize="Medium" Text="{Binding problem_title}"></local:TwoLinedButton>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
在 Viewmodel 中更新
foreach (AphiresObject ViewItem in ListViewItems)
{
ViewItem.problem_title = ViewItem.problem_title.Replace("Line 2", "Updated Line 2");
}
前
后
解决方案
我认为您需要做的就是override OnElementPropertyChanged
在您的渲染器中,并在您的文本属性更改时再次设置 textBlock 属性。
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName == TwoLinedButton.TextProperty.PropertyName)
{
//Set text block properties
}
}
推荐阅读
- xaml - 为什么无法识别此标签页子项?
- node.js - NodeJS lambda dynamoDB putItem 仅当主排序键不同时
- python - pytz 时区 DST 问题
- c++ - 何时调用移动构造函数?
- c - 链表上合并排序的时间效率与指针数组
- python - 如何在 MapReduce 中查找前 10 个元素
- kubernetes-ingress - 使用 GCE + ExternalName 创建入口路径时出错
- javascript - gatsbyjs中的bulma菜单切换不起作用
- ansible - 在剧本中使用命令任务时在 Ansible 中出现内存错误
- python - How to create list of dictionaries from a single dictionary?