简体   繁体   中英

Binding Grid Datacontext to Model

Is it possible to bind model as property to grid datacontext?

Example

Model

public class Model
{
   field1....
   field2....
}

Then create item

   private Model _newModel;
   public Model NewModel
   {
        get { return _newModel; }
        set { _newModel = value; OnPropertyChanged(); }
   }


NewModel = (new Model({
  field1 = "field1",
  field2 = "field2"
});

So is it possible to bind NewModel to grid datacontext

<Grid DataContext="{Binding NewModel}" >
    <Label Content="{Binding NewModel.field1}" />
    <Label Content="{Binding NewModel.field2}" />
</Grid>

Binding Path is relative to binding source, which is equal to DataContext by default.

Child elements (Labels here) inherit DataContext from parent (Grid). So Labels have NewModel for DataContext.

So binding should look like:

<Grid DataContext="{Binding NewModel}" >
    <Label Content="{Binding field1}" />
    <Label Content="{Binding field2}" />
</Grid>

And in model properties must look like this

private string _prop;
public string Prop
{
    get { return _prop; }
    set { _prop = value; OnPropertyChanged(); }
}

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