2017-03-03 130 views

回答

3

由於Xamarin.Forms不提供此功能,所以您需要通過爲每個平臺創建一個custom renderer來擴展標籤。通過這樣做,您可以訪問每個平臺上的本機控件(Android上的TextView和iOS上的UILabel),並在此處實施刪除線效果。

  1. 在Android上,您可以在TextView上使用STRIKE_THRU_TEXT_FLAG。在自定義渲染器中需要這樣的東西:someTextView.PaintFlags = Paint.StrikeThruText;
  2. 在iOS上,您應該遵循Xamarin論壇上this thread的指導。基本上,您使用UIStringAttributes來實現預期的結果。

如果您不熟悉自定義渲染器,請參閱入門教程,瞭解如何自定義Entry控制here


編輯:其實,你甚至可以使用效果來關閉它。更多信息here

+0

注:應該是'someTextView.PaintFlags = PaintFlags.StrikeThruText;'' PaintFlags'是引用的適當枚舉,而不是'Paint' –

5

在這裏,你可以製作自己的控件(strikedLabel)並放置這段代碼。爲了讓更多的樂趣和flexiable您可以添加像(IsStriked,StrikeColor等)可綁定屬性,記得在標籤和BoxView中之間的順序

<Grid> 
    <Label VerticalOptions="Center" Text="Sample string" /> 
    <BoxView HeightRequest="3" 
    VerticalOptions="Center" 
    Opacity="0.5" 
    Color="Aqua" /> 
</Grid> 
2

這是非常簡單的使用效果就以下事項步驟:

的XAML

<Label Text="{Binding TotalReatilAmount}" > 
    <Label.Effects> 
     <Helpers:LineThroughEffect /> 
    </Label.Effects> 
</Label> 

不要忘了把下面一行在XAML頭

xmlns:Helpers="clr-namespace:MyNameSpace.Helpers" 

創建一個類從RoutingEffect

public class LineThroughEffect : RoutingEffect 
    {  
     public LineThroughEffect() : base("MyNameSpace.Helpers.PlatformLineThroughEffect") { } 
    } 

繼承創建渲染爲平臺特定

的iOS

[assembly: ResolutionGroupName("MyNameSpace.Helpers")] 
[assembly: ExportEffect(typeof(PlatformLineThroughEffect), nameof(PlatformLineThroughEffect))] 
namespace MyNameSpace.iOS.Renderers 
{ 
    public class PlatformLineThroughEffect : PlatformEffect 
    { 
     protected override void OnAttached() 
     { 
      SetUnderline(true); 
     } 

     protected override void OnDetached() 
     { 
      SetUnderline(false); 
     } 

     protected override void OnElementPropertyChanged(System.ComponentModel.PropertyChangedEventArgs args) 
     { 
      base.OnElementPropertyChanged(args); 

      if (args.PropertyName == Label.TextProperty.PropertyName || 
       args.PropertyName == Label.FormattedTextProperty.PropertyName) 
      { 
       SetUnderline(true); 
      } 
     } 

     private void SetUnderline(bool underlined) 
     { 
      try 
      { 
       var label = (UILabel)Control; 
       if (label != null) 
       { 
        var text = (NSMutableAttributedString)label.AttributedText; 
        if (text != null) 
        { 
         var range = new NSRange(0, text.Length); 
         if (underlined) 
         { 
          text.AddAttribute(UIStringAttributeKey.StrikethroughStyle, 
           NSNumber.FromInt32((int)NSUnderlineStyle.Single), range); 
         } 
         else 
         { 
          text.RemoveAttribute(UIStringAttributeKey.StrikethroughStyle, range); 
         } 
        } 
       } 
      } 
      catch (Exception ex) 
      { 
       ex.Track(); 
      } 
     } 
    } 
}