Binding to a cutom property of the template parent - wpf

Q: How do I bind to a custom property of the template parent from a child control's style DataTrigger
I've been scratching my head over this one for a couple of days.
I have a databound TreeView which uses a Style which has a Template. The TreeView is bound to a ObservableCollection and a HierarchicalDataTemplate + DataTemplate bind to properties inside a collection item.
FontGroup -> Font(s)
<Style x:Key="ExpandCollapseToggleStyle" TargetType="{x:Type ToggleButton}">
...
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ToggleButton}">
<Image x:Name="ExpanderImage" Source="/Typesee;component/Resources/tree_expand.png" RenderOptions.BitmapScalingMode="NearestNeighbor" />
<ControlTemplate.Triggers>
<DataTrigger Binding="??? IsItemSelected ???" Value="True">
<Setter TargetName="ExpanderImage" Property="Source" Value="/Typesee;component/Resources/tree_collapse_selected.png" />
</DataTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<ControlTemplate x:Key="FontTreeViewTemplate" TargetType="{x:Type TreeViewItem}">
...
<ToggleButton x:Name="Expander" Style="{StaticResource ExpandCollapseToggleStyle}" ... />
...
<ControlTemplate.Triggers>
<DataTrigger Binding="{Binding IsItemSelected}" Value="True">
<!-- WORKS FINE HERE -->
</DataTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
First I tried to bind like:
Binding Path=IsItemSelected, RelativeSource={RelativeSource TemplatedParent}
Then I read that might not work so I tried (including AncestorLevel 1+3):
Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type TreeViewItem}, AncestorLevel=2
Have also tried combos with UpdateSourceTrigger=PropertyChanged and Mode=TwoWay
If this is a flawed design please suggest a way of doing this: I basically want to change the image of the expand toggle button based on whether the property IsItemSelected is true on the TreeViewItem -- any ideas?
Thanks so much for any help!

The viewmodel in all likelihood will be the DataContext, so the binding should be a RelativeSource binding with a respective path which needs to explicity target the DataContext as the new source is the RelativeSource:
{Binding DataContext.IsItemSelected,
RelativeSource={RelativeSource AncestorType=TreeViewItem}}
As noted in my comment it might be advisable to extract this logic from the ControlTemplate as this leaves its bounds. One method would be subclassing the ToggleButton and exposing a public property for the image which then can be changed via a Style.

Related

Can't change content-template dynamically

I have a ContentControl that I need to set it's ContentTemplate dynamically.
so I decided to write 2 DataTemplates, and then style my ContentControl such that a trigger fires and set the proper template (dt1/dt2) when a Boolean dependency property in my view-model changes (true/false).
But the problem is if the Boolean property is primarily set to true, the data template will always be dt1 and changing the property to false wont change the template to dt2.
since the data triggers are bound to the Boolean dependency property, shouldn't changing the property result in firing the triggers?
notes:
There is a button in MyView which changes BooleanDependencyProp on it's
click event.
MyViewModel inherits from an interface that
implements INotifyPropertyChanged.
Xaml:
<UserControl x:Class="Views.MyView">
...
<StackPanel>
<ContentControl Content="{Binding RelativeSource={RelativeSource AncestorType=MyView}, Path=MyViewModel}">
<ContentControl.Style>
<Style TargetType="{x:Type ContentControl}">
<Style.Triggers>
<DataTrigger Binding="{Binding BooleanDependencyProp}" Value="true">
<Setter Property="ContentTemplate">
<Setter.Value>
<dt1 ... />
</Setter.Value>
</Setter>
<DataTrigger Binding="{Binding BooleanDependencyProp}" Value="false">
<Setter Property="ContentTemplate">
<Setter.Value>
<dt2 ... />
</Setter.Value>
</Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</ContentControl.Style>
</ContentControl>
</StackPanel>
This is a known shortcoming of the WPF framework, if you want to apply different data templates, consider either using the visual state manager to change the presentation, or swap out the content data template for a user control that changes based on the triggers instead, you'll get more mileage.
There's a lot more I could say, but it would involve knowing your scenario and the differences in these DataTemplates, why you are disambiguating, etc. Also, MVVM all around? or straight ahead Code+Markup style with a few view models?

set value for listboxitem templated binding

