【问题标题】:Add function to Convert function将函数添加到转换函数
【发布时间】:2014-02-26 09:56:55
【问题描述】:

我正在尝试使用来自IValueConverterConvert 函数,但我必须在其中调用另一个函数。我将使用他的返回值,但我得到了一个错误,告诉我在转换器中返回一个对象值,请知道如何避免这种情况。

public void Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    RestClient client = new RestClient();
    client.BaseUrl = "http://";

    RestRequest request = new RestRequest();
    request.Method = Method.GET;
    request.AddParameter("action", "REE");
    request.AddParameter("atm_longitude", location.Longitude);

    client.ExecuteAsync(request, ParseFeedCallBack_ListDistance);
}
public void ParseFeedCallBack_ListDistance(IRestResponse response)
{
    if (response.StatusCode == HttpStatusCode.OK)
    {
        ParseXMLFeedDistance(response.Content);
    }
}
private string ParseXMLFeedDistance(string feed)
{
.... return myvalueToBind;

}

【问题讨论】:

  • 接口“System.Windows.Data.IValueConverter”希望您提供两种方法的实现,Convert 和 ConvertBack,它们都需要您返回一个对象。 void 方法无效。您至少必须返回 null 并将您的转换方法更改为“公共对象转换”。作为旁注,您到底想实现什么?在这种情况下,您使用转换器似乎是错误的方法,我显然无法判断,因为您没有提供一般问题的上下文。
  • 事实上,我需要在列表框中使用纬度和经度 foreach 项目,并使用它们来调用网络服务来获取设备和该项目之间的距离..所以我使用了这种方法,你呢还有其他建议吗?
  • 在这种情况下,您最好在本地进行计算。您有设备坐标和参考坐标。使您免于为列表中的每个项目打开 x 数量的 HTTP 连接,从而节省设备电池和数据使用量。请参阅下面的回复

标签: windows-phone-7 ivalueconverter


【解决方案1】:

计算两个坐标之间距离的简单方法,在这种情况下,假设你有设备的坐标,

using System.Device.Location;

public class GeoCalculator
{
    public static double Distance(double deviceLongitude, double deviceLatitude, double atmLongitude, double atmLatitude)
    {
        //Coordinates of ATM (or origin).
        var atmCoordinates = new GeoCoordinate(atmLatitude, atmLongitude);

        //Coordinates of Device (or destination).
        var deviceCordinates = new GeoCoordinate(deviceLatitude, deviceLongitude);

        //Distance in meters.
        return atmCoordinates.GetDistanceTo(deviceCordinates);
    }
}

因此您的转换器可能如下所示:

public class DistanceConverter : IValueConverter
{
    /// <summary>
    /// This is your device coordinate.
    /// </summary>
    private static GeoCoordinate devCoordinate = new GeoCoordinate(61.1631, -149.9721);

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var location = value as LocationModel;

        if (location != null)
        {
            return GeoCalculator.Distance(devCoordinate.Longitude, devCoordinate.Latitude, location.Longitude, location.Latitude);
        }

        return 0;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

请记住,我个人不会为此使用转换器。我将简单地在我的模型中公开一个简单的属性来执行此计算,因为它是一个简单的逻辑。如果您碰巧是一个纯粹主义者并且不喜欢模型中的任何逻辑,那么循环遍历列表并在模型上设置属性也可以。

【讨论】:

  • 这工作正常,但我正在使用一个网络服务,我在其中传递 atms 的位置和定位设备,然后我得到一个返回它的结果,就像我之前在我的代码中解释的那样
  • 任何想法如何避免解析的返回函数以在转换方法中获取它?
猜你喜欢
  • 2023-03-06
  • 2020-09-06
  • 1970-01-01
  • 2015-01-14
  • 2015-11-17
  • 2020-02-17
  • 2014-05-11
  • 2015-03-25
  • 1970-01-01
相关资源
最近更新 更多