How to access ViewModel's instance in Codebehind ?

Apr 21, 2010 at 3:04 PM

Hi,

I am stuck in a issue here, and I think I might need to access a View's chart control in my ModelView.

Can I do this ? Is it possible to do ?

Actually I need to dynamically add AreaSeries in my Chart control , and I couldn't figure out how to this by setting the DataContext of Chart control. So I was thinking to add series at run time in code behind.

And one more question , how can I access my ViewModel's instance in my View's code behind ?

 

Thanks for your support.

Shah

Coordinator
Apr 21, 2010 at 7:22 PM

Hi,

 

1) For your series, I am not sure how the chart control you use works, but in the controls I used before, the series were an ObservableCollection, so you can expose the series in the ViewModel and bind to that from your Chart control. If you want to add or remove a Series, just add or remove it in the ObservableCollection, and the bindings will do the rest.

2) In the View, you can access the ViewModel by casting the property DataContext. For example:

var vm = this.DataContext as MainViewModel;

 

Cheers,

Laurent

Apr 22, 2010 at 7:11 AM

I am using Silverlight toolkit 4 chart controls,like this.

 <chartingToolkit:Chart Title="Chronological" x:Name="AreaSeries" >
            <chartingToolkit:Chart.Series>
                <chartingToolkit:AreaSeries Title="Logistics X" ItemsSource="{Binding Series_X}" DependentValuePath="value" IndependentValuePath="date" />
                <chartingToolkit:AreaSeries Title="Logistics Y" ItemsSource="{Binding Series_Y}" DependentValuePath="value" IndependentValuePath="date" />
               Percent}"/>-->
            </chartingToolkit:Chart.Series>

     </chartingToolkit:Chart>

my Series_X and Series_Y is coming from ViewModel. But problem is I also want to bind the number of series as well, so it could generate the required number of series at run time as well !!!

Can I do this ?

Thanks,

Shah