Background:
I have an instance of a LabelService class in my Views that I use to get text from different languages.
This requires that I have code in the background as follows to populate the text in a TextBlock:
XAML:
<TextBlock Name="txtExample" Grid.Row="0" Margin="5,5,5,5"/>
C#:
// 'this' refers to the current class, the namespace of which is used to navigate
// through an XML labels file to find the correct label
string label = _labelService.GetSpecificLabel(this, txtExample.Name).Label
txtExample.Text = label;
Question:
Is it possible for me to have this functionality:
_labelService.GetSpecificLabel(this, txtExample.Name).Label
available in the XAML?
Supplementary Info:
just to explain what I mean by using the namespace to navigate the labels XML:
suppose class is defined as follows, in namespace
namespace My.App.Frontend
{
public class MainWindow
{
string label = _labelService.GetSpecificLabel(this, txtExample.Name).Label
}
}
The corresponding XML would be
<My>
<App>
<Frontend>
<MainWindow>
<txtExample label="I am the example text" />
</MainWindow>
</Frontend>
</App>
</My>
In WPF the the MVVM Pattern is often used to achieve this.
It is even considered bad practise to do such in the code behind,
as it is not testable and not very maintainable.
Leave the codebehind as empty as you can.
That way, you have a ViewModel class which can be connected to your
label service. Your view binds to the ViewModel then.
Here is a very good Video tutorial on how to architect a WPF application:
Jason Dollinger on MVVM
The source code he develops in his tutorial is also available here:
Source code of Jason Dollinger
Here is a very simple ViewModel for you, just to let you have a starting point:
(note that _labelService and txtExample are not set there at the moment)
In XAML, the Binding part is important:
In Codebehind (or better: where you do your scaffolding)