wpf resource binding to another element's property - wpf

I'm new to WPF so pardon me if i'm asking something stupid.
I have an class named Person in my application.
Can i do something like
<local:Person x:Key="p" BirthYear="{Binding Path=Value, ElementName=year}" />
where 'year' is a control?

you are probably better off inverting your binding and binding the control to your class
<Control Value="{Binding Path=BirthYear}" DataContext="{StaticResource p}"/>

No, you can't because resources are not part of the same naming container (and are added differently to the visual tree).
Why do you need to store a Person (business object I assume) as a resource, but having its value coming from another control? Maybe if you explain your motivation we can help you find a better alternative.

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?

WPF TreeView question

Is it possible to store some data in every item of a TreeView control? I mean, something useful (e.g. a string) besides the header text?
Thanks.
Yes, WPF is "lookless", so your actual data can be anything you want it to be, and a TreeView is just a Template used to display the data to the user in a pre-determined way.
You can overwrite any part of that Template to be whatever you want, and/or have it bind to your data however you want.
Edit
I'm no expert on using the TreeView, but if you had a DataContext of List<Folder>, and each Folder object had a Name and a FullPath property, your TreeView could look something like this:
<TreeView ItemsSource="{Binding MyFolderList}">
<TreeView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"
ToolTip="{Binding FullPath}" />
</DataTemplate>
</TreeView.ItemTemplate>
</TreeView>
If you haven't already, I'd highly recommend looking into the MVVM design pattern when working with WPF. Basically your application is your classes (ViewModels), and the Controls/XAML (Views) are just a pretty layer that sits on top of your classes to make them user-friendly.
This is an important concept when switching from a WinForms TreeView to a WPF TreeView
It depends on what you mean by store data...
If you're just talking UI customization Rachel's answer above works.
If you're talking about storing arbitrary object values, such as information about the TreeViewItem, or maybe a relation between two items, you can use the Tag property of TreeViewItem. For example, I had to write a mapping UI where two trees linked together where each TreeViewItem from the first tree, could connect to 1 TreeViewItems of the second tree. I used the Tag property of the first TreeViewItem to store the connecting TreeViewItem.

SelectedItem of SelectedItem

first of all I would like to thank you for the many good posts that i read in this forum. Unluckily I could not find anything of help for my current problem (either here or anywhere else).
What I'm trying to do sounds quite simple, but I have no clue how to get it to work ... perhaps I'm still to new to wpf or I don't thing wpfy enough :)
I'm designing a front end for a part in an automated manufacturing:
I have a quantity of places where pallets can be put (but it can be empty as well).
Each pallet has up to 3 places where parts can be mounted
Everything is created dynamically of a database and is reacting to changes.
The position of the parts on the pallet comes from the database as well and should be visualized
What I would like to have is:
An overview over the pallet-places with a preview of the pallet
When I select a place I want to see a detail view of the place
When I click on a part on the pallet of the detailed pallet I want to see details to the part
The first two points are quite simple and work nicely:
I have got a DataTemplate for every component (part, pallet, pallet-place). Actually those are UserControls that are imported as Datatemplates
the overview is a ListBox with the places as DataContext
for the detail-place-view I use the UserControl and bound it to the SelectedItem of the Listbox
I tried to bind the Text of a Textblock to the ID of the selected Part ... and fail.
Probably I could use some global variables in the code behind - but that sound very ugly.
Can anybody help?
I have got a solution ... it is not nice but works.
I created an event in the pallet, that triggers, when the selected part-place changes
I handle the event in the pallet-place and create a new one
And finally I handle it in the overview and change the detailview accordingly
Most likely there are much nicer solutions, but it will suffice.
Perhaps try an ElementName binding?
<TextBlock Text="{Binding ElementName=Name_of_your_Listbox, Path=SelectedItem.ID" />
Can you post a bit more code of your TextBlock and your Binding?
Context is important, if i use a ContentControl and bind its content to the SelectedItem like this:
<ContentControl Content="{Binding SelectedItem, ElementName=mylistbox}">
I can bind to the ID of the selected item in the DataTemplate like this:
<ContentControl.ContentTemplate>
<DataTemplate>
<TextBlock Text="{Binding ID}" />
</DataTemplate>
</ContentControl.ContentTemplate>
That is because setting the Content of the ContentControl automatically sets the DataContext as well, and this binding is relative to the DataContext since no source (ElementName, RelativeSource, Source) has been specified.
I do not know how your UserControl handles the context, if the DataContext is not affected such bindings will not work. You would need to bind directly then:
<uc:MyDetailsView Data="{Binding SelectedItem, ElementName=mylistbox}">
<!-- ... -->
<TextBlock Text="{Binding SelectedItem.ID, ElementName=mylistbox}" />
This of course defeats the purpose of having the binding on the UserControl itself in the first place. But unless you post some relevant code it's quite hard to tell what is wrong.
Also check the Output window in VisualStudio, binding errors will show up there and might provide valuable information as to what went wrong.

