简体   繁体   中英

Binding Data to Data Grid

I currently have a URL request the brings back XML data. I store that data in a document that is read and finds the information between certain attributes, and assigns those values to the my assigned variables. my wpf DataGrid is called Movie_DataGrid. Any help would be great on how to get this data to the DataGrid.

-- EDIT --

I updated my code with a new way i am trying to get my results. When stepping through each step of the code, the XML is storing fine, and all tag attributes between the Retrivalinfo class and the Retrievalinfo convertedMovie = new Retrievalinfo() are the same, but application errors out at this method.

My new issue is, the values within the attributes is not being grabbed and stored. I have also put a sample of what XML I would get back.

<root response="True">
<movie title="Up in the Air" year="2009" rated="R" released="23 Dec 2009" runtime="109 
min" genre="Drama, Romance" director="Jason Reitman" writer="Walter Kirn (novel), Jason
Reitman (screenplay), Sheldon Turner (screenplay)" actors="George Clooney, Vera Farmiga,
Anna Kendrick, Jason Bateman" plot="With a job that has him traveling around the country
firing people, Ryan Bingham leads an empty life out of a suitcase, until his company
does the unexpected: ground him." language="English" country="USA" awards="Nominated for
6 Oscars. Another 64 wins & 66 nominations."poster="http://ia.mediaimdb.com/images/M/MV5BMTI3MzYxMTA4NF5BMl5BanBnXkFtZTcwMD
E4ODg3Mg@@._V1_SX300.jpg" metascore="83" imdbRating="7.5" imdbVotes="215,961" imdbID="tt1193138" type="movie"/>
</root>    


     // This action will seach the IMDb API for the associated infromation for the IMDBID that is tagged with the title you chose in the ListBox.
     private void Movie_List_SelectionChanged(object sender, SelectionChangedEventArgs e)
     {   // Grabs the IMDBID associated to the movie title selected to be used with the second API request.
        var p = Movie_List.SelectedIndex;

        string titleID = structholder[p].IMDBID;

        // Prepares 2nd API URL request to get data for chosen title.
        // Creates a XML Document  to store the xml data that was sent back by the API.
        XmlDocument doc = new XmlDocument();
        doc.Load("http://www.omdbapi.com/?i=" + titleID + "&r=XML");

        // Creates a XML Noedlist to store the values that are going to be associated with the given attribute tag.
        XmlNodeList movieList = doc.GetElementsByTagName("movie");

        var movie = movieList.Item(0);

        Retrievalinfo convertedMovie = new Retrievalinfo()
        {
            title = movie.Attributes["title"].ToString(),
            actors = movie.Attributes["actors"].ToString().Split(',').ToList(),
            genre = movie.Attributes["genre"].ToString(),
            rated = movie.Attributes["rated"].ToString(),
            imdbRating = movie.Attributes["imbdRating"].ToString(),
            released = movie.Attributes["released"].ToString(),
            runtime = movie.Attributes["runtime"].ToString(),
        };

        List<Retrievalinfo> gridInfo = new List<Retrievalinfo>();
        Movie_DataGrid.ItemsSource = gridInfo;


Here is the class where each variable is stored that I want to display in the DataGrid.

namespace WpfApplication3
{
    public class Retrievalinfo
    {
       public Retrievalinfo()
        {
            actors = new List<string>();
        }

        //Creating a list of info objects that will store all returned data for selected title.
        public string title; 
        public List<string> actors; 
        public string genre;
        public string rated;
        public string imdbRating; 
        public string released; 
        public string runtime;

    }

    }

I though of writing a lengthy aswer but instead, here's a quick sample for you that you can use as reference and figure out the details yourself. MVVM not included :D

Hope it helps.

Codebehind

namespace MyMovies
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            DataContext = this;

            Movies = new ObservableCollection<Movie>()
                {
                    new Movie("Lock, Stock and Two Smoking Barrels", 4),
                    new Movie("Life of Brian", 5),
                };

            var addMovieCommand = new RoutedUICommand();
            CommandManager.RegisterClassCommandBinding(typeof(Window),
                new CommandBinding(
                    addMovieCommand,
                    (sender, args) => AddMovie(),
                    (sender, args) => args.CanExecute = true));
            AddMovieCommand = addMovieCommand;
        }

        public ObservableCollection<Movie> Movies { get; set; }

        public ICommand AddMovieCommand { get; set; }

        private void AddMovie()
        {
            Movies.Add(new Movie(Guid.NewGuid().ToString(), 3));
        }
    }

    public class Movie
    {
        public Movie(string name, int stars)
        {
            Name = name;
            Stars = stars;
        }

        public string Name { get; set; }
        public int Stars { get; set; }
    }
}

XAML

<Window x:Class="MyMovies.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <StackPanel>
            <DataGrid 
                HorizontalAlignment="Stretch" 
                VerticalAlignment="Stretch"
                ItemsSource="{Binding Movies}">
            </DataGrid>
            <Button Content="Add movie" Command="{Binding AddMovieCommand}" />
        </StackPanel>
    </Grid>
</Window>

Which gives you

未找到

If I am understanding your question correctly, you need a few pieces:

  • An ObservableCollection<RetrievalInfo> in your view model to store the retrieved data
  • A Datagrid (or perhaps a grid view) in your XAML that has its item source bound to the above property
  • Columns in the above control to represent each of your data pieces.
  • The retrieval code should modify the observable collection so they appear on your UI

I would be happy to provide samples for any or all of those pieces that you aren't sure how to implement.

You can read the xml to List of object using the code snippet provided in the following Blog

Blog Link:

http://danielwylie.me/blog/2010/04/c-convert-xml-to-an-object-or-list-of-an-object

You can assign the ItemSource of dataGrid by using the following code snippet

Movie_DataGrid.ItemsSource = list;
        //here list object from  public static List<T> XmlToObjectList<T>(string xml, string nodePath)  method

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM