Skip to main content
 首页 » 编程设计

c#之XAML 转换器如何做更多事情

2024年02月05日15wuhuacong

在 angular 中可以对文本进行一些过滤,例如:

<div ng-bind="vm.value | filter1| filter2| filter3" 

并且当序列被维护时。 这是如何在 XAML 中完成的?特别是 xamarin。

请您参考如下方法:

这是通过使用 Xamarin Forms 中的转换器完成的:

<?xml version="1.0" encoding="utf-8" ?> 
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" 
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
         x:Class="XamlSamples.SharedResourcesPage" 
         Title="Shared Resources Page"> 
 <ContentPage.Resources> 
   <ResourceDictionary> 
     <local:DoubleToIntConverter x:Key="intConverter" /> 
   </ResourceDictionary> 
 </ContentPage.Resources> 
  <StackLayout> 
   <Label Text="{Binding Color.R, 
          Converter={StaticResource intConverter}, 
          ConverterParameter=255, 
          StringFormat='R={0:X2}'}" /> 
  </StackLayout> 
</ContentPage> 

转换器:

class DoubleToIntConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, 
                          object parameter, CultureInfo culture) 
    { 
        double multiplier; 
 
        if (!Double.TryParse(parameter as string, out multiplier)) 
            multiplier = 1; 
 
        return (int)Math.Round(multiplier * (double)value); 
    } 
 
    public object ConvertBack(object value, Type targetType, 
                              object parameter, CultureInfo culture) 
    { 
        double divider; 
 
        if (!Double.TryParse(parameter as string, out divider)) 
            divider = 1; 
 
        return ((double)(int)value) / divider; 
    } 
} 

更多信息在这里:https://developer.xamarin.com/guides/xamarin-forms/user-interface/xaml-basics/data_binding_basics/