Accessing public properties in ViewModel from View's code behind

Topics: Questions
Aug 2, 2012 at 8:28 PM


what I am trying to accomplish is to bind a gridView to a variable number of columns. I have an example working, however this is not using MVVM (the data is hard-coded).

How can I access public properties in ViewModel from View's code behind? Also, I need to access the properties after they have been filled with data (for example: I change a project using a combobox, the viewModel updates all its properties, then I need to access this somehow in the view's code-behind and programatically create the columns based on the data extracted from the viewModel and do the binding. The column names number changes with each project).

I have tried another path: tried to do it all in xaml using ItemsControl and that one failed.

Is what I am trying to do possible or how should I approach this?

Thank you,



        // [constructors]
        public TranscriptView()
            this.genericFilterDescriptor = new FilterDescriptor<TranscriptItem>();
            // TranscriptViewModel vm = (TranscriptViewModel)this.DataContext;
            // var a = vm.TranscriptItems;
            // var a = ((TranscriptViewModel)(this.DataContext)).TranscriptItems;
            ?????? how to access the view model ????
var columnNameArray = ExtractcolumnNames(vm.TransccriptItems);
         }         //--------------------------------------------------------------------------------         // [methods]         //--------------------------------------------------------------------------------         public void BindingColumns(string[] columnNameArray)         {             foreach (string columnName in columnNameArray)             {                 GridViewDataColumn templateColumn1 = new GridViewDataColumn();                 templateColumn1.ColumnGroupName = columnName;                 templateColumn1.Header = Wordify(columnName);                 templateColumn1.CellTemplate = (DataTemplate)Resources["InFieldQuestionColumnTemplate"];                 radGridView.Columns.Add(templateColumn1);                 radGridView.Columns.Add(templateColumn1);             }         }         public void BindingItemsSource(ObservableCollection<TranscriptItem> transcriptItems)         {             radGridView.ItemsSource = transcriptItems;         }
Aug 3, 2012 at 1:41 PM

A view (in Catel) always exposes the view model using the ViewModel property. By default, this is of type IViewModel, but you can easily cast this if you *know* the view model type.

For example:

public new MyViewModel ViewModel { get { return (MyViewModel)base.ViewModel; } }

and then you have a string typed view model which you can use.