Как вычислить значение из длины сборщика в Xamarin - PullRequest
0 голосов
/ 15 октября 2019

Моя цель - создать конвертер длины на xamarin. Я создал функцию выбора, чтобы пользователи могли выбирать, какую длину им нужно конвертировать.

Но для следующего шага я не знаю, как создать метод, который может обрабатывать и устанавливать значение каждой длины и кратно значению, которое запрашивает пользователей формы

Может кто-нибудь помочь мне с этимметод

namespace LengthConversion
{
   public class PickerLength 
    {
        public int rate = 0;


        public List<Length> LengthList { get; set; }

        public PickerLength()
        {
            LengthList = GetLength().OrderBy(t => t.Value).ToList();
        }

        public List<Length> GetLength()
        {
            var length = new List<Length>()
            {
                new Length() {Key = 1, Value="Millimetres(mm)"},
                new Length() {Key = 2, Value="Centimetre(cm)"},
                new Length() {Key = 3, Value="Meters(m)"},
                new Length() {Key = 4, Value="Kilometers(km)"},
                new Length() {Key = 5, Value="Feet(ft)"},
                new Length() {Key = 6, Value="Inches(in)"},
                new Length() {Key = 7, Value="Decimeter"},
                new Length() {Key = 8, Value="Mile(m)"},
                new Length() {Key = 9, Value="Yerd"},
                new Length() {Key = 10, Value="Furlong"},
                new Length() {Key = 11, Value="Hand(horses)"},
                new Length() {Key = 12, Value="Fathom"}
            };


            return length;
        }


    }


    public class Length
    {
        public int Key { get; set; }
        public string Value { get; set; }
    }

}
    <ScrollView>
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="1*" />
                <RowDefinition Height="3*" />
                <RowDefinition Height="3*" />
                <RowDefinition Height="3*" />
                <RowDefinition Height="1*" />
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="1*" />
                <ColumnDefinition Width="3*" />
                <ColumnDefinition Width="1*" />
            </Grid.ColumnDefinitions>
            <StackLayout Grid.Row="2" Grid.Column="1">
                <Label Text="Select Length" HorizontalTextAlignment="Center" />
                <Picker
                        ItemsSource="{Binding LengthList}"  
                        ItemDisplayBinding="{Binding Value}"
                        IsEnabled="{Binding CanConvert}" />
                <Entry
                        x:Name="ConvertSource"
                        Text="{Binding SourceValue, Mode=TwoWay}"
                        IsEnabled="{Binding CanConvert}">
                </Entry>
            </StackLayout>

            <StackLayout Grid.Row="3" Grid.Column="1">
                <Label Text="Target Length" HorizontalTextAlignment="Center" />
                <Picker
                       ItemsSource="{Binding LengthList}"  
                        ItemDisplayBinding="{Binding Value}"
                        IsEnabled="{Binding CanConvert}" />
                <Entry
                        x:Name="ConvertTarget"
                        Text="{Binding TargetValue, Mode=OneWay}"
                        IsEnabled="False" />
            </StackLayout>
        </Grid>
    </ScrollView>
</ContentPage>
namespace LengthConversion
{

    [XamlCompilation(XamlCompilationOptions.Compile)]

    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
            BindingContext = new PickerLength();
        }
    }
}

1 Ответ

1 голос
/ 15 октября 2019

Это можно сделать, выбрав базовую единицу измерения, например Meters. Затем сохраните коэффициент для всех других единиц измерения. Затем преобразуйте каждый вход в эталонную единицу измерения и, наконец, в целевую единицу измерения.

Это не единственный способ сделать это, ни готовый к производству образец.

Например:

private readonly UnitOfMeatures _referenceUnits = UnitOfMeasures.Meter;

// Multiply the input values by these to get to the reference units.
// Divide the reference values by these to get to the output units.
private const double COEFFICIENT_METER = 1.0f; 
private const double COEFFICIENT_KILOMETER = 1000.0f;    
private const double COEFFICIENT_FOOT = 0.3048f;    
private const double COEFFICIENT_INCH = 0.0254f;         // use Google to find these.

// Create map of UnitOfMeasures to coefficients
private Dictionary<UnitOfMeasures, double> _coefficientMap = new Dictionary<UnitOfMeasures, double>() {
    {UnitOfMeasures.Meter, COEFFICIENT_METER}, {UnitOfMeasure.Kilometer, COEFFICIENT_KILOMETER} // etc...
};

public double ConvertUnits(UnitOfMeasures inputUnits, double value, UnitOfMeasures outputUnits) {
    double result = 0.0f;

    // convert to reference units
    result = value * _coefficientMap[inputUnits];

    // convert to output units
    result = result / _coefficientMap[outputUnits];

    return result;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...