binding to compound path - wpf

I'm creating a resource in the window xaml.
That resource is a controller, like this
<Window.Resources>
<ext:Controller x:Key="Controller"/>
</Window.Resource>
I have controls in my xaml that I want to bind to "compund members" in the Controller, so to speak.
Like if I hade a string in the controller and I want to bind to that strings length
<TextBlock Text="{Binding Source={StaticResource Controller},Path=myString.Length}"/>
or something like that.
It seems like a weird way to do it but I want to keep all of those members in the controller as opposed to making them separate resources, so they have access to certain things in the controller.
The real essence of the problem is that I have a couple of Windows and I want them to share the common resource (an instance of Controller).
So i put a static instnace of controller in controller. i actually want to bind like
<TextBlock Text="{Binding Source={StaticResource Controller},Path=StaticInstance.memberProperty/>
Is it possible to bind to a member of a member or what approach should I be using instead of wanting the "compound path in the binding", so to speak?
Thanks, guys!
Appreciate the help

StaticInstance is not a property of your resource (which is an instance) since it is static. If you want to bind to static members you can use the x:Static markup extension, note that the syntax is quite specific.
The binding probably would look like this:
{Binding Source={x:Static myns:Controller.StaticInstance}, Path=memberProperty}

Related

Binding three levels down in the data hierarchy

It's a good thing I don't mind feeling stupid.
I'm trying to bind to an ObservableCollection on my view model. The data hierarchy looks like: Parent -contains list of- Child objects. Nothing complicated.
At the outermost grid of my Xaml tree I establish a link to the view model with:
<Grid DataContext="{StaticResource src}">
Yes, src does reference the view model and the two dozen bindings before the problem textbox work fine. There is not another DataContext in my Xaml tree. Now I come to a simple textbox. I want to bind Textbox text to a child.property.
This works:
<TextBlock
DataContext="{Binding Parent}"
Text="{Binding Path=Child.Property}"
Style="{StaticResource headerMajor}"
/>
This doesn't work:
<TextBlock
Text="{Binding Source=Parent,Path=Child.Property}"
Style="{StaticResource headerMajor}"
/>
I thought they were two ways of saying the same thing. Ordinarily I wonder for a moment and then keep on coding. However, some advice I've read mentioned that DataContext attributes buried in Xaml controls can lead to hard to find bugs.
Please explain why one works and the other does not. This will help my grasp on the whole binding topic.
Jim
Source is a property which holds an object used as source for the binding, it does not resolve to a property. Hence your binding is looking for the property path Child.Property on the string "Parent", see the problem?

How to set a parameter from a parent view into a view model which is declared as a static resource within a user control

I have the following (condensed) silverlight xaml for a view / viewmodel:
<UserControl x:Class=MyView>
<UserControl.Resources>
<MyViewModel x:Name="MyViewModel"/>
</UserControl.Resources>
<Grid DataContext="{Binding Source={StaticResource MyViewModel}}">
<UserControl>
Hopefully this looks familiar to you all.
However, I would like to create 2 instances of this same view user control, but to pass in a parameter to the view model to allow me to have slightly different view model data based on a property which I pass into the view model. Something like:
<UserControl x:Class=MyView>
<UserControl.Resources>
<MyViewModel x:Name="MyViewModel" Filter="Some value set at a higher level"/>
</UserControl.Resources>
<Grid DataContext="{Binding Source={StaticResource MyViewModel}}">
<UserControl>
The problem is that I can't hard code the Filter parameter inside the user control, but need to set it at a higher level. Is there a way to obtain the filter parameter from higher up via binding, and what would the syntax look like. I was hoping something like the following:
Either directly from the parent something like:
<MyView>
<MyView.ViewModel Filter="All">
</MyView>
<MyView>
<MyView.ViewModel Filter="Some">
</MyView>
Or from user control looking upwards, something like:
<UserControl.Resources>
<MyViewModel x:Name="MyViewModel" Filter="{Binding FilterTypeFromDataContextHigherUpTheTree}"/>
</UserControl.Resources>
but I don't know if is is possible to directly refer to the static resource view model from the parent in order to set a property, or what the syntax would look like.
I also don't know if there is an easier way to do this, as I suspect my approach is not very elegant.
The real question is how can I pass a parameter into a view model which is a static resourd
Though it's possible to store the ViewModel as a resource, we usually see the ViewModel set as the DataContext of a view. Then, if someone needs to access the ViewModel through the View, they just cast the DataContext to the proper ViewModel type and access it's properties directly.
If you want to go the Binding route for your Filter you have a couple of choices. You can set the Bnding Soure to RelativeSource.TemplatedParent if the child control is placed inside of the parent control in a template (or Style). You could also use ElementName, but only if the named element is inside of the same scope (in your example above, the named element would have to be somewhere inside of MyView).
The final option I can think of would be to expose a DependencyProperty for the filter on MyView and then set the binding of the ViewModel to that property. This would effectively bubble the filter so that it's accessible outside of MyView, but I don't like this approach at all because it's adding properties to the View just for the sake of passing them to the ViewModel. That should never happen. The ViewModel should always be accessible independantly of the View, which is why I recommend exposing it through the DataContext property (inferred) or through a custom property specifically for the ViewModel (explicit).
I sometimes do this with my ViewModels (e.g., instantiate them as a resource). When I do this, I have my VMs extend DependencyObject, for reasons I'll detail later.
I'd recommend that you move them to app.xaml and define them as resources of the application, where they will be available to everyone as a resource of the application. That way you can
<UserControl
DataContext="{StaticResource MyViewModel}" />
In addition, you can bind properties of your ViewModels together. That's why I extend DependencyObject.
Of course, this limits you to a single instance of MyViewModel, which may or may not work in your case. If it doesn't work, I'd define a ViewModel which contains the shared data, then bind to this via a static resource, as in your "looking upward" example.

