XMLDataprovider label binding codebehind WPF c# - c#

I am working on a WPF application. I set up a multilanguage with xml files and I use static resource binding in front code to set the corrisponding text. The issue I have is with doing the same thing in the codebehind.
Here you can see how I use it in front code:
<XmlDataProvider x:Key="Lang" Source="/lng/english.xml" XPath="WpfApplication"/>
<Label HorizontalAlignment="Center" Margin="0,10,0,5" Foreground="White" FontWeight="Bold" Content="{Binding Source={StaticResource Lang}, XPath=MenuTextClimate/#Header}"></Label>
I am trying to do the same in codebehind like this:
String selLangFullPath = WpfLibrary.LanguageOptions.getSelLangFullPath();
XmlDataProvider xmlData = (XmlDataProvider)(this.FindResource("Lang"));
xmlData.Source = new Uri(selLangFullPath, UriKind.Relative);
xmlData.XPath = "MenuTextClimate/#Header";
Binding NewBinding = new Binding();
NewBinding.Source = xmlData;
NewBinding.Mode = BindingMode.OneWay;
NewBinding.XPath = "MenuTextClimate";
lblTitle.SetBinding(Label.ContentProperty, NewBinding);
but for some reason it doesent seem to work. Can any one tell me where I went wrong?

The codebehind you've shown doesn't actually do the same thing. It's different in three ways:
You're changing the Source property of the XmlDataProvider
You're providing a different XPath to the XmlDataProvider (MenuTextClimate/#Header instead of WpfApplication).
You're also providing a different XPath in the binding expression.
The problem could simply be that any or all of those things is wrong. (The XPath ones look particularly suspicious, because they look like they presume a completely different XML document structure. Although since you're also providing a different XML document, maybe that's fine. It's impossible to tell from the information provided so far.) So the first thing I'd do is try making your C# do exactly the same as your Xaml - same URI and same XPaths. If that works, it should be easier to see which of the three things that's different is causing the problem.
Alternatively, enable WPF debug output. If you're on .NET 3.5 sp1 or earlier, this is usually on by default for Error level logging of data binding messages. (Data binding errors appear in the Output window.) As of .NET 4.0, Microsoft turned it down so you won't see it unless you ask for it. You turn it on with the 'options' dialog in Visual Studio - it's under Debugging -> Output Window. Ensure that Data Binding is set to show errors. Or for more detail, crank it all the way up and then enable full logging by adding this:
PresentationTraceSources.SetTraceLevel(NewBinding, PresentationTraceLevel.High);
That should show you full gory details of what data binding is attempting to do with your binding, and that's often a pretty good way to find out why things aren't working.

Related

Efficiently creating UI elements from XML file (OpenGL / C# NET 6.0)

I'm currently working on a small game framework, build on top of OpenTK. In this project there should also be a way to easily create UI elements by defining their layout in an XML file, like WPF and XAML but way less complex (no bindings planned etc).
Now I'm kind of stuck when it comes to efficiently creating these ui elements from the XML file. The concept is that there are few core elements like image, label and panes for layouting and the structure of all more complex elements are defined in XML and represented by a seperated class (that inherits from UIElement, the base class for all UIElements).
For example, this is how it could look like for a button:
Button.xml
<Button Layout="AlignLayout Stretch Stretch">
<Image Name="image"></Image>
<Image Name="hoverImage"></Image>
<Image Name="pressedImage"></Image>
<AlignPane HorizontalLayout="Center" VerticalLayout="Center">
<Label Name="label"
IgnoreInputEvents="true">
</Label>
</AlignPane>
</Button>
Button.cs
public class Button : UIElement
{
protected Image image;
protected Image hoverImage;
protected Image pressedImage;
protected Label label;
public Button(UIElement? parent, Texture2D backgroundTexture,
Texture2D hoverTexture, Texture2D pressedTexture,
string text) : base(parent)
{
// Receive XML layout here probably? (from cache, not parsed)
image.Texture = backgroundTexture;
hoverImage.Texture = hoverTexture;
pressedImage.Texture = pressedTexture;
label.Text = text;
// ...
}
}
and the usage in code would simply be:
Button startButton = new Button(OverlayUICanvas, bgTex, hovTex, prsTex, "Start");
or use the element in some other XML file.
The element attributes in xml set properties in the corresponding class (except "Name", which is expected to set the fields/properties in the root element to the instance of the created class)
Basically i got something like this working already except that it is super inefficient (probably because all the reflection going on including parametered constructor calls). While testing it took over 100ms to load something simple with just 8 total elements.
It wouldn't be too bad if i could somehow cache the loaded layout somehow and then just create a new instance, without all the reflection going on again (layout would be loaded at game start or something) but i really have no clue how i could archive this.
Creating new instance of these elements is pretty important: imagine the game needs to creates some elements at runtime from a list or something like that.
I didn't really found any good information on how to do this, not even sure if it is possible like that. If I undestood correctly, WPF solves this by generating some source code on compilation but it stated this only works for netstandard2.0 and I'm having a hard time wrapping my head around if this would even help me solve this problem.
If you want to take a look at the current source yourself for some reason:
https://github.com/BlakkM9/VengineX/tree/master/VengineX/UI
but please keep in mind - this project is WIP, in a very very early state and nothing professional, really.
I'm graceful for any tips and hints that might lead me in the right direction!

Resources for working on an app in Xamarin using C# for UI rather than xml?

I am writing an app in xamarin.forms using C# for my UI. However, I am having trouble finding any resources to help me with certain things (like databinding for instance) that are strictly using c# as opposed to both c# and xml. If anyone can point me in the direction of where i could find those resources (if they exist) that would be awesome. (P.S. yes I have googled every single way I can possibly think of but all the keywords you'd use such as xamarin + c# + UI etc always just keep returning more results using xml)
the Xamarin binding docs have samples in C# and XAML
// set the binding context for the page
this.BindingContext = new MyViewModel();
// create a label
Label myLabel = new Label();
// set the binding to a property on the VM
myLabel.SetBinding(Label.TextProperty, "Description");

Windows 10 UAP - Compiled Data Bindings

According to the Windows 10 SDK kick start videos (http://www.microsoftvirtualacademy.com/training-courses/a-developers-guide-to-windows-10-preview?prid=ch9courselink) there is a new type of bindings for the Windows 10 universal app platform called "compiled data bindings".
Instead of
"{Binding Path=..."
the new style is
"{x:Bind Path=..."
However this only throws in a compiler error that whatever is behind the = is placed does not exist in the context.
Setting
"{x:Bind Path=DataContext...."
does not work either.
Has anybody managed to get the new bindings to work? Is there ANY documentation on the topic because I don't seem to be able to find anything (not even a sample that you could "reverse engeneer"...
Update:
Thanks to Nick's response I can add the following:
Since I usually insert view models after the Page / UserControl is initialized, the Page / UserControl does not seem to notice the updated ViewModel property (even when the Page / UserControl implements and "fires" INotifyPropertyChanged).
Apparently there is a new field in Pages / UserControls called Bindings which can enforce a reset of all compiled data bindings.
So once you change your ViewModel (or another property referenced by x:Bind) you can simply call:
Binding.UpdateAll()
This way the Page / UserControl reevaluates all compiled data bindings and accepts a "data context switch".
Hope this helps - http://nicksnettravels.builttoroam.com/post/2015/04/26/Compiled-DataBinding-in-Windows-Universal-Applications-(UAP).aspx
This explains what the context is and how some of the compiled bindings are generated
I'll just add these two links to official documentation since it is available now and the content seems relevant to the subject.
1) {x:Bind} markup extension
2) {x:Bind} and {Binding} feature comparison

Bind Strings from an .resw file with ReswFileCodeGenerator in XAML

I tried to localize my Windows Universal App with the Multilingual app toolkit.
Because you can't bind strings directly from a .resw file in XAML, I used the ReswFileCodeGenerator tool. It works great in code behind, but in XAML I can't get this right.
In Windows Phone 8.0 I could use:
Text="{Binding Path=LocalizedResources.StringName, Source={StaticResource Strings}}"
Is there a similar way in Windows (Phone) 8.1 with the ReswFileGenerator tool?
I would still suggest you do it as Depechie already suggested: use x:Uid attribute.
If you need to get the localized string from code, just replace . in resource name with /. So, in XAML you'll write:
<TextBlock x:Uid="appString" />
In code you'll use:
var resourceLoader = new ResourceLoader();
var localizedText = resourceLoader.GetString("appString/Text");
When doing resource translations in wp8.1 with .resw files, you need to use the x:Uid attribute on your xaml control!
Like <TextBlock x:Uid="FieldKey" />
Details are mentioned here...
I've coded something to help me with this. It may not be perfect, but works great for me. Here's a link to the helper. You build it and put the .exe file in some easy-to-reach folder.
In the project with the resources, you set the pre-build action to something like this (you only need to change the "path\to\ResourcesHelper.exe" part):
call "path\to\ResourcesHelper.exe" "$(TargetName)" "$(ProjectDir)\" "$(RootNameSpace)" "universal"
Also, the main resources must be in Resources/en-US folder of your project (you can change it in the code, though).
This way, when you build the project, it will generate a file called LocalizedStrings.cs which is something like the file generated for .resx files. It contains some additional properties called LC (for lower case), UC (for upper case) and UCF (for upper case first) which return the strings in that casing. I hope you'll find it useful. :)
Note: The tool wasn't meant for other people, so I really just coded what I needed, so it may not work flawlessly.

WPF Formatting string as currency using the € symbol

I've got an application where I need to show a price, for that, I have the following code:
<Label Content="{Binding Prijs}" ContentStringFormat="C"></Label>
However, that gives a stringformat like: $10.00, but i want to show the euro-sign (€) instead of the dollar-sign ($). How do I do that?
You need to make sure that the Language of the control is set correctly.
Tim Heuer has a blog post entitled "StringFormat and CurrentCulture in Silverlight" about this for Silverlight so I expect the same problem occurs in WPF.
The solution for Silverlight is to add the following line to the view constructor:
this.Language = XmlLanguage.GetLanguage(Thread.CurrentThread.CurrentCulture.Name);
Now for WPF you might just need to make sure that the CurrentThread.CurrentCulture is set correctly, if not try adding this line too.

Categories

Resources