在 C# 中访问 RadGridView 的行值

Access row values of RadGridView in C#

我可能会以错误的方式解决这个问题,但我不确定。我有一个搜索栏,用户可以输入地址。然后将请求发送到 Google 的 API 并且与输入的地址对应的一组地址将显示在我的 RadGridView 中。我的地址显示正常。

现在我想获取地址的纬度和经度值并在我的地图上找到它们。我遇到的问题是在选择地址后我无法访问 RadGridView 中的行值。我创建了一个方法,该方法在用户选择地址时被命中,但 grid.SelectedItem 返回 null。

我可能用错了方法。有什么想法吗?

xaml.cs

private void SearchTB_KeyDown(object sender, KeyEventArgs e)
{
searchclose.Opacity = 1;
    if (e.Key == Key.Enter)
    {
        var address = SearchTB.Text;

    var requestUri = string.Format("http://localhost/media/TextToSpeech/TextToSpeechService.svc/getDataProxy?url=https://maps.googleapis.com/maps/api/geocode/json?address={0}&key=AIzaSyCgsNpuUoH7m6U7lqeZjlLZ3MgM15PW15o", Uri.EscapeDataString(address));

        HttpWebRequest request = WebRequest.Create(requestUri) as HttpWebRequest;
        request.Method = "GET";
        IAsyncResult result = request.BeginGetResponse(new AsyncCallback(RequestCompleted), request);
    }
} 

private void RequestCompleted(IAsyncResult result)
{
    var request = (HttpWebRequest)result.AsyncState;
    var response = (HttpWebResponse)request.EndGetResponse(result);
    Stream stream = response.GetResponseStream();

    try
    {
        StreamReader reader = new StreamReader(stream);
        string text = reader.ReadToEnd();

        Regex rgx = new Regex("<.*\>");
        string newResult = rgx.Replace(text, "");

        JObject json = JObject.Parse(newResult);
        JArray results = (JArray)json["results"];

        List<object> locationList = new List<object>();
        ObservableCollection<object> AddressList = new ObservableCollection<object>();

        if (results.Count == 0)
        {
            Dispatcher.BeginInvoke(new Action(() => MessageBox.Show("No results found")));
        }
        else
        {
            foreach (JObject obj in results)
            {
                if (obj == null)
                {
                    Dispatcher.BeginInvoke(new Action(() => MessageBox.Show("Address returned no results")));
                }
                string formattedAddress = (string)obj["formatted_address"];
                AddressList.Add(formattedAddress);

                object loc = (object)obj["geometry"]["location"];
                locationList.Add(loc);
                //TODO Add exception handling
            }
            Dispatcher.BeginInvoke(new Action(() => addressGrid.ItemsSource = AddressList));
        }

    }
    catch (Exception ex)
    {
        Dispatcher.BeginInvoke(new Action(() => MessageBox.Show("Error" + ex.Message)));
    }

}

    private void SelectedAddress_Click(object sender, RoutedEventArgs e)
    {
        object dodo = "";
        dodo = addressGrid.SelectedItem;
    }

xaml

<!--Address Results-->
<telerik:RadGridView  Grid.Row="2" AutoGenerateColumns="False" x:Name="addressGrid" Margin="18 0 0 18" CanUserFreezeColumns="False" CanUserSelect="True"
        EnableColumnVirtualization="True" EnableRowVirtualization="True" ShowGroupPanel="False" ScrollViewer.VerticalScrollBarVisibility="Visible"
        CanUserDeleteRows="False" RowIndicatorVisibility="Collapsed" DataLoadMode="Asynchronous" HeaderRowStyle="{StaticResource ZoneActivityHeaderRowStyle}"
        GroupPanelStyle="{StaticResource GroupPanelStyle}" Background="#00000000" VerticalGridLinesBrush="#00000000" HorizontalGridLinesBrush="#00000000" AlternationCount="2" 
        RowHeight="32" ShowColumnHeaders="False" RowStyle="{StaticResource ActivityRowStyle}" AlternateRowStyle="{StaticResource ActivityAlternateRowStyle}">

    <telerik:RadGridView.Columns>

        <telerik:GridViewDataColumn Header="Targetting" Width="35" IsReadOnly="True" IsFilterable="False" ShowDistinctFilters="True" IsGroupable="False" IsVisible="True">
            <telerik:GridViewDataColumn.CellTemplate>
                <DataTemplate>
                    <ctrl:TargetButton x:Name="targetButton" VerticalAlignment="Center" HorizontalAlignment="Center" Visibility="Visible" />
                </DataTemplate>
            </telerik:GridViewDataColumn.CellTemplate>
        </telerik:GridViewDataColumn>

        <telerik:GridViewDataColumn Header="Address" Width="*" IsReadOnly="True"
                IsFilterable="False" ShowDistinctFilters="True" IsGroupable="False">
            <telerik:GridViewDataColumn.CellTemplate>
                <DataTemplate>
                    <Grid>
                        <TextBlock Text="{Binding}" Foreground="White" FontFamily="Segoe UI"
                                   FontSize="12" VerticalAlignment="Center" Margin="5" TextWrapping="Wrap" />
                        <Border Background="#00000000" Height="40" Margin="-5 0" Cursor="Hand" MouseLeftButtonDown="SelectedAddress_Click" />
                    </Grid>
                </DataTemplate>
            </telerik:GridViewDataColumn.CellTemplate>
        </telerik:GridViewDataColumn>

    </telerik:RadGridView.Columns>
</telerik:RadGridView>

您可以将事件处理程序的 sender 参数转换为 Border,然后使用其 DataContext 属性:

访问当前数据对象
private void SelectedAddress_Click(object sender, RoutedEventArgs e)
{
    Border border = sender as Border;
    object dodo = border.DataContext;
    string address = dodo as string;
    if (!string.IsNullOrEmpty(address))
    {
        //...
    }
}