|
1 | | -# how-to-bind-columns-from-view-model-in-wpf-and-uwp-treegrid-in-mvvm |
| 1 | +# How to Bind Columns from ViewModel in WPF / 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 ViewModel in [WPF TreeGrid](https://www.syncfusion.com/wpf-controls/treegrid) and [UWP TreeGrid](https://www.syncfusion.com/uwp-ui-controls/treegrid) (SfTreeGrid). |
| 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: |
| 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](https://help.syncfusion.com/cr/wpf/Syncfusion.UI.Xaml.TreeGrid.TreeGridTextColumn.html) when creating the ViewModel instance. |
| 24 | + |
| 25 | +### C#: |
| 26 | + |
| 27 | +```c# |
| 28 | +public class ViewModel: NotificationObject |
| 29 | +{ |
| 30 | + #region Private Variables |
| 31 | + |
| 32 | + private ObservableCollection<EmployeeInfo> _employees; |
| 33 | + |
| 34 | + private TreeGridColumns sfGridColumns; |
| 35 | + |
| 36 | + #endregion |
| 37 | + |
| 38 | + public TreeGridColumns SfGridColumns |
| 39 | + { |
| 40 | + get { return sfGridColumns; } |
| 41 | + set |
| 42 | + { |
| 43 | + this.sfGridColumns = value; |
| 44 | + RaisePropertyChanged("SfGridColumns"); |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + #region ctr |
| 49 | + |
| 50 | + public ViewModel() |
| 51 | + { |
| 52 | + this.Employees = GetEmployeesDetails(); |
| 53 | + rowDataCommand = new RelayCommand(ChangeCanExecute); |
| 54 | + this.sfGridColumns = new TreeGridColumns(); |
| 55 | + sfGridColumns.Add(new TreeGridTextColumn() { MappingName = "FirstName" }); |
| 56 | + sfGridColumns.Add(new TreeGridTextColumn() { MappingName = "LastName" }); |
| 57 | + sfGridColumns.Add(new TreeGridTextColumn() { MappingName = "Title" }); |
| 58 | + sfGridColumns.Add(new TreeGridTextColumn() { MappingName = "Salary" }); |
| 59 | + } |
| 60 | + #endregion |
| 61 | +} |
| 62 | +``` |
0 commit comments