Approach for a multi-lingual WPF application - wpf

it seems there are a number of approaches on how to implement multiple languages in a WPF application. But I would like some more information about what method I should be using with the following requirements:
It's a PRISM application, so a number of independent modules (assemblies) working together. I would like that each assembly has its own translations of UI elements.
I need a simple approach, no tools needed to generate stuff
Should still be able to use blend to design the UI
Optionally be able to switch language without restarting the application (not a dealbreaker)
Can someone advice me on how to achieve this?
Thanks!

A common approach is to bind the text property of your textblocks / labels etc.. to some property on a statically defined localization resource:
<Label Content="{Binding Source={x:Static loc:LanguageContext.Instance},
Path=Dictionary, Mode=OneWay,
Converter={StaticResource languageConverter},
ConverterParameter=TextId}" />
i.e. LanguageContext.Instance exposes a dictionary via a property Dictionary, the Converter uses the given ConverterParameter to look up the text identified via TextId.
This is a cumbersome approach, and will not fulfil all your requirements.
A better method is to defined your own markup extension to perform this sort of logic. There are a couple of solutions I have seen on the web, this high rated codeproject article:
http://www.codeproject.com/KB/WPF/realtime_multilingual.aspx
And a similar solution here that provides Blend, on-the-fly language changes, so is probably a good choice for you:
http://blogs.microsoft.co.il/blogs/tomershamam/archive/2007/10/30/wpf-localization-on-the-fly-language-selection.aspx
With the above example you define an attached property which identifies the key of the translated item, and use the Translate markup extension to identify the properties which are translated.
NOTE: it is not just text which is being translated here, often you have to change colors / graphics etc ...

Meanwhile I found an open source project that works really well: http://wpflocalizeextension.codeplex.com. It's just adding a reference to the dll, adding the resources with translations, and using it in XAML. It worked in 5 minutes. I can add multiple resources to individual modules; and it works fine in visual studio designer and blend. And, locale can be changed on the fly. Meets my requirements :)

Related

Multi-Language resources for wpf user control

I am building a wpf user control to provide navigation facilities for database records.
The control is provided with a set of default images (as illustrated above) which the end user can change is they so wish. In addition the end user can choose to dispense with images altogether. In the event that they select that option (for either one or all of the buttons that comprise the control) I have provided some default fallback text.
This text can also be overwritten by the end user if they so wish, but the default text at least provides them with some basic text that essentially conveys what the button does and saves them having to add text every time they use the control (default tooltip text is also provided).
Now if you happen to speak English, or your intended target audience is English this should work, but it doesn't really cater as is for languages other than English. This I would now like to change.
What reading I've done on the subject of multi-lingual resources and wpf seems to assume that one is talking about the overall application rather than a standalone user control that might be used in different language environments.
I had a talk with a creator of controls who said that making this multilingual would probably involve building several copies of the control for each intended language.
In the light of this I have two questions. Was the gentleman I spoke to correct, should I in fact build multiple copies of this for each language, of is there a way to have multi-language resources within the same copy of the user control?
If the latter is possible what is the correct way to go about achieving this. We will be dealing in total with default texts for eleven buttons (which I will need to be able to refer to in code within the control incidentally) and default texts for thirteen tooltips (which again will need to be able to be referred to within the code of the control).
Take a look on WPF localization extension.
Here's a pretty good documentation for it: link.
You can define your controls' localizable properties, which store their localized values in the satellite resource assemblies.
In your xaml code, define the localized properties with xaml extensions syntax:
<Button Content="{lex:Loc Test}" />
Then, create resource files for each culture your application will support and give them the same name as the main assembly plus the general or specific culture code (e.g. en-US, de, de-AT, ...) before the .resx ending yielding: AssemblyName.CultureCode.resx.
Now, populate the resource files with your localized properties key/value pairs and build the project.
You're done!

MVVM, The best way to structure the View

