Windows store app ResourceLoader at design time - c#

I've started creating a Windows Store App for Windows 8.1 and now I encountered a problem concerning localization.
I would like to display a string resource from a .resw file at design time, but every attempt to do so has failed, even though it works at runtime.
When using the x:Uid attribute, I still have to supply the Text property (i.e. for a TextBlock) and I don't like to write the text twice.
I also tried creating a property for the string on the viewmodel:
public string Title
{
get { return ResourceLoader.GetForCurrentView("Strings").GetString("MainView_Title"); }
}
This is working at runtime, but at design time it is blank.
So the question is, is there a way to display resources from a .resw file in the XAML-designer?
More specifically, does the ResourceManager class allow .resw files to be read at design time?
Thanks for your help,
Lucas

Old Method
So, there are a couple of things you can do.
The first (and simplest, given that you're using x:Uid already) is to just supply the text into the Text field. The x:Uid-related value will overwrite whatever is in there.
<TextBlock Text="MyText" x:Uid="MainView_Title"/>
The second method is to use the property like you already have, and then check to see if the app is in Design Time (through a couple of different methods), then return a constant value if it is and the Resource if it is not.
public string Title
{
if(ViewModelBase.IsInDesignTimeStatic) //Mvvm Light's easy accessor
return "My Text";
return ResourceLoader.GetForCurrentView("Strings").GetString("MainView_Title");
}
Hope this helps and happy coding!
Edit: There appears to be a new way to do this, at least as of Windows 8.1.
New Method
Create a class which references a ResourceLoader (similar to the property described above).
Create an indexed property accessor which accepts a string key and return the value from the ResourceLoader.
public class LocalizedStrings
{
public string this[string key]
{
get
{
return App.ResourceLoader.GetForViewIndependentUse().GetString(key);
}
}
}
In your App.xaml, define a StaticResource of this type.
<Application.Resources>
<ResourceDictionary>
<common:LocalizedStrings x:Key="Localized"/>
</ResourceDictionary>
</Application.Resources>
Now, when you want to access your property with entry key MainView_Title, use this. It's more verbose, but it should translate both in the designer and in the app itself.
<TextBlock Text="{Binding Source={StaticResource Localized}, Path=[MainView_Title]}" />
You can shuffle it around to be a bit more readable if you'd like, such as:
<TextBlock Text="{Binding [MainView_Title], Source={StaticResource Localized}}" />

This is an old thread, but since Nate provided such an elegant solution to the problem for Win8.1 I figured I'd ask here...
After much investigation and experimentation, Nate's solution does not appear to work for UWP apps for Win10 under VS2017 Community. The LocalizedString approach works just fine at runtime, but it appears
App.ResourceLoader.GetForViewIndependentUse().GetString(key);
refuses to return anything except String.Empty during design time. I've done a lot of experimenting and things like
ResourceContext.GetForViewIndependentUse().QualifierValues
Seem to be identical between runtime (working) and design time (not working).
I was wondering if anyone has encountered this and solved it. Nate? :)

Related

wpf element name as an argument for IValueConverter

I am trying to get multilingual translation("label or caption") string value for the given elementname in wpf.
For example; for elementname "txtDescription" ; my IValueConverter implementation will return with "Description" ; for another language will return different translation string(i.e. descripciĆ³n for Spanish) and the translation string will be Text=... of the same element.
I am new to wpf; I cant make it work. Is there any elegant way to do that with similiar manner as below.
<TextBlock Name="txtDescription" Text="{Binding Converter={StaticResource MultiLingualConverter} }"</TextBlock>
If this is not simple or requires more code then as an alternative sending "txtDescription" as an argument to MultiLingualConverter is acceptable but I dont now how to do that neither.
Definitely, you should build good localization support in your system, better then using converter for every string.
Until today, the best solution i have found and i almost always use it is this:
http://blogs.microsoft.co.il/tomershamam/2007/10/30/wpf-localization-on-the-fly-language-selection/
give it a try. good luck
You can pass the element name via the ConverterParameter property, this is an example of how it is used to pass a string to the converter.
However, WPF localization is more than returning different strings for different languages. You can read this article for more information and there is a Run Dialog Box example in the page to get you started.
Due to cyclical dependency restrictions you cannot reference a control inside itself or its descendants in the tree.
I would recommend you not to use converter for multilingual support. it is not a best way to do this.
got here for best way to do.
https://msdn.microsoft.com/en-us/library/ms745650(v=vs.110).aspx

