简体   繁体   中英

Bind object properties to a datagrid in WPF

I have the following class:

public class Sp3dItem
{
    public Sp3dItem()
    {
        Items= new ObservableCollection<Sp3dItem>();
    }

    public string OID
    {
        get;
        set;
    }

    public string Name
    {
        get;
        set;
    }

    public string Type
    {
        get;
        set;
    }

    public ObservableCollection<Sp3dItem> Items
    {
        get;
        set;
    }
}

I need to show the properties of an instance of this object to a Datagrid (or any other type of grid). Like the Properties Window in Visual Studio. But there are certain properties that I don't care, like 'Items', I only need to show properties of string Type, and only the ones with non empty values (this last one would be a plus, not a real need).

The question is, can I do something like this with binding or do I have to assembly the data on the grid manually?

Sounds like you want a property grid to view the properties of a single object instance , where each property/value pair is a 'row', yes? If that's the case, look into some of the third-party Property Grid controls. The WPF Extended Toolkit has a free one.

Typically, these grids can automatically discover the properties of the target object, and you can choose to hide certain properties by adorning them with [Browsable(false)] .

Yes... it's possible and easy once you figure out how the built-in binding wizard works.

This example is for a

<Label...
  1. Create a static instance to your view model in the View. By doing this the designer will show the properties of the Viewmodel in the properties page once you start "wiring up the bindings"...
//in code behind
public static string Error
{
  get { return _Error; }
  set { _Error = value; }
}

Now click on the XMAL component in designer just once.

   <Label Grid.Row="2"  <=Click here one time
  1. In the properties page, click the icon (small square on far right side of property) to start the binding process

属性页

  1. Select "Create Data Binding"

在此处输入图片说明

  1. Select 'FindAncestor' then the MainWindow of interest, and finally the static property.

寻找祖先

  1. Click ok and the bindings are set in XAML Automatically.
 <Label Grid.Row="2" 
   Content="{
    Binding Error, 
    RelativeSource={
     RelativeSource FindAncestor, 
     AncestorType={x:Type local:MainWindow}}}"/>

The verbosity above just says:

  • Look in MainWindow's static properties for Error.
  • Make this Label's content that value.

If you want you can also edit the template for the Datagrid, but that's not relevant to your question.

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