自定义渲染未在Bindable属性更新

时间:2018-05-04 13:54:02

标签: xamarin.forms custom-renderer xaml-binding

请考虑以下问题。

在我的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");
}

之前

enter image description here

enter image description here

2 个答案:

答案 0 :(得分: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
    }
}

答案 1 :(得分:0)

您可能还需要告诉视图重新渲染。

iOS: this.SetNeedsDisplay();

Android: this.Invalidate(); 
相关问题