Can I bind to an ancestor DataTemplate in Silverlight? - silverlight

I'm having trouble pulling off a binding that I believe should be valid in Silverlight 5:
<Controls:GraphLayout>
<Controls:GraphLayout.VertexTemplate>
<DataTemplate>
<TextBox ... />
</DataTemplate>
</Controls:GraphLayout.VertexTemplate>
<Controls:GraphLayout.SubgraphTemplate>
<DataTemplate>
<Controls:GraphLayout VertexTemplate="{Binding VertexTemplate, RelativeSource={RelativeSource AncestorType=Controls:GraphLayout}}"/>
</DataTemplate>
</Controls:GraphLayout.SubgraphTemplate>
</Controls:GraphLayout>
This is a simplified example but hopefully it's pretty readable. In excessence I'm trying to bind the VertexTemplate of the SubgraphTemplate to the VertexTemplate of the containing control (the root GraphLayout control). Unfortunately, in the code behind I can see that VertexTemplate is null in the subgraph control.

May be your code can work (this is strange that you bound to something that doesn't have an x:Key and I think you should use {StaticResource SomethingWithName})).
But actually what you looking for is DataTemplateSelector. It's very easy to use and actually support the logic you described.

Related

Setting the background color of separate WPF ListBox items

I want to set the background color separately for each item in a WPF ListBox. e.g. If I am adding Widgets to the ListBox, I might set the background color for each one based on the type of widget. This must be done in code (not XAML) as I only know what the items are at run time.
I know how to use ItemContainerStyle to set the style for all items, but how do you do it separately for each item?
Yes you do set ItemContainerStyle, using a StyleSelector.
This example at MSDN is exactly what you are looking for.
There are lots of ways to do this.
One is to use a StyleSelector, as loxxy suggests. This is pretty low on my list, because that kind of code is harder to read (well, find) and test than I'd like.
Another is to use a DataTrigger in the style. This is simple, if (and only if) the items all implement a common property that can be used in the trigger. You might be well served by implementing a wrapper class that exposes this common property, and contains the logic that figures out what value to assign to the property based on the object it's wrapping. (Whether or not this is easier than a StyleSelector is certainly arguable.)
If the items are really and truly heterogeneous, you can accomplish the result by using data templates, e.g.:
<ListBox.Resources>
<DataTemplate DataType="{x:Type local:Foo}">
<TextBlock Text="{Binding FooText}" Background="Red"/>
</DataTemplate>
<DataTemplate DataType="{x:Type local:Bar}">
<TextBlock Text="{Binding BarText}" Background="Yellow"/>
</DataTemplate>
<DataTemplate DataType="{x:Type local:Baz}">
<TextBlock Text="{Binding BazText}" Background="PapayaWhip"/>
</DataTemplate>
</ListBox.Resources>
etc. This would generally be my first choice, but your question doesn't really explain enough about the circumstances to know if it's the right way to go or not.

For WPF, Is it overkill to use a setter to set the itemtemplate property?

When I searched the internet to find out how to set the itemtemplate for a listbox, I found an example where they used a Style Setter in the window.resources to do this. So, I have a couple of options, I can either create a datatemplate in my window.resources, or, create a Style Setter. Would it be overkill to set the style instead of the datatemplate? Which method should I use?
Thank You.
You can't say one or the other is better, it depends. Implicit DataTemplates are a nice way to globally (even if just for part of the visual tree) how a Type should look. While using ItemTemplate allows you to indicate how it should look in a given ItemsControl (i.e. ListBox, ComboBox, etc.).
You can even use a combination of both of them, which allows you have a "default" look, but customize it per control or control type.
Even with ItemTemplate, you can set it globally for say all ListBoxes, or for just one ListBox instance. So again, sometimes one method is better, sometimes not. It depends on what you are trying to do.
Styles in general are used to apply the same values to different instances of the same type. If this is not the case there is no need to create a style at all.
I prefer to make a <DataTemplate> for the type of item and then let WPF figure it out.
<DataTemplate DataType="{x:Type local:Task}">
<StackPanel>
<TextBlock Text="{Binding Path=TaskName}" />
<TextBlock Text="{Binding Path=Description}"/>
<TextBlock Text="{Binding Path=Priority}"/>
</StackPanel>
</DataTemplate>
<List ItemSource="{Binding MyListOfTaskItems"/>

Are "{Binding Path=.}" and "{Binding}" really equal

In my WPF project, I have a ListBox that displays items from a List<string> collection. I wanted to make the text of these items editable, so I wrapped each of them in an ItemTemplate with a TextBox (might not be the best way, but I'm new to WPF). I was having trouble simply binding the TextBoxes' Text property to the value of each item. I finally stumbled upon an example using a single dot or period for its Path property ({Binding Path=.}):
<ListBox ItemsSource="{Binding ElementName=recipesListbox,Path=SelectedItem.Steps}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBox Text="{Binding Path=.}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
However I don't understand why simply using {Binding} didn't work.
It raised a "Two-way binding requires Path or XPath" exception, as according to Microsoft:
[...] a period (.) path can be used to bind to the current source. For example, Text="{Binding}" is equivalent to Text="{Binding Path=.}"
Could someone shed light on this ambiguous behavior?
EDIT: Moreover, it seems {Binding Path=.} does not necessarily give two-way binding, as modifying the text and moving the focus does not update the underlying source (the same source has also properties displayed and successfully modified on a DataGrid control). I'm definitely missing something here.
The point of the exception presumably is that you cannot two-way bind a binding-source itself, so it tries to prevent you from creating a binding which does not behave the way you would want it to. By using {Binding Path=.} you just trick the error detection.
(Also it's not unheard of that documentation is erroneous or inaccurate, though i do like the MSDN documentation a lot in general as it usually does contain the crucial points one is interested in)
The documentation states that {Binding} is equivalent to {Binding Path=.}. However it is not equivalent to {Binding Path} as you have typed. If you include the Path property, you must assign it to something, be it Path=. or Path=OtherProperty.
These are not the same. If you bind this where ConsoleMessages is an ObservableCollection string with just {Binding} you get a "Two-way binding requires Path or XPath." exception where as {Binding Path=.} works. This is with WPF 4.0...
<ItemsControl x:Name="ConsoleOutput" ItemsSource="{Binding ConsoleMessages, Mode=OneWay}" MaxHeight="400">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBox Text="{Binding Path=.}" BorderThickness="0" Margin="0" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
My 2p worth...
In short, the difference between the two is analogous with the difference between the traditional pass by value and pass by reference. (FYR - What's the difference between passing by reference vs. passing by value?)
However I don't understand why simply using {Binding} didn't work (it raised a "Two-way binding requires Path or XPath" exception)
Lets assume here for now that {Binding} can be used for two way binding. In general {Binding} creates a value based link with datacontext which does not allow updating the datacontext.
Whereas {Binding Path=.} creates reference based link with the memory area referenced by the 'Path' which allows updating the value through reference.(in this case 'dot' the current datacontext).
Hope this helps!

WPF: CommandParameters for input bindings

One of the things I really like with WPF is the extent to which my views can be built declaratively, ie. using XAML rather than code-behind.
Now I'm really stumped by InputBindings, because their CommandParameters don't accept bindings. I imagine my case is pretty generic and straightforward, but I cannot see how I can do it without resorting to code-behind. Consider:
<ListBox Name="casingsListBox" ItemsSource="{Binding Path=Casings}" SelectedValuePath="Id">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=Title}"/>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.InputBindings>
<!-- Doesn't work: -->
<MouseBinding Gesture="LeftDoubleClick"
Command="ApplicationCommands.Open"
CommandParameter="{Binding RelativeSource={RelativeSource Self} Path=SelectedValue}"/>
</ListBox.InputBindings>
</ListBox>
This will not work, since the binding expression for the MouseBinding's CommandParameter is illegal.
I ask myself: what's the point of adding a mouse-click gesture to a listbox if I cannot get to the selected value?
This can be easily solved using a code-behind event handler, of course, or by having the command consumer extract the id from the command source, but there are several reasons why this is undesirable. Apart from the fact that droves of code-behind code defeats (some of) the purpose of WPF in the first place, it makes the UI designers working in Expression Blend less empowered. And dammit, my command parameter shall be an id, not some UI element!!
Subjective: Having browsed SO for a while, I'm struck by the amount of code I see in the WPF-related questions. I get the feeling we developers stick to our old habits and happily hack away in the code-behind file rather than trying to utilize the fresh take on UI building that WPF is supposed to represent. What do you think?
But most importantly: can anyone show me a code-free workaround for this seemingly trivial problem? Preferably without terrible hacks like this one.
I wrote a markup extension that allows an InputBinding's Command to be databound :
<KeyBinding Modifiers="Control" Key="E" Command="{input:CommandBinding EditCommand}"/>
Your situation is slightly different since you want to bind the CommandParameter, but you can probably adapt my code to fit your case. Note that this code uses private reflection, which only works in full-trust, and can be broken in later versions of WPF (actually it is broken in WPF 4.0... I can post a modified version if you need it).
Another option is to use the CommandReference class that can be found in the MVVM toolkit :
<Window.Resources>
<c:CommandReference x:Key="EditCommandReference" Command="{Binding EditCommand}"/>
</Window.Resources>
...
<KeyBinding Modifiers="Control" Key="E" Command="{StaticResource EditCommandReference}"/>
Again, this is for binding the Command property, but can probably be adapted to bind the CommandParameter...
The new way to solve this problem is by using Expression Triggers / Actions which allow you to set up keyboard shortcuts on arbitrary controls that do custom actions (like firing a Command).

WPF Creating a ControlTemplate that is DataBound

I have a control bound to an Object and all is well but I want to turn it into a control template bound to different objects of a similar type. I would like to do this exclusively in xaml, if possible. Any good tutorials that outline the steps?
<TextBlock Text="{Binding Source={StaticResource BorderControl}, Path=ControlName}"/>
EDIT: With a little more experience, it turns out what I need is the ability to Set the Binding source based on a property of the control. i.e.
<TextBlock Text="{Binding Source={StaticResource {TemplateBinding Tag}}, Path=ControlName}"/>
The control exists within a ControlTemplate but works correctly if I bind it directly to the data -- if that makes a difference. I don't know if this is possible or if it's the correct approach. Any thoughts welcome!
EDIT:
This doesn't work either.
<TextBlock Text="{Binding Source={TemplateBinding Tag}, Path=ControlName}"/>
I think you want ContentPresenter here (http://msdn.microsoft.com/en-us/library/system.windows.controls.contentpresenter.aspx) - think of it as one line of an ItemsControl, it's got a content and a reference to a template that will represent that content.

Resources