Databinding - Lozalized FallbackValue/TargetNullValue etc

In my Windows Phone 8 C#/XAML .NET 4.5 App I'm using databinding from ViewModel, which is working fine.
What I'd like is for a lozalized string from LocalizedResources to be displayed as a content of a button in the following cases:
The value returned by Binding is null
The binding could not be resolved
How could this be achieved?
What I've tried to do is:
(omitted TargetNullValue, since the way to do it is probably going to be the same)
(for presentation purposes, i set the resource to be Applicationtitle)
<Button ... Content="{Binding Something, FallbackValue={Binding Path=LocalizedResources.ApplicationTitle, Source={StaticResource LocalizedStrings}}}" ... />
But what I get is text like System.Windows.Text.Data.Binding...(can't read more since it's out of screen).
Did some googling/"stackoverflowing" and found something with valueconverters for WP7, that got me a bit puzzled.
(And added C# tag because I've got a feeling this is not going to be solved just by adding the right "property" to a tag/value to a "property", although I'd appreciate it to be)
I'm pretty sure you cannot apply binding to the FallbackValue. A very simple workaround is to check for null within your 'Something' property.
private string _something;
public string Something
{
get { return _something ?? AppResources.ApplicationTitle; }
set
{
_something = value;
OnPropertyChanged("Something");
}
}

WP7 - Data bound value in custom control, how to set default string so it's visible in designer

I'm fairly new to WP7 and totally new to Expression Blend.
I have a ListBox bound to a List of custom objects,
List<Person>
Each item in the list contains a custom control, MyControl which is bound to Person.
MyControl contains a TextBox which is bound to the Username property of Person.
All of this works fine. My question is: how do I set a default value for the TextBlock so that it becomes visible in the Designer or ExpressionBlend? With it being data bound, it has no text till it runs ... so I can't actually do any fancy styling using these wonderful tools unless I repeatedly delete the binding code to replace it with a string, make the changes, replace the binding code, repeat. Seems long winded!
Thanks,
Steven
What you want is "Design time data".
There are a number of ways of doing this. Fortunately there are also lots of resources online which explain it.
#Steven Have you looked at creating sample data in Blend to do what you require and then some binding to actually attached the data to the control bound to your list? You might like to check out Blend Sample Data as it guides you through a simple example of doing just that. You might then be able to adapt to to your own ends.
It depends if you are using any MVVM model or not.
My suggestion, if you are not using a MVVM, is to use Blend Sample data, is fast and quick.
If you are MVVM Light I've found very usefull to create two files:
DataService.cs - contains the real connection and data
DesignDataService.cs - contains the sample data
The two libraries are identical, from an call perspective so that in the ViewModelLocator you can swap them:
if (ViewModelBase.IsInDesignModeStatic)
{
SimpleIoc.Default.Register<IDataService, Design.DesignDataService>();
}
else
{
//SimpleIoc.Default.Register<IDataService, Design.DesignDataService>();
SimpleIoc.Default.Register<IDataService, DataService>();
}
In the Design class I've decided to create an XML file for each Model so that it's easy to change the sample data and test all possible scenarios.
I then use the Deserialize function to read it:
csNodeList _Copyrights = new csNodeList();
resource = System.Windows.Application.GetResourceStream(new Uri(#"Design/sampledata.xml", UriKind.Relative));
streamReader = new StreamReader(resource.Stream);
serializer = new XmlSerializer(typeof(csNodeList));
_Copyrights = (csNodeList)serializer.Deserialize(streamReader);
Please note that the file sampledata.xml has to be stored in folder Design and must be defined as Content not as Resource.
It is suggested to improve performance and load time.
M

Setting char properties in Xaml

Perhaps it is something trivial but I am out of ideas...
Originally I wanted to add some features to PasswordBox. Because it is a sealed class, original properties have to be replicated, among them PasswordChar. Looks trivial, but when I started to set PasswordChar in Xaml, I could not get rid of parser exception.
At the end I simply defined a new property
public char MyProperty {get; set; }
and tried to set it in Xaml as follows:
<MyPasswordBox MaxLength="3" Password="xxx" MyProperty="c" />
I am getting an exception with the call stack looking like
at MS.Internal.XcpImports.CheckHResult()
at MS.Internal.XcpImports.ConvertStringToTypedCValue()
at MS.Internal.SilverlightTypeConverter.ConvertFrom()
at MS.Internal.FrameworkCallbacks.ConvertValueToPropertyType()
....
at MS.Internal.FrameworkCallbacks.SetValueToProperty()
at MS.Internal.FrameworkCallbacks.SetPropertyAttribute()
....
at System.Windows.Application.LoadComponent()
....
As far I can read it, the type conversion string -> char fails.
Note that whenever I'll change the type of MyProperty to string (for example), everything works.
Does anybody know how to implement char properties so that they can be set from Xaml?
Working on Windows Phone 7, perhaps that's the problem. (Limited SVL 3)
I can't verify this will work, but you can give it a go. The long form xaml syntax should work ok.
Add the following to your namespace imports
xmlns:sys="clr-namespace:System;assembly=mscorlib"
Then the following should work
<MyPasswordBox MaxLength="3" Password="xxx">
<MyPasswordBox.MyProperty>
<sys:Char>c</sys:Char>
</MyPasswordBox.MyProperty>
</MyPasswordBox>
The other solution is to look into type converters to apply to your property so that it'll convert the string for you. Type Convereters and XAML.

User Control Property Designer Properties

For a C# UserControl on Windows Mobile (though please answer if you know it for full Windows...it might work) how do you change what shows up in the Designer Properties window for one of the Control's public Properties. For example:
private Color blah = Color.Black;
public Color Blah
{
get { return this.blah; }
set { this.blah = value; }
}
This shows up for the control, but it's in the "Misc" category and has no description or default value. I've tried using the settings in System.ComponentModel like "DesignerCategory", such as:
[DesignerCategory("Custom")]
But says this is only valid for class declarations... could've sworn it was the System.ComponentModel items I used before...
Update:
#John said:
DesignerCatogy is used to say if the
class is a form, component etc.
Try this:
[Category("Custom")]
Is there a particular namespace I need to use in order to get those?
I've tried those exactly and the compiler doesn't recognize them.
In .NETCF all I seem to have available from System.ComponentModel is:
DataObject,
DataObjectMethod,
DefaultValue,
DesignerCategory,
DesignTimeVisible,
EditorBrowsable
The only one it doesn't scream at is EditorBrowsable
DesignerCategory is used to say if the class is a form, component etc.
For full windows the attribute you want is:
[System.ComponentModel.Category("Custom")]
and for the description you can use [System.ComponentModel.Description("This is the description")]
To use both together:
[System.ComponentModel.Category("Custom"),System.ComponentModel.Description("This is the description")]
However this is part of system.dll which may be different for windows mobile.
Is this of use to you? I am not into CF development, but it looks like you need to add some XML metadata to enable it:
http://blogs.msdn.com/bluecollar/archive/2007/02/08/adding-compact-framework-design-time-attributes-or-more-fun-with-textboxes.aspx
Interesting read.. Looks like a lot of design time support was stripped out of CF because you dont design them on the devices.. Which seems kinda weird to me.. Cant imagine using a handheld as a development rig!
Scroll down about half way for the good stuff ;)
The article does not suggest that anyone is designing ON the device. However, when you create a Compact Framework project, the compact framework (for your desktop PC) is used to handle design time rendering. If you think about it that is what you expect. The same framework (or nearly so) is used to do the rendering both on your PC at design time and later on the device at runtime. The issue is that the design time attributes were not added to the compact framework (I assume to reduce the size).

Categories

Resources