difficulty understanding and using xaml markup extentions

I am learning on to the concepts of WPF such as data binding, commands, resources, element bindings, styles etc, which use markup extensions extensively, and i am having problem understanding the meaning behind the Markup classes, as they are being used beyond what i understand they should be used for. So here are a few points i need to clear:
(all code snippets are from Pro WPF in C# 2010 book)
What is the meaning and use of Static extension? It can be used to
declare static resources, which can be declared in as
, but this xaml confuses me:
<Button ... Foreground="{x:Static SystemColors.ActiveCaptionBrush}" >
In {x:Static SystemColors.ActiveCaptionBrush}, what is the role
of static here, and what will change if i use x:Dynamic here? The
book says this xaml is equivalent to this codebehind:
cmdAnswer.Foreground = SystemColors.ActiveCaptionBrush;
This means that if i have a class with static properties, i should
be able to use something like this:
<Button ... Foreground="{x:Static MyClass.SomeStaticProperty}" >
But it didn't work, despite i had created a class, i tried using
local:Static (referring to the local namespace) but VisualStudio
didn't allow me to use it. What is the proper method of achieving
this?
What is the meaning of Binding (beyond obvious meaning, what is
happening when i am binding)? It is used for resource binding, or
data or element binding. I was able to understand element binding,
but binding to objects that are not elements caused problems. For
example:
<TextBlock Text="{Binding Source={x:Static SystemFonts.IconFontFamily},
Path=Source}"></TextBlock>
Here it is binding to the text to the SystemFonts.IconFontFamily
property, what is the use of x:static in this case, and how to bind
it to a property in a class that i have created? Also how to update
the text property of the textfield if the value of the binding
target changes? Due to binding, it should update by itself, is this
the case?
All the examples in the book make use of SystemFonts.IconFontFamily,
none that i have seen explains the use of such binding, and how to
do it for the classes that i create? Some help in this regard is
needed. I want to ask more about binding, but i will do so in a
separate question about binding only.
Finally, recommend a book or resource that explains what is
happening, instead of how to do this and that?
Answers....
1)
You said ...
... This means that if i have a class with static properties, i should be
able to use something like this:
<Button ... Foreground="{x:Static MyClass.SomeStaticProperty}" >
But it didn't work, despite i had created a class, i tried using
local:Static (referring to the local namespace) but VisualStudio
didn't allow me to use it. What is the proper method of achieving
this?
Well your trial attempt was correct but it was incorrect to what term you have applied that namespace token to.... local namespace token applies to the class that is declared under it so...
<Button ... Foreground="{x:Static local:MyClass.SomeStaticProperty}" >
Should work just fine provided that SomeStaticProperty is a valid Brush.
In this example, the whole markup was internally equivalent to Binding as ...
Binding.Source = {x:Type local:MyClass}
Binding.Path = SomeStaticProperty.
2)
You had an example...
<TextBlock Text="{Binding Source={x:Static SystemFonts.IconFontFamily},
Path=Source}">
</TextBlock>
So use the same equivalence from example 1 and apply it to this example...
<TextBlock Text="{Binding Source={x:Type SystemFonts},
Path=IconFontFamily.Source}">
</TextBlock>
3)
I learned this whole thing from MSDN... I dont think we can have any other legitimate source than that.

Beginner - confused about binding and resources in WPF

