简体   繁体   中英

How to make List<Object> variable appear in DataBinding UI when using WPF in Visual Studio?

I'm in the process of learning WPF and currently exploring data binding. I have a DataGrid control on my form, and in my C# code for the form I have a List<string> variable.

I want to be able to use the Properties UI for the DataGrid in the designer to bind the List<string> to the DataGrid . I cannot figure out what I need to do or where I need to look in the UI to do this.

This is what I am doing:

  1. Click my DataGrid in the UI designer to make it the active control.
  2. Move to the Properties window.
  3. Scroll down to the ItemsSource property.
  4. Click on the field and the UI with Source, Path, Converter and Options pops up.

And when I get to this point I no longer know what to do.

I do not want to accomplish this by writing/modifying XAML. I want to know how it works using the UI.

Having never used the designer before, I can't be totally sure (your use case isn't quite clear either).

That being said, in my designer you

  1. Set the "Binding Type" to "Data Context"
  2. Select the "Custom" text box (needed for me because it doesn't see my DataContext)
  3. Type the name of your property in the "Path" field (you can only bind to Properties)
  4. Hit OK.

Note that this is the same as writing in XAML:

<DataGrid ItemsSource="{Binding MyItemCollection}"/>
<!-- or --!>
<DataGrid ItemsSource="{Binding Path=MytItemsCollection}"/>

There's a reason no one uses the designer....

The other options are more "advanced" binding concepts that you don't normally use on ItemsSource properties.

Note that DataGrid is a poor choice for displaying strings. ListView or ListBox are much better choices, as they don't assume your information has multiple pieces (like DataGrid does).

I understand not liking XAML, as it really intimidated me at first, but I will quickly say that it is a powerful tool. I am not sure how to do it through the designer, but in C# let's say you name your DataGrid 'myDataGrid' and your List is named 'stringList'. It is as simple as the following:

  myDataGrid.ItemsSource = stringList;

and the data grid is now bound to your string list.

Thanks for asking the question! The properties window is so underrated. First you must set the DataContext. It's in the common section of the properties window. Set the data context to whatever view model you need. If you don't have a VM and the List is in the code behind, set the data context to relative source self. Next in the Path write the name of your List. Also, you may want to use ObservableCollection instead of List so your objects are updated in the UI as they change.

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