MVVM Caluculated Column with outside value

2 posts, 0 answers
  1. Daniel
    Daniel avatar
    3 posts
    Member since:
    Jun 2013

    Posted 16 Dec 2015 Link to this post


    I have a list of workers, whom all needs to have an amount paid by way of their hours times a value.

    I have a WorkerModel class:

    public class WorkerModel
        public string Name { get; set; }
        public int HoursWorking { get; set; }

    Then I have a CompanyModel that contains the workers:

    public class CompanyModel
        private ObservableCollection<WorkerModel> _workers = new ObservableCollection<WorkerModel>();
        public ObservableCollection<WorkerModel> Workers
            get { return _workers ; }
            set { _workers = value; }

    And then I have a ViewModel that allows me to bind to the view:

    public class MainViewModel : ViewModelBase
        private readonly CompanyModel _company;
        public MainViewModel()
            _company= new CompanyModel();
        public ObservableCollection<CompanyModel > Workers
            get { return _company.Workers; }
        public decimal PayoutPerHour
            get { return 71M; }

    Lastly my view looks like this:


    <telerik:RadGridView ShowGroupPanel="False"
                                 ItemsSource="{Binding Workers}"
                    <telerik:GridViewDataColumn Header="Name" DataMemberBinding="{Binding Path=Name}" Width="230"></telerik:GridViewDataColumn>
                    <telerik:GridViewExpressionColumn Header="Payout" Width="100" Expression="HoursWorking * PayoutPerHour"></telerik:GridViewExpressionColumn></telerik:GridViewDataColumn>


    My goal is to have the HoursWorking from the WorkerModel, multiply with the PayoutPerHour thats in the ViewModel. I have in this example made the PayoutPerHour a static value, which it is not in my full example. I need the Expressioncolumn to update whenever either of those two properties are updated. But I can't tell the viewmodel what the WorkerModel is doing, since they are in a collection in the CompanyModel.

    Any clever way to do this?

  2. Stefan
    Stefan avatar
    1073 posts

    Posted 21 Dec 2015 Link to this post

    Hello Daniel,

    The most convenient approach for such scenario, would be the WorkerModel to implement INotifyPropertyChanged interface. By doing so, you can subscribe to the PropertyChanged event of each object in the ViewModel and listen for a value change. When such occurs, you can update the ExpressionColumn as per your requirements.

    Best Regards,
    Stefan X1
    Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Feedback Portal and vote to affect the priority of the items
Back to Top