Is Element Binding to a Collapsed UserControl a Sloppy, Cheap Trick?

I'm sure that most of us will agree that it is possible to run out of declarative DataContext sources from parent or self contexts. We then might resort to Binding to a parent Tag and then use Element Binding. So the source might look like this:
<Grid.Tag>
<Binding Path="MyProperty" Source="{StaticResource MySource}" />
</Grid.Tag>
What happens when we can't even do this? My next sloppy trick is to use a collapsed UserControl element:
<UserControl
x:Name="MySloppyControl"
DataContext="{StaticResource YetAnotherSourceInThisCrazyGrid}"
Foreground={Binding CrazyForegroundColor}
Visibility="Collapsed" />
Now I can do this:
<Grid.Resources>
<Style TargetType="{x:Type TextBox}">
<Setter Property="Foreground" Value="{Binding CrazyForegroundColor, ElementName=MySloppyControl}" />
</Style>
</Grid.Resources>
Assuming that I explained this adequately, is this collapsed UserControl pattern misguided?
Not that I haven't done it myself, but I would have to say "yes" -- that pattern is misguided.
In those few cases where I chose to do this my code looked like this:
<Control x:Name="Whatever" DataContext="..." />
<Control x:Name="SomethingElse" DataContext="..." />
Since a control is invisible by default this acheives the same effect with less code.
Having said that, let me explain why I think this approach is misguided:
WPF is all about binding to data. If you have some data to bind to, it is either part of your model (or viewmodel) or it is external. If it is part of your model (or viewmodel) and your model's structure is well-defined you should be able to access it through the current DataContext. On the other hand, if it is static you should be able to access it directly from the target.
For example, let's say you want to populate a ComboBox with all the possible WidgetTypes from the model. If your model is well-constructed, the binding can be as simple as:
<ComboBox ItemsSource="{Binding DataSet.AllWidgetTypes}" />
This assumes that your ComboBox's DataContext is a "Widget" and that "Widget" has a "DataSet" property that gives access to other related data. Alternatively if the list of available types might change based on the other details of the Widget, the binding might be simply {Binding AppliableWidgetTypes}.
The other situation in which you might want a "separate DataContext" as you call it is when referencing static objects, such as through x:Static or StaticResource. In these cases there is a better way to do it: Set Binding.Source. It looks like this:
Text="{Binding DefaultFontSize,Source={x:Static ApplicationProperties.Instance}}"
or this
Text="{Binding PropertyName,Source={StaticResource ResourceContainingProperty}}"
If your motivation is to avoid creating a viewmodel to combine multiple model objects, use C# anonymoust types to construct an poor-man's viewmodel. For example:
DataContext = new { something = 123, whatever = "Test" };
Another common pattern is to create properties on the control and use a ControlTemplate and TemplateBinding to bind to them.
This leaves one final situation, which is when you really want a shared value and you want no code-behind at all. In this case I have actually gone ahead and used the invisible <Control> as shown previously. So there are rare situations where it may apply.

