I'm a newbie in windows phone development. I would like to ask if it is possible to do this scenario. I need to access a variable in XAML using my code behind, then I will add it as an item to my existing list found in my View Model. Therefore, I need to access both of my View Model to get the list and the XAML to get the variable from the resources.
Is this doable? If yes, 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 much,
What you're trying to do is a pretty big violation of everything MVVM is about, but it is possible...
With the following lines in the codebehind of your view, you can...
...access the resource string:
var scanName = this.Resources["scanName"];
...access the ViewModel:
var vm = DataContext as MyViewModel;
if (vm == null) return;
vm.ScanHistory.Add(scanName);
That being said, you really shouldn't do this. The idea of MVVM is to decouple ViewModel and View completely and let the WPF binding mechanisms wire it together for you. In your case, as far as I can tell, you should store the scan name somewhere else, either as a resource or a config value, fetch it in your ViewModel and provide a property on your ViewModel to which your View can bind.
I haven't near winphone app so i make simple example on wpf(it's similiar with winphone).
//write string value from dynamic resource into textblock
<TextBlock FontSize="14" Text="{DynamicResource scanName}"/>
//changing resource in codebehind (this
is Window in my example)
this.Resources["scanName"] = "new value";
As my mind you scenario is veru specific.Try to read about bindings. May be bindings will be more useful in your scenario.