Как я могу заставить работать этот код рендерера xamarin switch? - PullRequest
0 голосов
/ 18 марта 2020

Я пытаюсь заставить работать этот переключатель рендерера, но Visual Studio не распознает CustomSwitch , и компиляция завершается неудачно с сообщением "Тип: local: CustomSwitch" не найден. Убедитесь, что вы не пропали ссылка на сборку и то, что все ссылки на сборки были созданы. (MasterDetailPageNavigation) "

У меня есть CustomSwitch.cs в папке моего проекта:

using Xamarin.Forms;

public class CustomSwitch : Switch
{
    public static readonly BindableProperty SwitchOffColorProperty =
      BindableProperty.Create(nameof(SwitchOffColor),
          typeof(Color), typeof(CustomSwitch),
          Color.Default);

    public Color SwitchOffColor
    {
        get { return (Color)GetValue(SwitchOffColorProperty); }
        set { SetValue(SwitchOffColorProperty, value); }
    }

    public static readonly BindableProperty SwitchOnColorProperty =
      BindableProperty.Create(nameof(SwitchOnColor),
          typeof(Color), typeof(CustomSwitch),
          Color.Default);

    public Color SwitchOnColor
    {
        get { return (Color)GetValue(SwitchOnColorProperty); }
        set { SetValue(SwitchOnColorProperty, value); }
    }

    public static readonly BindableProperty SwitchThumbColorProperty =
      BindableProperty.Create(nameof(SwitchThumbColor),
          typeof(Color), typeof(CustomSwitch),
          Color.Default);

    public Color SwitchThumbColor
    {
        get { return (Color)GetValue(SwitchThumbColorProperty); }
        set { SetValue(SwitchThumbColorProperty, value); }
    }

    public static readonly BindableProperty SwitchThumbImageProperty =
      BindableProperty.Create(nameof(SwitchThumbImage),
          typeof(string),
          typeof(CustomSwitch),
          string.Empty);

    public string SwitchThumbImage
    {
        get { return (string)GetValue(SwitchThumbImageProperty); }
        set { SetValue(SwitchThumbImageProperty, value); }
    }
}

В проекте. У меня есть папка droid CustomSwitchRenderer.cs :

using System;
using Android.Graphics;
using Android.Widget;
using MasterDetailPageNavigation.Droid;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;

[assembly: ExportRenderer(typeof(CustomSwitch), typeof(CustomSwitchRenderer))]
namespace MasterDetailPageNavigation.Droid
{
    [Obsolete]
    public class CustomSwitchRenderer : SwitchRenderer
    {
        private CustomSwitch view;
        protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Switch> e)
        {
            base.OnElementChanged(e);
            if (e.OldElement != null || e.NewElement == null)
                return;
            view = (CustomSwitch)Element;
            if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.JellyBean)
            {
                if (this.Control != null)
                {
                    if (this.Control.Checked)
                    {
                        this.Control.TrackDrawable.SetColorFilter(view.SwitchOnColor.ToAndroid(), PorterDuff.Mode.SrcAtop);
                    }
                    else
                    {
                        this.Control.TrackDrawable.SetColorFilter(view.SwitchOffColor.ToAndroid(), PorterDuff.Mode.SrcAtop);
                    }
                    this.Control.CheckedChange += this.OnCheckedChange;
                    UpdateSwitchThumbImage(view);
                }
                //Control.TrackDrawable.SetColorFilter(view.SwitchBGColor.ToAndroid(), PorterDuff.Mode.Multiply);  
            }
        }

        private void UpdateSwitchThumbImage(CustomSwitch view)
        {
            if (!string.IsNullOrEmpty(view.SwitchThumbImage))
            {
                view.SwitchThumbImage = view.SwitchThumbImage.Replace(".jpg", "").Replace(".png", "");
                int imgid = (int)typeof(Resource.Drawable).GetField(view.SwitchThumbImage).GetValue(null);
                Control.SetThumbResource(Resource.Drawable.icon);
            }
            else
            {
                Control.ThumbDrawable.SetColorFilter(view.SwitchThumbColor.ToAndroid(), PorterDuff.Mode.Multiply);
                // Control.SetTrackResource(Resource.Drawable.track);  
            }
        }

        private void OnCheckedChange(object sender, CompoundButton.CheckedChangeEventArgs e)
        {
            if (this.Control.Checked)
            {
                this.Control.TrackDrawable.SetColorFilter(view.SwitchOnColor.ToAndroid(), PorterDuff.Mode.SrcAtop);
            }
            else
            {
                this.Control.TrackDrawable.SetColorFilter(view.SwitchOffColor.ToAndroid(), PorterDuff.Mode.SrcAtop);
            }
        }
        protected override void Dispose(bool disposing)
        {
            this.Control.CheckedChange -= this.OnCheckedChange;
            base.Dispose(disposing);
        }
    }
}

И это соответствующая часть моего xaml :

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:behavior="clr-namespace:MasterDetailPageNavigation.XAML"
             xmlns:local="clr-namespace:MasterDetailPageNavigation"
             x:Class="MasterDetailPageNavigation.XAML.CompletaCadastroProf"
             BackgroundImageSource="background">
    <ContentPage.Content>
       <StackLayout>

        <local:CustomSwitch SwitchOnColor="Red" Grid.Column="0" Grid.Row="0" />

 ...
 ...

Может быть Я забыл добавить ссылку, вы, ребята, видите, что я делаю не так?

Ответы [ 2 ]

0 голосов
/ 18 марта 2020

Я пропустил, чтобы дать пространство имен для CustomSwitch.cs, только что добавил

namespace MasterDetailPageNavigation.XAML
{ 
...
}

и все работает сейчас.

0 голосов
/ 18 марта 2020

Прежде всего, если вы не поместите свой CustomSwitch в путь root этого проекта, как на этом снимке экрана, enter image description here

Пожалуйста, измените другой префикс, который я изменил myswitch мой код похож на следующий формат.

  <myswitch:CustomSwitch SwitchOffColor="Green"  SwitchOnColor="Red"  />

Если у VS есть пространство имен автоассоциирования, пожалуйста, нажмите Alt+Enter, вы получите следующий снимок. Щелкните по add xmlns xxxxxxxx enter image description here

Если VS не имеет пространства имен для автоматической ассоциации, вы можете щелкнуть правой кнопкой мыши по элементу PCL, выберите Properties. enter image description here

Затем скопируйте значение пространства имен по умолчанию. enter image description here

Откройте соответствующий xaml и добавьте xmlns:myswitch="clr-namespace:xxxxxxx":

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:myswitch="clr-namespace:SqliteFormsMVVM"
             mc:Ignorable="d"
             x:Class="SqliteFormsMVVM.MainPage">

    <StackLayout>
        <myswitch:CustomSwitch SwitchOffColor="Green"  SwitchOnColor="Red"  />


    </StackLayout>

</ContentPage>

Если вы выполнили вышеуказанные настройки, эта проблема все еще существует, пожалуйста, закройте VS, откройте папку вашего проекта, удалите все папки bin и obj (папки xxx, xxx. Android, xxx. iOS), в конце перестройте ваш проект.

...