如何将 Xamarin Xaml IValueConverter 翻译成 C#?

How to translate Xamarin Xaml IValueConverter into C#?

你能帮我把这个 Xamarin xaml 翻译成 c# 吗?

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

谢谢!

您可以通过MyBtn.SetBinding(Button.BackgroundColorProperty, "IconColor", BindingMode.OneTime, new LocalHexColorFromStringConverter()) ;

翻译

我用Button的背景颜色做了个测试

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

这里是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()" ?

您是指“new LocalHexColorFromStringConverter()”和“转换器:LocalHexColorFromStringConverter”吗?

如果是,它们是一样的,converter: LocalHexColorFromStringConverter是Xaml中的wirte类型,converter:是前缀,说明了这个class的具体路径,如果你想从任何页面调用它,你需要把它写在 App.xaml.

比如你在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>

然后在 Mainpage.xaml 和 Converter={StaticResource HexColorFromStringConverter}}"

中使用它