Can I apply "StaticResource" to element in run-time? - xaml

Can I apply "StaticResource" to element in run-time?
I know I can use "StaticResource" to element in xaml files. But, I want to know how to use it from C# (code-behind).

A StaticResource is a static defined resource, usually defined in the <X.Resources> element, for any element or page.
In C# you simply access it with X.Resources["MyResource"] like you should do {StaticResource MyResource}.

Not really with the same meaning. StaticResources are "static" in the sense that their value is resolved during Xaml parsing. The XamlParser will resolve the resource by examining the resource dictionary the ancestor FrameworkElement Resource properties that are also in the same xaml and then the Application.Resources if necessary.
If you happen to know where to find the resource you want to assign using C# code then it is as simple as in Claus' answer. However if you only know the name of the resource but not which dictionary its found in then its much tricker.
It is possible to write a routine (you can probably find one in SO or elsewhere on the web) that you can use to hunt up the Visual tree using the VisualTreeHelper looking at all the Resource properties along way. You could probably get away with this but be aware that this may search more dictionaries than the original Xaml version would and its possible for you to get some unexpected value.

Related

UWP MVVM XAML Dynamic UserControl Manager

I need help with a change of perspective.
I got stuck trying to approach UWP in a way I used to do in WPF regarding a MVVM pattern for managing UserControls dynamically.
I naturally tried to perform the same pattern in UWP but got stuck on various things like UWP not supporting 'x:Type' ...
Situation is; time to rethink this approach and look for a new direction. Seems I'm forced to abandon to use implicit binding in a similar fashion to the WPF pattern, using the Content property of a ContentPresenter and a VM property 'of type Object', which maintain a selected ViewModel. It was a simple and clean approach for matching up the correct View automagically with the VM set in ActiveViewModel.
the below was such a simple way of managing many views all over the place, odd MS not fixing this? But, back to the big Q: what now in UWP!?
<ContentPresenter Content="{Binding ActiveViewModel}">
<ContentPresenter.Resources>
<DataTemplate DataType="{x:Type local:OneViewModel}">
<local:OneView />
</DataTemplate>
<DataTemplate DataType="{x:Type local:TwoViewModel}">
<local:TwoView />
</DataTemplate>
</ContentPresenter.Resources>
</ContentPresenter>
What Shall I do instead of this!? Anyone found a new efficient way of doing it? I got stuck in my stubborn mind and need someone to kick my butt so I go forward. Getting to old to change, but due to this profession it seems I constantly have to. :)
Looking at the DataTemplate documentation, there's a paragraph explaining the situation which you are trying to figure out.
For advanced data binding scenarios, you might want to have properties
of the data determine which template should produce their UI
representations. For this scenario, you can use a DataTemplateSelector
and set properties such as ItemTemplateSelector to assign it to a data
view. A DataTemplateSelector is a logic class you write yourself,
which has a method that returns exactly one DataTemplate to the
binding engine based on your own logic interacting with your data. For
more info, see Data binding in depth.
Here, you have an example on how you can select distinct DataTemplate for items in a control such as a ListView based on defined conditions.
Your situation is a bit different from the one described above, but the solution should be within what is explained above.
Create a class which derives from DataTemplateSelector, and override the SelectTemplateCore methods exposed by it, where you define the logic of what DataTemplate should be selected for the specific presented object.
This Derived class should expose properties of type DataTemplate, which identify each single DataTemplate template object, you pretend to be able to choose from.
Just as in the example, you are probably better of by defining the DataTemplate resources on an higher level object, such as the Page itself.
Instantiate your DataTemplateSelector Derived class in XAML as a resource and set each of the properties exposed above of type DataTemplate to the analogous DataTemplate static resource.
Utilize the ContentTemplateSelector dependency property, by setting it your custom DataTemplateSelector.
With this logic, it should be possible to have your ContentPresenter decide correctly between which DataTemplate it should choose from, based on your required UI logic.

In static method bindings that exist inside DataTemplates, is it possible to pass in the instance of the entity?

Example:
<DataTemplate x:DataType="FooEntity">
<Grid Background="{x:Bind MyClass.MyStaticBindingMethod(???)}" />
</DataTemplate>
It’s easy enough to pass in properties of the entity, but I can’t see a way to pass in the instance itself. Is this feature not supported? I could store a reference to this in FooEntity with a property called Instance (for example), and then go MyClass.MyStaticBindingMethod(Instance), but just want to make sure there isn't a cleaner way.
Relevant docs: https://learn.microsoft.com/en-us/windows/uwp/xaml-platform/x-bind-markup-extension
You cannot pass the instance itself onto a DataTemplate.
The DataTemplate is only responsible for describing the visual structure of a data object and therefore its not part of its job to hold a explicit reference to any CLR object.
DataTemplate is defined to extend the visual structure of data objects, such as GridView/ListView, and those already handle the possibility of referencing to Collections, by setting the ItemsSource dependency property. Taking advantage of this, the DataTemplate simply exposes the customization of your visual structure. However this visual structure should be followed with the necessary bindings, to achieve your desired custom behavior.
If you are dealing with x:Bind, you will have to set the x:DataType, to the type of the Collection which you are setting as the Control ItemsSource, because the compiler needs that information at compile-time.
That is not a problem for Binding because those are evaluated at runtime, with the help of reflection.
I am not sure if I understand correctly, but to bind this, meaning the entity directly, you can just use empty binding:
Background="{x:Bind}"
or
Background="{Binding}"
This however means that FooEntity should derive from Brush so that it is compatible with Background type.

How to get Control from DataTemplate and ControlTemplate ? thinks so much