I have made a root AppView, a root AppViewModel for my application as a container for all the things. Within the application view, I have a TabControl that each tab has its own task to do. One tab for imoprting data, one tab for issuing, one tab for management and etc:
App_View[Model] // root
{
TabTask1_View[Model], TabTask2_View[Model], TabTask3_View[Model] // tab items
}
1) In MVVM, Is it standard that I have grouped my whole views and view-models into the main application-view and application-model-view ?
2) In MVVM, The model should be implemented for every view & vm ? Or is it standard if I implement the whole models into one or two class files and share the model between them? I personally think that model part is not specific to a certain view, like the class 'student' that can be used anywhere in the code and is not restricted to a certain view. Based on this, if the models are general and shared, yet, is it good to follow the naming convention Class + 'Model' for it? like StudentModel? Is it helpful/necessary to add 'Model' after the general or shared class name like the thing I said?
3) In WPF, What is the best way to implement the Views? I want to edit and design very easily and without any restriction, and it should be standard enough to cover future needs. There are 4 things to use: Window, Page, UserControl and DataTemplate. Which one is the best option that you go for? UserControl or Page?
4) In WPF, How can I load the UserControl/Page(View) inside a tabItem dynamically at run-time based on the MVVM approach?
You're cheating. That's 4 questions!
1)
In terms of how you group your Views and Viewmodels I've seen people put views and viewmodels in the same namespace/folder and others separate them out into different folders based on functionality. The best option for you is what suits you/your team. There is no "right" way.
2)
Keep it DRY - so don't repeat yourself. It is perfectly sensible to reuse code. If you have common classes keep them common. As for naming, the name of the class should be helpful in explaining what it does: I'm sure you'd be able to figure out what the classes NavigationService, NavigationMenuItem and NavigationMenuView did and probably could put together a good mental model of how they relate. So - if naming a class BlahViewModel or BlahModel is useful to you, do it.
3) Implementing views:
A Window is always shown independently. Pages are intended for use in Navigation applications (usually with Back and Forward buttons, e.g. Internet Explorer). Pages must be hosted in a NavigationWindow or a Frame. If you're looking at dynamically adding/removing content, adding content to ItemsControls (TabControl, etc) then you'll want to be creating user controls. You can put user controls in Page and Window object, into other controls, etc, and are really the workhorse for WPF developers.
4)
You have a number of options here:
1)The quick and dirty way is to create DataTemplate which, on being given a ViewModel of type X, load up and apply the ViewModel to their data context. This will allow you to inject a ViewModel directly into a control and have the correct View render.
An example:
View.xaml
<ContentControl Content="{Binding Error, Mode=OneWay}" />
ViewModel:
private void ReceiveError(ErrorViewModel errorModel)
{
//if (errorModel.AcceptCommand==null || errorModel.AcceptCommand is NoOpCommand)
errorModel.AcceptCommand = new DelegateCommand(ClearError);
Error = errorModel;
}
public ErrorViewModel Error
{
get { return _error; }
set
{
_error = value;
_propertyChangedHelper.NotifyPropertyChanged(this, () => Error);
}
}
Styles.Xaml (ResourceDictionary)
<DataTemplate DataType="{x:Type vm:ErrorViewModel}">
<DataTemplate.Resources>
<conv:CustomisableBooleanToVisibilityConverter x:Key="VisibilityConverter" TrueValue="Visible" FalseValue="Collapsed" />
</DataTemplate.Resources>
<Popup AllowsTransparency="True" PopupAnimation="Fade" Placement="Center" StaysOpen="True"
PlacementTarget="{Binding Mode=OneWay, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type v:ModuleView}}}"
IsOpen="True" Width="400" SnapsToDevicePixels="True"/>
So you can see I'm injecting my viewmodel directly into the content control and it's using the data template that is bound to the viewmodel's type to find a View for it.
2)
A better bet is to use a DataTemplateSelector. This basically allows you to specify which templates are available for a control and then uses logic you code to determine which datatemplate to use. You can find an example of this here.
3)
Use a framework that abstracts the UI controls away. Microsoft has a framework (free) that does this called Prism. Basically, instead of adding your usercontrols directly to a TabControl,ItemsControl, etc you add your control to a named "Region". This region is mapped to an underlying control and an adaptor is put in place to manage how that UserContorl is added/removed when you ask it to be. You can find an in-depth discussion of this here. Beware, though, Prism is an application framework so implementing this isn't 3 hours work.
Here is not an answer, it's my experience that i'll explain to you and how I handle with MVVM. I started with WPF 3 month ago and I handle with it.
For each new theme/menue/option I create a new project file wich contains the ViewModels and the Views. All Business classes are collected in one Project file because I may have to use it in more than one ViewModel.
Yes, it was helpful for me as beginner to name the the classes ...ViewModel and ..View. It maked it easy for me to separate the diffrences and also it was/is easier to explain other people your classes ( for example if u have a problem with your coding )
I am using UserControls for our different views and I load them into ContentControls and TabControls without any problems.
Have a look at Prism for MVVM-pattern.
Point 1:
It depends. There are two widely used approaches AFAIK. First is as you've said group all VM's that constitute the same Window with direct dependencies to form a class structure that shows your actual program structure. Second is where you use an EventAggregator(Prism) / Messenger(MVVM Light) to loosely link the VM's instead of direct dependency.
Now both approaches have their benefit's
With the first one It's pretty easy to identify your program structure cos your VM dependencies show it clearly, which is not so clearly visible from the second approach.
Second approach helps you a lot when unit testing VM's cos you are not forced to either mock / work-around all the dependent VM's, It also helps code re-factoring a bit when changing project structure(think of "Plug in" classes)
oh and these ^^ are by no means exclusive. You can mix these together well and fine.
Point 2:
Models do not have any recommended 1 <-> 1 relation with a View / VM like what Views have with VM. Models just hold your Business Logic. I've had apps that sometimes do not hold a Model at all. Something there is just 1 Model used by the entire Application(when the back-end is say a c++ library and you just interface with it with a C++/CLI Module). yes maintain the naming convention to append Model class names with "Model"
Point 3
How about all of them? use them where applicable. Do not take a partial preference to any. When a View composes multiple other sections that are by themselves a View with VM I'd have a DataTemplate with the Data a UserControl. Your app almost always uses a Window and Page is useful for navigation based apps I think. Think Page's are what I've used least tbh.
Point 4
This is a question of tutorial's. Take a bunch of examples, see how it's implemented, reason it and pick your approach. If your using VS2010 get MVVM In the box (It's great. no 2 ways about that. Really hope this could get to be updated for VS2012 if it's not already). For VS2012 check out Two Views MVVM CodeProject which shows the concept, you can then apply it to any ItemsControl of your choosing.
Finally atleast when you're starting up, PLEASE start off with using a MVVM helper library. I prefer MVVM Light <- that link has a couple videos by the author of the library showing some usages and you can find extensive help here on SO about it. If you want to do things yourself, learn the basics from it and then implement it yourself. if you take the high road from day-one it's just a much longer learning curve(Just my opinion)

