在C#中访问RadGridView的行值

时间:2017-01-30 23:53:11

标签: c# wpf xaml dispatcher radgridview

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

现在我想获取地址的lat和lng值,并在我的地图上找到它们。我遇到的问题是,在选择地址时,我无法访问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>

1 个答案:

答案 0 :(得分:0)

您可以将事件处理程序的sender参数强制转换为Border,然后使用其DataContext属性访问当前数据对象:

BackgroundWorker bg;
public MainWindow()
    {
       bg = new BackgroundWorker();
        bg.DoWork += new DoWorkEventHandler(bg_DoWork);

        bg.WorkerReportsProgress = true;
        bg.WorkerSupportsCancellation = true;
    }
    void bg_DoWork(object sender, DoWorkEventArgs e)
    {
        CompositionTarget.Rendering += StartAnimation;
    }
    private void StartAnimation(Object sender,EventArgs e)
    {
        //code
    }