将datagrid数据绑定到LocationCollection

时间:2011-07-28 15:49:46

标签: silverlight data-binding

我对datagrid和MapPolyLine-LocationCollection有一个小问题。目前我已经创建了一个网格,其中两列为经度,一列为纬度。我已将datagrid的ItemsSource设置为我的LocationCollection,并将列绑定到相应的位置值,如下面

var lonCol = new DataGridTextColumn {Header =“Longitude”,Binding = new Binding(Longitude){Mode = BindingMode.TwoWay}}

这一切都很好但是,我实际上想让网格有一个单独的列,整个坐标作为其显示值,原因是我可能想要在不同的坐标系中显示项目(UTM for例如),我以为我可以通过某种方式使用值转换器来做到这一点。我的问题是,我无法看到我如何使我的网格有一列绑定到我的LocationCollection中的项目并显示其ToString()值,其次我如何能够根据某种标志转换显示的值。

很抱歉,如果没有解释清楚。

所有帮助非常感谢

1 个答案:

答案 0 :(得分:0)

使用值转换器

可以在DataGrid中仅使用一列
// If you don't specify a property path, Silverlight uses the entire object
// For two way binding make sure you bind it to an IList<LocationWrapper>
var theOneColumn = new DataGridTextColumn ( 
    Header = "Long + Lat",
    Binding = new Binding(){ 
        Mode = BindingMode.TwoWay,  
        Converter = new LongLatConverter()
    }
);


//Converter
public class LongLatConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var loc = value as LocationWrapper;
        return String.Format("Long: {0}, Lat: {0}", loc.Longitude, loc.Latitude);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        //...
    }
}

//Wrapper class for Location so two way binding works
public class LocationWrapper
{
    //The actual location object
    public String Location( get; set;}      
    public LocationWrapper(Location loc)
    {
        this.Location = loc;
    }
}

对于基于标志部分的转换,您可以传入Converter参数来更改转换器的行为。

var theOneColumn = new DataGridTextColumn ( 
    Header = "Long + Lat",
    Binding = new Binding(){ 
        Mode = BindingMode.TwoWay,  
        Converter = new LongLatConverter(),
        ConverterParameter = "UTM" // This is what you want to set
    }
);

// ....
// In the Value Converter
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    var loc = value as Location;

    if( (parameter as string).equals("UTM"))
    {
        //return UTM formated long/lat coordinates 
    }
    else
    {
        return String.Format("Long: {0}, Lat: {0}", loc.Longitude, loc.Latitude);
    }
}