【问题标题】:Custom Render not being used on Bindable property update可绑定属性更新未使用自定义渲染
【发布时间】:2020-02-07 22:20:36
【问题描述】:

请考虑以下问题。

在我的 Xamarin.Forms 应用程序中,我有一个用于 UWP 的自定义渲染,它允许一个按钮有两行,并且是集中式的。

问题中的按钮是 Listview 中绑定到对象的项目。最初生成它们时,它们会在按钮中心正确显示两行文本,但是如果我更新文本,它会更新,但似乎绕过了自定义呈现“居中”代码。

请看下面的代码sn-ps和图片进一步说明情况。

自定义渲染

[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");
}

之前

之后

【问题讨论】:

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


    【解决方案1】:

    我认为您需要做的就是在您的渲染器中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
        }
    }
    

    【讨论】:

    • 嗨,尼克,感谢您抽出宝贵的时间。当我将该代码 sn-p 放入其中时,我似乎无法访问 e.NewElement,因此不确定如何设置 Textblock 的 Text 参数(我看到您在编辑中删除了更新的评论,谢谢!)
    • 感谢您的更新,我已经编辑了我上面的评论。干杯!
    • ControlElement 都应该在 OnElementPropertyChanged 中找到,您可能需要检查以确保它们不为空
    • 完美,你是个绅士。谢谢。
    【解决方案2】:

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

    iOS: this.SetNeedsDisplay();
    
    Android: this.Invalidate(); 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-08
      • 2012-07-18
      • 2020-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多