-1

Can you please help me translate this Xamarin xaml into c#?

BackgroundColor="{Binding IconColor, Converter={StaticResource LocalHexColorFromStringConverter}}"/>

Thanks!

ScumSprocket
  • 347
  • 5
  • 16
  • 1
    https://learn.microsoft.com/en-us/dotnet/api/xamarin.forms.bindableobjectextensions.setbinding?view=xamarin-forms – Jason Nov 02 '20 at 17:32

1 Answers1

1

You can translate it by MyBtn.SetBinding(Button.BackgroundColorProperty, "IconColor", BindingMode.OneTime, new LocalHexColorFromStringConverter()) ;

I make a test with Button's background color.

   Button MyBtn = new Button();
   MyBtn.Text = "test";
   MyBtn.SetBinding(Button.BackgroundColorProperty, "IconColor", BindingMode.OneTime, new LocalHexColorFromStringConverter()) ;
   Content = MyBtn;

Here is LocalHexColorFromStringConverter.cs

  public class LocalHexColorFromStringConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return Color.FromHex((string)value);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value;
        }
    }

Can I ask what the difference is between "new LocalHexColorFromStringConverter()" and "converter: LocalHexColorFromStringConverter()" ?

Do you mean "new LocalHexColorFromStringConverter()" and "converter: LocalHexColorFromStringConverter"?

If so, they are same, converter: LocalHexColorFromStringConverter is wirte type in Xaml , converter: is prefix, it explains the specific path of this class, If you want to call it from any pages, you need to write it in the App.xaml.

For example, you add add it in the App.xaml.

<?xml version="1.0" encoding="utf-8" ?>
<Application xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
             xmlns:converters="clr-namespace:OAuthGoogleDemo"
             x:Class="OAuthGoogleDemo.App">
    <Application.Resources>
       
       <ResourceDictionary>
            <converters:LocalHexColorFromStringConverter x:Key="HexColorFromStringConverter" />
        </ResourceDictionary>
        
    </Application.Resources>
</Application>

Then use it in the Mainpage.xaml with Converter={StaticResource HexColorFromStringConverter}}"

Leon
  • 8,404
  • 2
  • 9
  • 52
  • Can I ask what the difference is between "new LocalHexColorFromStringConverter()" and "converter: LocalHexColorFromStringConverter()" ? I guess I learned to create an instance in App.Xaml, then call it from any page.... is that a typical workflow? – ScumSprocket Nov 04 '20 at 11:30