When i define a control in DataTemplate, how to get reference of this control ?
If the control in ControlTemplate of Style , how to get ?
You should instead tell us why you would need to reference a control inside a template.
Consider that the control will be rendered multiple times, so getting a single reference does simply not make any sense.
The most common approach to this is to 'name' the element that you wish to locate via x:Name="MyElementName", you can then use the FindName method to locate the names element. If your DataTemplate is being used in an ItemsControl to render multiple copies of yoru XAML markup, then clearly there will be a number of elements that share this same name. For this reason, there is a concept known as XAML namescope, you should read up on this to understand the scope of the name you provide.
If you require a more generic method for searching for elements in the visual tree, try Linq-to-VisualTree, you can use it to query you UI, for example:
var itemsFluent = this.Descendants<TextBox>()
.Where(i => i.Ancestors().FirstOrDefault() is Grid);
The above query will find all TextBoxs that have a Grid as a direct parent.
Finally, if you can avoid doing any of this, by using databinding, or event bubbling then do so! it is much easier.

XAML tag list reference

As the question suggests I'm simply looking for a XAML tag list reference. I've banged the obvious queries in Google/SO but not found what I am looking for yet. Any useful links welcome.
There's a WPF Binding Cheatsheet and another XAML for WPF Cheatsheet which might help, but really the "tags" in XAML are just the properties of the classes.
There isn't such a thing as a xaml tag list.
XAML is just a declarative way to instantiate .Net classes. Class names are elements in XAML and properties on the class are attributes or attribute elements using dot notation.
Tags in XAML only mirror the types in one or more assemblies that are bound to a particular XAML namespace.
There are however a specific set of elements that are specific to XAML in itself and are not related to any particular .Net assembly, those are usually in the x: namespace, more info here: XAML Namespace (x:).
There is no such thing as the XAML tag list since XAML is an open system.
There are, however, standard vocabularies. Rob Relyea's Blog is a good place to keep track of the standardization around these vocabluaries. For example, this is an entry for the Silverlight XAML vocabulary.
With WPF the XAML elements map to the classes like StackPanel. MSDN seems to give XAML examples for many of the controls.
There are XAML-specific conventions about representing things like complex properties and bindings. However, there is no definitive list of XAML tags. XAML tags are actually mapped to WPF objects. For example, <Button> is just a XAML representation of the System.Windows.Controls.Button class and the attributes allowed on the <Button> tag are the public properties of the Button class.
There should be several WPF cheatsheets available soon on http://www.devsheets.com (since around September 2011) ... You can download it there, and also buy printed versions with more detailed information on them (not all content fits in publicly available pdf, because pdf would not be readable if printed on paper without high quality print ... that is why we also decided to sell high quality laminated cheatsheet prints in addition to their free versions)

How to correctly inherit from a usercontrol defined in XAML in Silverlight

If I have a usercontrol (in Silverlight) that I've written, that uses XAML to define it's appearance, how can I make a customised version of it?
i.e. I have MyControl.xaml & MyControl.xaml.cs
What do I need to do if I want a "SpecialisedControl" child class? I assume I just make a new code file, then inherit from MyControl. But what if I want to change the appearance of the base class - then what do I do?
I wrote this thinking you were talking about WPF, rather than Silverlight, but there may be enough overlap for this to be helpful, so I'm posting it, anyway.
If by "change the appearance of the base class" you mean "provide a new template", then what you need is probably a CustomControl, not a UserControl.
The best way to accomplish this is to follow the example set by other Microsoft controls, such as Button or ListBox:
Create a class that derives directly from Control (or whatever is closest to your control).
If any properties will need to be exposed to the control (such as text on a button, for example), make sure that you properly define them as DependencyProperties.
As described here, create a ResourceDictionary called Themes/generic.xaml and add a style for your class that includes a template (don't give the style a key).
Use TemplateBindings for any properties of elements on your control that need to get values from your control.
If you'll need to attach any event handlers to elements in your template, give them a unique name. Microsoft uses the convention of prefixing these names with "PART_", and I think it's a good thing to do for the sake of consistency, but it's not strictly required.
Again, if you need to attach event handlers, overload OnApplyTemplate(). In this method, you should detach any old event handlers (we certainly don't want any memory leaks!), and look for elements that have the names your provided in your template--when you find them, attach event handlers, as necessary.
This is certainly much more work than simply deriving from UserControl, but if you want to be able to totally re-template controls, like you can with the built-in controls, this is the way to do it.
On the other hand, if all you want to do is to provide a certain amount of limited customization, such as changing the background, or associating a Command with some user action, then the best thing to do is to expose DependencyProperties, which can then be set in styles for your control, or on instances of your control, itself.
In the case you mentioned of wanting to customize the look in an inherited control, the process is pretty similar: just add a default style for the new control with a new template; if you need to add more event handlers, just be absolutely certain that you call base.OnApplyTemplate().
I dunno, I like doing things with just plain objects. Here's an article that describes an easy way to slip a XAML-designed control outside your inheritance hierarchy so that you can customize appearance and behavior using SimpleThingsLikeInheritance rather than MicrosoftStuffThatAlmostWorks
http://gen5.info/q/2009/02/10/subverting-xaml-how-to-inherit-from-silverlight-user-controls/
As Mihnea's link describes, the easiest solution is to simply add a namespace in your XAML:
C#
public class MyBase : UserControl
{
}
public class FirstUserControl : MyBase
{
...
}
XAML
<local:MyBase
x:Class="FirstUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:local="YourAssembly" ...>
<!-- Sticking with UserControl instead of local:MyBase makes this clearer -->
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
..
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</UserControl.Resources>
..Your XAML
</local:MyBase>
You can solve this by using a wrapper as described in the link above.
But you can also use the strategy pattern to solve this problem.
In this post I explain how you implement these two methods.
http://www.lab101.be/2008/07/silverlight-usercontrol-inheritance/