I have this style:
<Style x:Key="SelectableListBoxItemStyle" TargetType="{x:Type ListBoxItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<Border Background="Transparent"
BorderBrush="{TemplateBinding BorderBrush}"
CornerRadius="4"
BorderThickness="2"
x:Name="IconBorder"
Margin="4,2,4,2">
<ContentPresenter/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="true">
<Setter TargetName="IconBorder"
Property="BorderBrush"
Value="Blue" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
My problem is that I don't know which property to set on the ListBox, when consuming my style so that the borders of it's ListBoxItems would end up having the desired border brush. I would also like to make this work for the other border brush in my style.
I would like to be able to have two list boxes with this same style but different border colors. I have this for a ListBox:
<ListBox
ItemsSource="{Binding SelectedProduct.Pictures}"
SelectedItem="{Binding SelectedSet, Mode=TwoWay}"
ItemContainerStyle="{StaticResource ResourceKey= SelectableListBoxItemStyle}">
</ListBox>
Update..I tried this:
<ListBox
ItemsSource="{Binding SelectedProduct.Pictures}"
SelectedItem="{Binding SelectedSet, Mode=TwoWay}">
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}" BasedOn="{StaticResource SelectableListBoxItemStyle}">
<Setter TargetName="IconBorder" Property="BorderBrush" Value="Green" />
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
But, I get:
Error 8 TargetName property cannot be set on a Style Setter.
Instead of using a TemplateBinding you should try using a relative source binding.
BorderBrush="{Binding RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type Listbox}},
Path=BorderBrush}"
If you want to have a different border than that defined for the ListBox then you will need to add a brush resource to your ResourceDictionary and apply that instead:
<Listbox.Resources>
<SolidColorBrush x:Key="MyListBoxItemBorderBrush" Color="Red"/>
<Listbox.Resources>
and then in your template:
BorderBrush="{StaticResource MyListBoxItemBorderBrush}"
If you need certain items to have different borders then you need to look at a StyleSelector.
I am not 100% sure, but I think you may need a custom control for that. A least I know you can do it with a custom control!
If you create a custom control, extending from ListBox, that includes this style you've created, you can then create an attached property in it (something like ItemBorderColor) that you could bind to your border's BorderColor (actually, for a selection effect, you may want to create a trigger on you ControlTemplate () that applies that "ItemBorderColor" value to the border's BorderColor based on the "IsSelected" property).
There may be a pure XAML way to do it, but I do not know it....

Datatrigger on contentpresenter.content not working

I am trying to switch the content of a contentpresenter based on a datatrigger.I want to display a usercontrol in the contentpresenter.content, if i have a value set or else i need to display an error message.But the binding on my datatrigger fails stating that the property is not found.I cant get the datacontext to inherit for the datatrigger checking.I can make it work by using the commented out code.But i am confused why it doesn't work the normal way.
<ContentPresenter.Style>
<Style TargetType="{x:Type ContentPresenter}">
<Setter Property="Content" Value="{Binding UC}"/>
<Style.Triggers>
<!--<DataTrigger Binding="{Binding DataContext.HasValue,RelativeSource={RelativeSource AncestorType={x:Type ContentPresenter}}}" Value="false">
<Setter Property="Content" Value="No preview"/>
</DataTrigger>-->
<DataTrigger Binding="{Binding HasValue}" Value="false">
<Setter Property="Content" Value="No value"/>
</DataTrigger>
</Style.Triggers>
</Style>
</ContentPresenter.Style>
</ContentPresenter>
If you want to use triggers to display UserControl, you should use ContentControl not ContentPresenter.
I prefer to use ContentPresenter for CustomControls and When I am using the UserControl for views of Custom Data Types in my system and Allow to give dynamic behavior.
Example: To switch templates for ContentPresenter you need to set ContentTemplateSelector like this
<ContentPresenter Content="{Binding MyContent}"
ContentTemplate="{Binding MyContentTemplate}"
ContentTemplateSelector="{Binding MyContentTemplateSelector}"/>
MyContent, MyContentTemplate & MyContentTemplateSelector are Dependency Properties and can be binded wherever you are using its instance.
READ :
Usage of ContentPresenter
What is the difference between ContentControl and ContentPresenter
The binding mentioned in the question won't work as
ContentPresenter’s DataContext is automatically set to the value of
its Content property, while ContentControl’s DataContext is not.
Bindings are resolved relatively to the value of the DataContext property. If you declare a binding on the ContentPresenter, the moment its content is set, the binding would be re-evaluated.
ContentControl.Content Property can be changed on any trigger based on your requirement. If you want to use it to change on PropertyChanged Event of a property of ViewModel, DataTrigger can be used by binding it with a DataTemplate with UserControl instance in it or using static resource of that UserControl.
<ContentControl>
<ContentControl.Style>
<Style TargetType="{x:Type ContentControl}">
<Setter Value="{StaticResource UnSelectedDataTemplate}" Property="ContentTemplate" />
<Style.Triggers>
<DataTrigger Binding="{Binding Path=IsSelected}" Value="True">
<Setter Value="{StaticResource SelectedDataTemplate}" Property="ContentTemplate" />
</DataTrigger>
</Style.Triggers>
</Style>
</ContentContro.Style>
</ContentControl>
READ How to use triggers for content template, more details here
Difference in DataTemplate and StaticResource scope is DataTemplate creates a new instance of the template every time its applied.
Whereas, StaticResource is using the same instance of UserControl again (Static Instance).
You can also use EventTriggers to change content base don Control Events like MouseOver etc.
Alternate approach
Very similar to the above with slight difference. Defining as a data template in resources. Triggering for the content change is essentially identical.
...in <x.Resources /> tag:
<DataTemplate x:Key="DesignerTemplate" DataType="{x:Type vm:SolutionViewModel}">
<vw:SolutionDesignerView />
</DataTemplate>
<DataTemplate DataType="{x:Type vm:SolutionViewModel}">
<ContentControl Content="{Binding }">
<ContentControl.Style>
<Style TargetType="{x:Type ContentControl}">
<Style.Triggers>
<DataTrigger Binding="{Binding IsLoaded}" Value="True">
<Setter Property="ContentTemplate" Value="{StaticResource DesignerTemplate}" />
</DataTrigger>
</Style.Triggers>
</Style>
</ContentControl.Style>
</ContentControl>
</DataTemplate>
...then:
<ContentControl Content="{Binding Solution}" />
I usually use trigger Like this...
<UserControl>
<UserControl.Resources>
<DataTemplate x:Key="normalTemplate" >
<!-Fav UserControl->
</DataTemplate >
<DataTemplate x:Key="overWriteTempalte">
<!-Fav UserControl-> </DataTemplate>
</UserControl.Resources>
<ContentPresenter x:Name="ContentField"
Content="{Binding}"
ContentTemplate="{StaticResource ResourceKey=normalTemplate}" />
<UserControl.Triggers>
<DataTrigger Binding="{Binding Path=MyProperty}" Value="True">
<Setter TargetName="ContentField" Property="ContentTemplate" Value="{StaticResource ResourceKey=overWriteTempalte}" />
</DataTrigger>
</UserControl.Triggers>
</UserControl>
If Bindings are a problem Use Snoop to Detect binding errors

How do I do this in XAML?

I want to do this in XAML with a trigger, how do I do it?
If ListBox1.SelectedIndex > -1 Then
Border1.Visibility = Windows.Visibility.Visible
Else
Border1.Visibility = Windows.Visibility.Hidden
End If
This XAML code does NOT work. SelectedIndex member is not valid because it does not have a qualifying type name.
<ListBox.Triggers>
<Trigger SourceName="ListBox1" Property="SelectedIndex" Value="False">
<Setter TargetName="Border1" Property="Visibilty" Value="Hidden" />
</Trigger>
</ListBox.Triggers>
Can you show me how are you trying to do this in xaml?
In case of this error message you need to mention type name also with the property inside trigger.
<Trigger SourceName="ListBox1" Property="ComboBox.SelectedIndex" Value="-1">
<Setter TargetName="Border1" Property="Border.Visibility" Value="Hidden" />
</Trigger>
Further, it seems that you are adding a Trigger in <ListBox.Triggers> collection, but you can only add EventTrigger in to this collection. So you need to declate a Style for your ListBox to add a Trigger for that and your Border element should be inside the ControlTemplate of ListBox, but in your case Border seems to be outside of ListBox, so declaring a style will not be a solution. Instead you should use Binding with SelectIndex property with the help of a ValueConverter(say IndexToVisibilityConverter). You need to define this converter in codebehind and add it in resources.
<Border Visibility={Binding Path=SelectedIndex, ElementName=ListBox1, Converter={StaticResource IndexToVisibilityConverter}}/>
Choice is totally on your requirements.
It is as simple as this:
<Border x:Name="Border1" ... Visibility="Visible" ... />
...
<Trigger SourceName="ListBox1" Property="ListBox.SelectedIndex" Value="-1">
<Setter TargetName="Border1" Property="UIElement.Visibilty" Value="Hidden" />
</Trigger>
Update
I see from the new code you posted that you're trying to use a trigger directly on the ListBox. The trigger must be in a ControlTemplate to use SourceName. If your UI is done with "custom controls" (my preference), you will already have a ControlTemplate to put it in. If not, you can easily add one by wrapping your XAML in a generic "ContentControl" (base class, not any subclass) and setting its template, like this:
<Window ...>
...
<ContentControl>
<ContentControl.Template>
<ControlTemplate TargetType="{x:Type ContentControl}">
<Grid>
...
<ListBox x:Name="ListBox1" ... />
...
<Border x:Name="Border1">
...
</Border>
</Grid>
<ControlTemplate.Triggers>
<Trigger SourceName="ListBox1" Property="ListBox.SelectedIndex" Value="-1">
<Setter TargetName="Border1" Property="UIElement.Visibility" Value="Hidden" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</ContentControl.Template>
</ContentControl>
...
</Window>
A better solution would probably be to use custom controls. Using a binding with a converter is possible but not as elegant IMHO.

WPF ComboBox - showing something different when no items are bound

I have a ComboBox, and i want to change its look when the ItemsSource property is null. When it is in that state, i want to show a TextPanel with the text "Retrieving data" in it, and give it a look kind of similar to the watermarked textbox.
I figure to do this i need a ControlTemplate, and a trigger. I have the ControlTemplate here:
<ControlTemplate x:Key="LoadingComboTemplate" TargetType="{x:Type ComboBox}">
<Grid>
<TextBlock x:Name="textBlock" Opacity="0.345" Text="Retrieving data..." Visibility="Hidden" />
</Grid>
<!--
<ControlTemplate.Triggers>
<Trigger Property="ComboBox.ItemsSource" Value="0">
<Setter Property="Visibility" Value="Visible" />
</Trigger>
</ControlTemplate.Triggers>
-->
</ControlTemplate>
but my issue is how do i set up the trigger to show this when the ItemsSource property is null? I have tried a couple of different ways, and each way has given me the error message "Value 'ItemsSource' cannot be assigned to property 'Property'. Invalid PropertyDescriptor value.". My ComboBox xaml is this (including the attempted trigger):
<ComboBox Margin="112,35,80,0"
Name="MyComboBox"
Height="22.723"
VerticalAlignment="Top"
DisplayMemberPath="FriendlyName"
SelectedValuePath="Path"
TabIndex="160"
>
<Trigger>
<Condition Property="ItemsSource" Value="0" />
<Setter Property="Template" Value="{StaticResource LoadingComboTemplate}" />
</Trigger>
</ComboBox>
now should the trigger go on the ComboBox, or on the ControlTemplate? How do i access the ComboBox's ItemsSource property? Should i even be using a trigger?
Thanks!
Try putting {x:Null} for the value of the condition instead of 0.
Also I got it working by moving the Trigger to a style and modifing it slightly, see below.
<Style TargetType="ComboBox" x:Key="LoadingComboStyle">
<Style.Triggers>
<Trigger Property="ItemsSource" Value="{x:Null}">
<Setter Property="Template" Value="{StaticResource LoadingComboTemplate}" />
</Trigger>
</Style.Triggers>
</Style>
<ComboBox Style="{StaticResource LoadingComboStyle}" .... >
The reason it only works in a style, is that only EventTriggers are allowed in the triggers collection directly on the Framework Element. For property triggers (like above) you need to use a style (I learn something every day).
See FrameworkElement.Triggers
Note that the collection of triggers established on an element only supports EventTrigger, not property triggers (Trigger). If you require property triggers, you must place these within a style or template and then assign that style or template to the element either directly through the Style property, or indirectly through an implicit style reference.

Resources