how to use xaml magic

I have problems figuring out where to use what xaml keywords because its hard to figure out what hierarchy it wants. It seems there is some grand design on how and where to use attributes, properties or child nodes.
<Node Attribute="True">
<Node.Property />
</Node>
I found this beautiful page explaining all the ribbon menu properties, but have no idea how to use them in xaml. After half an hour of searching and trying everything I managed to get an Icon to show in the ribbon menu button.
What is the logic behind this all and how to figure out what to use where?
How to merge the ribbon menu with the application bar (the top bar on most windows applications)? So I get a nice Ribbon Application Menu, like in the example.
Is there a way to turn off xaml background compliation? I'd sacrifice Intellisense for this.
Because the xaml editor performance is abysmal, the are many suggestions for this, but none working so far.
Edit:
I know the xaml syntax, but there's no hint on what hierarchy to use. So if I find the object I want to use (because they are all available) it will only say I'm using the wrong object, it should ask for the kind of object it wants to be in.
Also in normal programming when you use a reference you can always use all classes in it. With xaml we must suddenly know what reference our class came from, also it won't find the reference for you, you either have to try all references to see if they have a certain class or find a code example.
Good questions. Its a little hard to get a feel for exactly what you're asking for in your #1 question, but I'll take a brief stab at that one. I do have an answer for your #2 question. I do not have an answer for your #3.
"1. What is the logic behind this all and how to figure out what to use where?"
Like Clemens mentioned, the XAML Overview does a pretty good job at explaining things.
I'm guessing that one of the main things that you're asking about is basically "when do you use attribute syntax vs property element syntax". From that doc:
For some properties of an object element, attribute syntax is not possible, because the object or information necessary to provide the property value cannot be adequately expressed within the quotation mark and string restrictions of attribute syntax. For these cases, a different syntax known as property element syntax can be used....
Now about this part of your question...
"Also in normal programming when you use a reference you can always use all classes in it. With xaml we must suddenly know what reference our class came from, also it won't find the reference for you, you either have to try all references to see if they have a certain class or find a code example."
If part of your question is more about how can you more-easily handle your XAML (or more appropriately xmlns) namespaces so that it is easier to get references ironed out in your XAML, there is a technique that you may find useful. It lets you consolidate namespaces so that you can use fewer XAML namespace prefixes (or even no namespace prefixes if you take this technique to its extreme).
"2. How to merge the ribbon menu with the application bar (the top bar on most windows applications)? So I get a nice Ribbon Application Menu, like in the example."
Essentially it seems that you're asking how to: (a) extend the window chrome area (the Aero glass area) down into the client part of the window (the part that your application normally gets to put things) and (b) extend the client part of the window up into the window chrome area. If you can do both of these things, then you can end up with something that looks like Microsoft office products or modern web browsers. Fortunately there is the WPF Shell Integration Library which helps you do both of these things. I found this blog and this blog (and the source code they offer) good guides for getting started with using the WPF Shell Integration Library.
Using this library, I was able to make this window (all but the Aero color changing abilities which is a whole other topic). Notice that both of qualities I mentioned are working here (the TabControl is being display up in the normal window chrome top bar area and the window chrome Aero glass is being displayed down in the normal client area):
Here's my take
1) What is the logic behind this all and how to figure out what to use
where?
Whatever you can fit between "" can go inline like:
<TextBlock Text="{Binding Name}" />
Whatever can't, go the element way:
<TextBlock>
<TextBlock.Text>
<MultiBinding StringFormat="{}{0} ({1})">
<Binding Path="Name" />
<Binding Path="Gender" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
2) How to merge the ribbon menu with the application bar (the top bar on
most windows applications)? So I get a nice Ribbon Application Menu,
like in the example.
You'll find more or less complicated mumbo jumbo around google, this is the essence of it:
<Window ...
WindowStyle="None" AllowsTransparency="True" Background="Transparent"
...>
<!-- Fill it up with a PNG image if you want to play with transparency -->
</Window>
Then make the ribbon the top element, and re-create Close/Maximize buttons
3) Is there a way to turn off xaml background compliation? I'd sacrifice
Intellisense for this.
Yep, it's called Notepad++

