Access variables from XAML and an object from ViewModel using Code Behind

I am new to developing Windows phones. I would like to ask if this scenario can be done. I need to access the variable in XAML using my code behind, then I will add it as an element to my existing list found in my view model. So I need to access both of my View Models to get a list and XAML to get a variable from resources.

Is this doable? If so, how can I access it. This is what I have in my current XAML.

<phone:PhoneApplicationPage.Resources> <system:String x:Key="scanName">SCAN</system:String> </phone:PhoneApplicationPage.Resources> 

Thanks a lot,

+4
source share
2 answers

What you are trying to do is a pretty serious violation of the whole MVVM, but it is possible ...

With the following lines in your view code, you can ...

... access the resource line:

 var scanName = this.Resources["scanName"]; 

... access to ViewModel:

 var vm = DataContext as MyViewModel; if (vm == null) return; vm.ScanHistory.Add(scanName); 

Having said that, you really should not do this. The idea behind MVVM is to completely disable ViewModel and View and allow WPF binding mechanisms to connect them for you. In your case, as far as I can tell, you should save the scan name somewhere else, either as a resource or as a configuration value, get it in your ViewModel and provide a property on the ViewModel to which your view can bind.

+1
source

I do not have a winphone application, so I am doing a simple wpf example (it looks like winphone).

// write the string value from the dynamic resource to textblock

  <TextBlock FontSize="14" Text="{DynamicResource scanName}"/> 

// change the resource in codebehind ( this is a window in my example)

  this.Resources["scanName"] = "new value"; 

You use a script as my mind. Try to read about bindings. Bindings might be more useful in your scenario.

+1
source

All Articles