I'm trying to learn WPF but I find it very difficult to understand bindings, the "resources" thing, and object creation.
My background is in C++/MFC and C#-Winforms.
My questions:
Most of the examples I see in XAML (in MSDN and in two other WPF books I've read) use StaticResource in the binding expression. Are these related in any way to static members? Or is this just a misleading name? When a reference is made to any object as a StaticResource, when is it instantiated?
As far as I can see StaticResources are used with "things" defined in the "Resources" section of the app/window/control etc.
Now, these Resources sections are very confusing to me.
What exactly are they? From my experience in MFC these were icons, strings, etc. However, judging by all the examples I've seen, in WPF these seem to be essentially a "dumping ground" for
(a) all kinds of global object definitions in markup (styles, data templates, etc)
(b) all kinds of global object instantiations in markup
Am I correct? This strikes me as very messy.
It essentially involves learning all sorts of semi-DSLs in XAML (for defining styles, for defining data templates, for creating objects etc), and sticking them together in the same place.
I keep thinking about something like editing the resource file (.rc) in MFC by hand. At least there the sections were well separated and the syntax for each resource was relatively simple.
To tie up the previous two questions: When I define an object instance in the Resources section, and later reference it from a StaticResource binding, when exactly is it instantiated?
MSDN says (in "How to: Make Data Available for Binding in XAML"):
one way you can make the object
available for binding is to define it
as a resource
However, this isn't very clear. What do they mean available? Do they mean created? Do they mean hooked up to the binding subsystem? And when exactly is that object created?
From playing around with a simple example I saw that WPF seems to create this object for me when it tries to attach the binding. And this is even more confusing.
EDIT:
After the clarification by karmicpuppet below, I'm still confused as to how this is connected to Binding.
Suppose I have in my resources:
<local:Person x:Key="MyPerson" Name="Title"/>
(where Person is a class with a property called Name) and then in the window I have:
<TextBlock Text="{Binding Source={StaticResource MyPerson}, Path=Name}"/>
1) What does this do? Does it goes through the same steps - searching for the resource and then applying it to the Text property? Does the MyPerson object gets created at the time of Window creation, or later?
2) Do I have to use the Binding mechanism to bind to the Name property? Can't I bind to it directly like you did above with myBrush? Why can't I do something like this?
<TextBlock Text="{StaticResource MyPerson, Path=Name}"/>
Is it just a short-sightedness on the part of the framework? I think I'm missing very big here, but I can't seem to understand what...
3) I tried using DynamicResource, but I am very confused about each step I took.
a) Added a DependencyObject with a DependencyProperty above my single Window class in code (is this DependencyObject necessary?)
public class SomeText : DependencyObject
{
public string Header
{
get { return (string)GetValue(HeaderProperty); }
set { SetValue(HeaderProperty, value); }
}
public static readonly DependencyProperty HeaderProperty =
DependencyProperty.Register("Header", typeof(string), typeof(SomeText), new UIPropertyMetadata(0));
}
b) Added an instance of it to the Windows.Resources (is this necessary with DynamicResource? MSDN seems to say no, but if so I can't figure out how to do the next step in XAML)
c) I tried both:
Text="{Binding Source={DynamicResource HeaderText}, Path=Header}"
Which gave me an exception, and
Text="{DynamicResource HeaderText}"
But I couldn't understand where to put the path to the Header property.
This is my 5th or so attempt to fiddle around with WPF lately, and each time I get stumped by this seemingly simple things which don't work. I've read 2 books and I really try to understand the MSDN articles, however they're of no help at all.
First, an overall comment:
WPF is hard to learn. It's hard to learn because there are several different fundamentally new concepts that you have to get your head around at the same time. The struggle that you're having right now is that you're trying to learn at least three different things at once:
How the XamlReader (and particularly markup extensions) deserializes XAML into objects.
How the FrameworkElement's resource dictionaries work.
How data binding works.
Something like this:
<TextBox Text="{Binding Source={StaticResource MyPerson}, Path=Name}"/>
is engaging (at least) three very different technologies at the same time. Those technologies are all designed to be as flexible as possible, which only makes them more confusing to the beginner. The idea that a binding source can be just about anything: that's hard to grasp. The idea that a markup extension is a special kind of serialization format that supports recursion: simple enough to understand in principle, but a little baffling when you first start working with real-world examples. The idea that a resource dictionary can contain just about anything, and that the resource searching algorithm essentially makes resources inheritable: again, pretty simple in concept, but easy to lose the thread of when you're trying to figure out data binding and XAML at the same time.
It's frustrating, because something that's conceptually simple - "I want to bind this control to a property of an object that I've created" - requires that you understand a great many things before you can actually express it in XAML.
The only solution is to be patient, and to make sure you understand things at the lowest level possible. When you see this:
{StaticResource MyPerson}
you should be able to think, "That's going to invoke the StaticResource markup extension handler, which retrieves an object from a resource dictionary using the key MyPerson when the XAML is deserialized.
It's extremely challenging at first. I've been developing software professionally for 35 years, and I've found WPF to be the most challenging technology platform that I've ever learned by a considerable margin. But all of this stuff is hard to learn because it's incredibly functional and flexible. And the payoff of learning it is huge.
To address a couple of issues that karmicpuppet didn't:
From my experience in MFC [resources] were icons, strings, etc.
That hasn't changed. You can still create resource files in WPF and load them into objects at runtime. There are lots of different ways of doing this - you can create resources in the resource editor and load them via the Properties.Resources object, you can add image files (for instance) to the project, have them compiled as resources, and load them using their URI, and there are plenty of other ways that I don't know about.
The resources available to FrameworkElements via their resource dictionaries are a different thing. Well, sort of. Here's an example:
<Window.Resources>
<Image x:Key="MyImage" Source="images/myimage.png"/>
</Window.Resources>
This creates an Image object and adds it to the Window's resource dictionary with a key of MyImage You can then reference that object via the StaticResource markup extension in XAML, or the FindResource method in code.
Setting the Source attribute on the Image element in XAML also makes the XamlReader use the ResourceManager to read the image data from the project's compiled resources at runtime when it creates the Image object.
In practice, this is nowhere near as confusing as it is when you're first learning WPF. I never get resources that ResourceManager loads and resources stored in resource dictionaries mixed up.
And when exactly is that object created?
Any object defined by a XAML element is created when the XamlReader reads the element. So this:
<Window.Resources>
<local:Person x:Key="MyPerson"/>
</Window.Resources>
instantiates a new Person object and adds it to the Window's resource dictionary with a key of MyPerson. It's exactly equivalent to doing this in the Window's code-behind:
AddResource("MyPerson", new Person());
So why don't you just do it in code-behind? Two reasons:
First, it's consistent. If you define all your resources in XAML, you only need to look in XAML files to find what your resources are. If you define them in both XAML and code-behind, you have to look in two places.
Second, the IDE knows about resources that you define in XAML. If you type
<TextBox Text="{Binding {StaticResource MyPerson}, Path=Name}"/>
in your XAML, the IDE will let you know if you haven't defined, somewhere in the hierarchy of resource dictionaries, a resource whose key is MyPerson. But it doesn't know about resources that you've added in code, and so even though the resource may actually be findable at runtime, the IDE will report it as a problem.
Think about it this way: all FrameworkElements (Windows, Buttons, other Controls, etc), as well as the Application object, contain a Dictionary of Resources. Whenever you define a resource in XAML as shown here:
<Window>
<Window.Resources>
<SolidColorBrush x:Key="myBrush" Color="Red"/>
<DataTemplate x:Key"myTemplate">
<!--Template definition here -->
</DataTemplate>
</Window.Resources>
</Window>
It's like doing something like this in code:
class Window
{
void Window()
{
this.Resources.Add("myBrush", new SolidColorBrush(Brushes.Red));
this.Resources.Add("myTemplate", new DataTemplate());
}
}
You can put all kinds of objects as Resources. Anything that you would like to re-use throughout your application, you can define it as a Resource.
Now, when you do use a "{StaticResource}" as follows:
<Button Background="{StaticResource myBrush}"/>
This is like telling WPF to search for the corresponding "myBrush" resource and apply it to the Background property. What will happen is WPF will first search the resource in the Button's resource dictionary, and if it's not found will search its parent, then its parent's parent, and so on up to the application's resources.
The "static" thing in "StaticResource" just distinguishes it from the other type of resource-lookup called "DynamicResource". The difference between the two is answered in this link.
When applied to Binding, it also works the same way. Say, for instance, you have the following resource in your XAML:
<local:Person x:Key="MyPerson" Name="Title"/>
and used it as:
<TextBlock Text="{Binding Source={StaticResource MyPerson}, Path=Name}"/>
In this case, what will happen is something like this:
Binding b = new Binding();
b.Source = FindResource("MyPerson");
b.Path = "Name";
[TextBlock].SetBinding(TextBlock.TextProperty, b);
Again, the "{StaticResource}" markup in the XAML tells WPF to search for the corresponding resource and set it as the value for the a property. In this case, the property is Binding's "Source" property.
That's the basics. Hope you find this helpful

Is there a way to convert WPF binding markup to and from an instance of the binding class?

For example I have the following binding markup
Text="{Binding Path=FirstName}"
pretty simply but it could be much more complex, I need to be able to parse this markup and get it into some objectified form such as an instance of the Binding class.
Something that could work in reverse, an instance of the binding class to spit out the markup would be great as well.
I know such a thing must exist in the framework but I dont know where/what class.
I have looked at XamlReader but was unable to get it working because in this case I am missing context as I am only working with bits of the project and not the whole.
You can get the Binding object using GetBindingExpression, for example if you have:
<TextBlock Name="MyTextBlock" Text="{Binding Name}"/>
You can use:
BindingExpression expr = BindingExpression.GetBindingExpression(MyTextBlock, TextBlock.TextProperty);
Binding bindingObject = expr.ParentBinding;
To use XAMLReader you have to surround it with a valid root. then this shoudl work.

Resources