What are the real-world benefits of declarative-UI languages such as XAML and QML?

I'm currently evaluating QtQuick (Qt User Interface Creation Kit) which will be released as part of Qt 4.7. QML is the JavaScript-based declarative language behind QtQuick.
It seems to be a very powerful concept, but I'm wondering if anybody that's made extensive use of other, more mature declarative-UI languages like XAML in WPF or Silverlight can give any insight into the real-world benefits that can be gained from this style of programming. Various advantages are often cited:
Speed of development
Forces separation between presentation and logic
Better integration between coders and designers
UI changes don't require re-compilation
Also, are there any downsides? A few potential areas of concern spring to mind:
Execution speed
Memory usage
Added complexity
Are there any other considerations that should be taken into account?
(Updated)
The misconception with XAML is that it's not compiled. It is indeed compiled down to BAML a binary pre-tokenized XAML. Apparently there was a IL compiled version of XAML too called CAML. The OP pointed me to this good article explaining what XAML/BAML and CAML are.
Anyway, to the question why to use it:
XAML is simply a Serialization Format for C# objects that it is particularly well suited to describe hierarchical object structures, like found in WPF GUIs.
What WPF helps you do is write less boring C# code like this:
var grid = new Grid();
grid.Content.add(new TextBlock() {Text = "Hello"});
grid.Content.add(new TextBlock() {Text = "World"});
and just express it in a more readable way like this:
<Grid>
<TextBlock Text="Hello">
<TextBlock Text="World">
</Grid>
Since WPF object nesting (putting stuff inside other objects) can get very deep, WPF makes it much easier to read than the resulting C# code.
As for separation of concerns: XAML helps here too since it does only allow you to express objects and their relationships/properties, rather than logic. That forces you to separate logic from UI layout. The MVVM Pattern is very well suited for this task and allows for eay testability and interchangeable Views.
Added complexity in XAML can be also easily dismissed because the same code in C# gets easily more complex than the XAML markup.
I can't give you any insight into QTQuick though. Sorry
QtQuick is extensible via C++ plugins, actually what the Qt guys recomment is that you do the UI, Animations, Transitions etc in QtQuick/QML while all of your business logic is in C++/Qt. So this way you get the best of both worlds, you can debug your C++ code like you usually do, while at the same time making UIs becomes effortless and extremely easy.
Also another important think about QtQuick/XAML is that they are hardware accelerated, so for example you can get pretty good fps without any effort. So they are not slow at all for what they set out to accomplish.
It saves time, soo much time. I did a UI with code in 3 days, did the same in QML in 2 hours.
The point of declarative coding, i.e. WPF or QTQuick is to provide a separation between the developer and presumably the artist that is implementing the visual aspects of your application. With regards to WPF, I find that debugging gets to be a bit harder. As we speak, I am compiling the latest QT to look at QTQuick. (It takes a long time and I have time to look at stackoverflow :-) ) So, I don't have an opinion on that yet.
QML/XAML are:
Great for MVVM pattern
Hardware accelerated (QML with using OpenGL for Windows, MAC, Linux and Phone OSes... XAML with using DirectX for Windows and its phone version)
Closer to artists
You can create a GREAT and NICE UI using XAML/QML
Easier UI implementation
Nice animation is possible
In XAML, usually you can create a Silverlight version of your application just with a little changes
In XAML there is some great features such as Template, Trigger (DataTrigger, Trigger, EventTrigger), Binding (in any side and also both side together), Resource, Commands, DependencyProperty and Notifiable Properties.
But please note in XAML: (I am a XAML programmer, therefore i have not points for QML)
XAML debugging is not possible
For any change in XAML, all program must be recompile
Be more careful for performance. For example if you use much many RoutedCommands in XAML, your application will be unusable!
In XAML, some feature not works as expected. There is unfortunately some tricks. (It should be clear... should works as expected... isn't it? )
Be careful for some similar namespaces like BitmapEffect and Effect. There is different features and costs. (e.g. BitmapEffect has some effects with software render and Effect has some effect with hardware render)
In real world, artists could not use WPF as Flash (at least with good performance).
Some features works on special places. For example DataTrigger works just in Style tag not in Resource section.
There is some weaknesses in XAML. Some examples: there is not any sequential animation... you cannot do any calculation in XAML (you must write a converter in C# even for a liiiittle work! JavaSript is a great replacement in QML)... some attributes are duplicate. e.g. x:Name and Name... Controlling View from ViewModel is not clear. e.g. closing View from ViewModel (you need some CodeBehind)
Tooooooo much run-time errors. If you use some tags in bad place it will notice you for syntax error, but many of errors occurs just in the run-time. e.g. if i target Background property (instead of Background.Color) for ColorAnimation, it will compile successfully, but in running animation... BUMP... runtime error!!! in such case on Expression Blend, application will crash!!!

How unique is XAML?

Was talking to a colleague about XAML and how it is both a presentation and object description language and therefore quite unique and novel among IT technology.
Is this true that XAML is unique and novel?
Does XAML have any counterparts or predecessors in the Java world or elsewhere? I believe someone told me that Java Server Faces was similar to WPF, so what is the equivalent of XAML there?
I know MXML in Flex is similar but as far as I can remember there are some major structural differences, from what I remember MXML doesn't really describe objects but is more of a pure presentation XML.
This is a case of a general technology having such an overwhelming common specific usage that becomes synonmous with the specific usage. For example, discussions of Javascript often assume the browser context and the manipulation of a HTML DOM without anyone having to expressly say so.
Strictly speaking XAML is not like XUL or SVG apart from being XML. XUL, SVG have a defined syntax for declaring User interface or graphical elements, raw XAML does not.
XAML can, for example, also be used to describe Workflows in Workflow foundation.
XAML is actually an approach to reading XML in order to describe types and properties of those types. For example, a property of a type may be described either using an attribute or an Element as long as its name can be interpreted correctly. XAML also includes an extension to the basic XML syntax where { } in an attribute can act as a short hand for a complex element.
I've not come across this sort of thing before. All other XML based technologies come with a specific purpose, XAML is the first usage of XML I've seen that is deviod of any specific nomenclature but just a means of mapping XML to types.
****XAML, XUL, and XHTML Overlap****
The greatest overlap between XAML and other standards lies in its support for concepts drawn from HTML/XHTML. The similarities between XAML and HTML are numerous. Overlap with HTML is not limited to XAML, of course. The other well-known XML GUI dialect—Mozilla's XUL—also overlaps with XHTML. Finally, both XAML and XUL overlap in places that XHTML doesn't even include. XHTML and XUL can be combined in one document (at least in Mozilla browsers). Such a combination is a rough analog for non-Web uses of XAML. In fact, Mozilla's XUL alone is a rough analog for some uses of XAML.
but taken together, they really constitute nothing more than support for most of the basic HTML content and form widgets that are already routine in ordinary Web applications. XUL overlaps XHTML less that XAML does because XUL attempts to separate itself from XHTML. It's not trying to be a drop-in replacement, as XAML is.
One thing I do like about XAML compared with HTML is the increased freedom from the publishing-derived features of HTML. XAML frees you from h1 tags, code tags and a host of other miscellaneous niche tags used infrequently in HTML. For practical purposes, these tags act as little more than style information in modern HTML documents.
HTML is also a poor GUI for applications, despite the popularity of the Web. Both XAML and XUL go a long way towards rectifying that problem. You could re-write your Web applications in XAML and they'd look better than the HTML originals, if only XAML had better CSS support.
Read the comparisons to other presentation technologies with a grain of salt - Xaml is a method of constructing and composing .NET objects. That's in stark contrast to other systems that were designed as a way to build user interfaces. The nice thing about Xaml is that it's independent of the technology stack that its used for - it's a purpose-agnostic declaritive language more like C# than XHTML. In that way, it's unique.
Cocoa from Apple, or event earlier NeXtStep had something similar long before XAML.
The GUI is created with an interface builder, which makes so called nib (Nextstep Interface Builder) files, which contains the layout, bindings, actions, outlets and serialized object instances. In the former time these nib files were stored in a binary file format, but nowadays it is also xml (xib).
So XAML is not the first not unique at all.
Besides XAML, you have XUL which is used by Mozilla. SVG on the other hand, is one recommended by W3C.
Mozilla created their UI description language XUL originally to be able to easily customize the UI of all of their products.
Nowadays it's a package which can be included in other applications and also has an extended functionality.
Although XUL mainly focuses on UI representation it also contains other structures as Events and Scripts and Data sources. Nevertheless as far as I know XAML integrates these concepts much tightlier into their .NET (and attached) frameworks. But I'm not sure if this is enough to call it unique and novel.
XAML is an object graph construction language in the dialect of XML (not the greatest choice). Every XAML element is an object instantiation and the corresponding attributes are property assignments on said instance. Since XML is a string based language, property values need to be converted from their string type into whatever type the property expects. This is done using descendants of TypeConverter that the XAML processor locates and utilizes automatically. XAML and WPF come with a default set of TypeConverters corresponding to their provided types and you can provide your own.
A rough overview of the definition process is as follows:
<classG-in-namespace-A
xmlns="namespace-A"
xmlns:alias-B="namespace-B"
xmlns:alias-C="clr-namespace:namespace-C;assembly=assembly-of-namespace-C"
propertyG1="simple text value stipulation"
propertyG2="{alias-C:classH-in-namespace-C propertyC1=valueC1,..}"
>
<classG-in-namespace-A.propertyG2>
<alias-B:class-I-in-namespace-B propertyB1=valueB1,...>
class-I-in-namespace-B's content property value assignment
</alias-B:class-I-in-namespace-B>
</classG-in-namespace-A.propertyG2>
classG-in-namespace-A's content property value assignment
</classG-in-namespace-A>
There are utility types provided by XAML and WPF beyond TypeConverters that facilitate property assignments. In particular, there are the following:
ResourceDictionary,
ObjectDataProvider,
RelativeSource,
StaticResource,
DynamicResource,
...and more as shown in Microsoft Docs
Well, XAML is basically advanced markup for .NET, therefore I think you can draw a lot of parallels from XAML to XHTML - Both being presentation techniques.
There's a lot of differences as well ofc (XHTML being interpreted by a browser to produce graphics, while XAML is being compiled into MSIL and relying on the CLR to do the graphics :) )

Resources