PropertyValueEditor and DependencyObject in Blend 3 - Silverlight DesignTime support

I'm working on a set of controls that has a number of DependencyProperties. The properties are themselves DependencyObjects and created during the get method of the properties. During the Get method, they are also set back to the propertybag using the SetValue() method, so they are in fact valid in Xaml and their properties can be storyboarded without having to explicitly created in the the visual tree.
These DependencyObjects has all its properties as DependencyProperties as well, for supporting DataBinding. They are as mentioned above possible to use in Storyboards.
At the same time I'm developing special designtime support for Blend 3 for these properties and have created an InlineEditorTemplate in the form of a Control. I create the template and set it for the PropertyValueEditor like this:
var vectorEditControl = new FrameworkElementFactory(typeof (VectorEditorControl));
var dataTemplate = new DataTemplate {VisualTree = vectorEditControl};
InlineEditorTemplate = dataTemplate;
In the Control I have the following:
<Grid DataContext="{Binding Value}">
<StackPanel Orientation="Horizontal">
<TextBox Text="{Binding Path=X, Mode=TwoWay}"/>
<TextBox Text="{Binding Path=Y, Mode=TwoWay}"/>
<TextBox Text="{Binding Path=Z, Mode=TwoWay}"/>
</StackPanel>
</Grid>
The editor shows up and I can edit the data. And even while debugging, I see that it actually sets the data back to the DependencyProperties on the DependencyObjects, but nothing happens to the Xaml. So the data is actually not persisted in any way in the Xaml and lost when I close the Xaml file and open it again.
Is there anything I need to do specifically for it to actually get into the Xaml? I was under the impression that this would happen automatically?
Excellent Question!
The core issue you're running into a misunderstanding as to what PropertyEditors in Blend/Cider end up databinding to.
Consider this object graph:
- MyControl
-- MyControl.MyProperty
--- FooClass
---- FooClass.BarProperty
Let's look at a scenario where we have a PropertyEditor (of any type: Inline, Dialog or Extended) to property MyControl.MyProperty.
When inside MyPropertyPropertyEditor you'd expect to get a fully settable copy of FooClass and be able to manipulate it's members.
That's a good assumption, but the wrong one.
The core issue is that Blend/Cider have elaborate data structures that represent your model at design time. There's about 3-5 levels of abstraction in how Blend/Cider interact with an actual control.
Creating those levels of abstraction allows Expression Blend / Visual Studio designers to be leveraged between framewroks (Silverlight / WPF) and support advanced scenarios (like Property transactions and property chaining).
So, the value you actually get to DataBind to is just one of those levels of abstraction.
Don't believe me? In your custom PropertyEditor, register for this.DataContextChanged event and checkout the type in this.DataContext. You'll end up getting the PropertyValue class (or one of it's friends).
Every single property change you want persisted to XAML (and shown on the design surface) should go through those abstraction layers.
the question you have to ask yourself is "Where do I get one of these absteaction classes for my PropertyValue.Value property instance?".
Well, what I'd do if I were you is create a ModelItem around MyControl.MyProperty and set that as your PropertyEditor.DataContext.
We've shipped an example of using ModelFactory.CreateItem in the Silverlight Toolkit as part of the Chart DefaultInitializer: Source Code, Ning Zhang (Awesome Design Time Dev) explains about ModelItem
If you've got follow-up questions I'd consider pinging PeteBl or UnniR through the Silverlight Insiders mailing list.
Sincerely,
-- Justin
It partly solves my problem. I'm having a dialog with UnniR for a followup.
I couldn't see how I could use this together with the PropertyValueEditor, but for default values this is brilliant and something I'll implement ASAP.
Thanks.

Resources