|
1 | 1 | # how-to-bind-columns-from-view-model-in-wpf-and-uwp-treegrid-in-mvvm
|
2 | 2 |
|
3 |
| -This example illustrates to bind the columns from view model. |
| 3 | +This example illustrates to bind the columns from ViewmModel in [WPF TreeGrid](https://www.syncfusion.com/wpf-controls/treegrid) and [UWP TreeGrid](https://www.syncfusion.com/uwp-ui-controls/treegrid) |
| 4 | + |
| 5 | +You can bind the [SfTreeGrid.Columns](https://help.syncfusion.com/cr/wpf/Syncfusion.UI.Xaml.TreeGrid.SfTreeGrid.html#Syncfusion_UI_Xaml_TreeGrid_SfTreeGrid_Columns) property in ViewModel by having the binding property of `Syncfusion.SfGrid.UI.Xaml.TreeGrid.Columns` type. Thus, you can set binding to the `SfTreeGrid.Columns` property that provides DataContext of `TreeGrid` in ViewModel. |
| 6 | + |
| 7 | +## XAML code: |
| 8 | + |
| 9 | +```xml |
| 10 | +<syncfusion:SfTreeGrid Name="treeGrid" |
| 11 | + Grid.Row="1" |
| 12 | + ChildPropertyName="ReportsTo" |
| 13 | + AutoExpandMode="AllNodesExpanded" |
| 14 | + ShowRowHeader="True" |
| 15 | + Columns="{Binding SfGridColumns, Mode=TwoWay}" |
| 16 | + AutoGenerateColumns="False" |
| 17 | + ItemsSource="{Binding Employees}" |
| 18 | + ParentPropertyName="ID" |
| 19 | + SelfRelationRootValue="-1"> |
| 20 | +</syncfusion:SfTreeGrid> |
| 21 | +``` |
| 22 | + |
| 23 | +Refer to the following code example in which the TreeGrid column is populated with some `TreeGridTextColumn` when creating the ViewModel instance. |
| 24 | + |
| 25 | +## C# code |
| 26 | + |
| 27 | +```c# |
| 28 | +public class ViewModel: NotificationObject |
| 29 | +{ |
| 30 | + private TreeGridColumns sfGridColumns; |
| 31 | + public TreeGridColumns SfGridColumns |
| 32 | + { |
| 33 | + get { return sfGridColumns; } |
| 34 | + set |
| 35 | + { this.sfGridColumns = value; |
| 36 | + RaisePropertyChanged("SfGridColumns"); |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + public ViewModel() |
| 41 | + { |
| 42 | + this.Employees = GetEmployeesDetails(); |
| 43 | + rowDataCommand = new RelayCommand(ChangeCanExecute); |
| 44 | + this.sfGridColumns = new TreeGridColumns(); |
| 45 | + sfGridColumns.Add(new TreeGridTextColumn() { MappingName = "FirstName" }); |
| 46 | + sfGridColumns.Add(new TreeGridTextColumn() { MappingName = "LastName" }); |
| 47 | + sfGridColumns.Add(new TreeGridTextColumn() { MappingName = "Title" }); |
| 48 | + sfGridColumns.Add(new TreeGridTextColumn() { MappingName = "Salary" }); |
| 49 | + } |
| 50 | +} |
| 51 | +``` |
0 commit comments