简体   繁体   English

将数据绑定到数据网格

[英]Binding Data to Data Grid

I currently have a URL request the brings back XML data. 我目前有一个URL请求带回XML数据。 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. 我的wpf DataGrid叫做Movie_DataGrid。 Any help would be great on how to get this data to the DataGrid. 如何将这些数据提供给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. 当单步执行代码的每一步时,XML存储正常,并且Retrivalinfo类和Retrievalinfo convertedMovie = new Retrievalinfo()之间的所有标记属性都相同,但是此方法的应用程序错误。

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. 我还提供了一些我会得到的XML样本。

<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. 下面是我想要在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. 我写了一篇冗长的aswer,但是,这里有一个快速的样本,你可以用作参考并自己弄清楚细节。 MVVM not included :D MVVM不包括在内: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 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 视图模型中的ObservableCollection<RetrievalInfo>用于存储检索到的数据
  • A Datagrid (or perhaps a grid view) in your XAML that has its item source bound to the above property XAML中的Datagrid(或者可能是网格视图),其项目源绑定到上面的属性
  • 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 检索代码应修改可观察集合,以便它们出现在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 您可以使用以下博客中提供的代码段读取xml到对象列表

Blog Link: 博客链接:

http://danielwylie.me/blog/2010/04/c-convert-xml-to-an-object-or-list-of-an-object 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 您可以使用以下代码段分配dataGrid的ItemSource

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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