ContentPresenter loosing it data binding after triggers invoked more than twice - wpf

I have created an extended button with 2 different border styles invoked by triggers in XAML. Both share the same contentpesenter but after changing the border style more than twice the content in the contentpresenter fails to display.
Below is a link to the entire project with a test bed application that demonstrates the issue, I think the issue is somewhere in the XAML below but I cannot see why it breaks:
Sample Button App
<Style.Resources>
<ContentPresenter x:Key="ButtonContent" Margin="5" HorizontalAlignment="Center"
Content="{Binding Content}"/>
</Style.Resources>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Grid Margin="{Binding KeyMargin}">
<Grid Visibility="{Binding RectangleVisibility}">
<Grid.OpacityMask>
<VisualBrush Visual="{Binding ElementName=rectBorder}" />
</Grid.OpacityMask>
<Border x:Name="rectBorder"
CornerRadius="{Binding BorderCorners}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
BorderThickness="{Binding BorderThickness}"/>
<Viewbox Stretch="Fill"
StretchDirection="Both">
<ContentControl Content="{StaticResource ButtonContent}"/>
</Viewbox>
</Grid>
<Grid Visibility="{Binding EllipseVisibility}">
<Ellipse Stroke="{TemplateBinding BorderBrush}"
StrokeThickness="{Binding BorderThickness}"
Fill="{TemplateBinding Background}">
</Ellipse>
<Viewbox Stretch="Fill"
StretchDirection="Both">
<ContentControl Content="{StaticResource ButtonContent}"/>
</Viewbox>
</Grid>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>

The problem is most likely that you cannot have the same element (the ContentPresenter in this case) in more than one place in the visual tree, and in which one of the two grids it ends up is undefined, i.e., an implementation archetype of WPF.
To get the element duplicated this might work:
<ContentControl Content="{TemplateBinding Content}"/>
or in your case
<ContentControl Content="{TemplateBinding Content}" Margin="5" HorizontalAlignment="Center"/>
instead of a static resource. The <ContentPresenter/> syntax is pretty much an optimized shortcut for that (or you could set x:Shared="False" on the resource, but having a ContentPresenter as a static resource is as far as I know not how it is intended to be used)
If the Button content is a UIElement itself though, it will be used directly itself in the visual tree, i.e., twice and this wont work either. A better solution would be to just have the content once in the control template and change the visual appearance around it, e.g., using a trigger to set the Grid's OpacityMask.
Another remark is that your control template is very tightly bound to where the Button is used, with direct bindings to the current data context, which reduces its reusability. Some easy fixes is to use TemplateBinding instead of Binding for BorderThickness respectively Margin (instead of KeyMargin), since those are existing properties of the Button.
For better reusability and cleaner code you should consider looking into creating a custom control deriving from Button with dependency properties for BorderCorners, the desired visual state (ellipse vs rectangle) etc. You might also want to use triggers to get the mouse-over effects of the button etc. Have fun control templating!

Related

Is there a way to see DropShadowEffect on designtime?

I want to attach a DropShadowEffect on a Border control. I see it on runtime but not in the designer.
<Grid>
<Border Background="LightGray"
BorderBrush="DarkGray"
BorderThickness="1"
ClipToBounds="True"
Width="400"
Height="100">
<Border Background="Transparent"
BorderBrush="Black"
BorderThickness="0,10,0,0"
Margin="0,-11,0,0">
<Border.Effect>
<DropShadowEffect ShadowDepth="0"/>
</Border.Effect>
</Border>
</Border>
</Grid>
It's quite annoying, especially if working on custom control library.
The former and now apparently obsolete DropShadowBitmapEffect works on run- and designtime.
Edit:
This not a duplicate of other questions like Here as it is quite the opposite problem. The shadow effect appears at runtime, but not in the designer. Just try it out with NET-Framework WPF Project and the code above.

Images from Resources folder for custom controls in WPF

I'm trying to make a WPF window with a control realized by an array of RadioButtons, each of which is represented by a picture. I've used a template provided in this example, so the template looks like that:
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="RadioButton">
<Border BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="Transparent"
CornerRadius="20">
<Image Source="{Binding Path=Content,
RelativeSource={RelativeSource TemplatedParent}}"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
Now the problem is that, in order to set the picture on the control, I have to write the whole path to the picture, like that
<RadioButton Name="radioButtonNo" Checked="radioButton_Checked"
Content="C:\Myfolder\MyProject\Resources\MyPic0.png"
Style="{StaticResource Flag}" Width="75"/>
Naturally, I'd wish to be able to write something like
<RadioButton Name="radioButtonNo" Checked="radioButton_Checked"
Content="MyPic0.png"
Style="{StaticResource Flag}" Width="75"/>
but when I do this, all I get is a standard RadioButton with the filename as a caption. What am I doing wrong?
It should be sufficient to provide a correct relative path, like
<RadioButton Content="Resources/MyPic0.png" .../>
Note that image resources in WPF are usually managed as assembly resource files. Their Build Action is set to Resource and they are referenced by Resource File Pack URIs. The XAML parser automatically adds the missing pack://application:,,,/ prefix.
You may as well explicitly create the ImageSource instance that is assigned to the Source property of the Image control in the ControlTemplate:
<RadioButton ...>
<RadioButton.Content>
<BitmapImage UriSource="Resources/MyPic0.png"/>
</RadioButton.Content>
</RadioButton>
Or with an explicitly written Pack URI:
<RadioButton ...>
<RadioButton.Content>
<BitmapImage UriSource="pack://application:,,,/Resources/MyPic0.png"/>
</RadioButton.Content>
</RadioButton>

WPF IDataErrorInfo issues

I've used WPF and IDataErrorInfo in the past apps to display errors to the user via a controltemplate by putting an image in the adorner and adding a tooltip to the image like this;
<Style x:Key="textStyle" TargetType="TextBox">
<Setter Property="Validation.ErrorTemplate">
<Setter.Value>
<ControlTemplate>
<DockPanel LastChildFill="True">
<Border BorderBrush="Orange"
BorderThickness="2"
CornerRadius="4"
SnapsToDevicePixels="True">
<Border.Effect>
<DropShadowEffect BlurRadius="10"
ShadowDepth="0"
Color="Orange" />
</Border.Effect>
<DockPanel>
<Image Width="16"
Height="16"
Margin="-20,0,0,0"
HorizontalAlignment="Left"
VerticalAlignment="Center"
RenderOptions.BitmapScalingMode="HighQuality"
Source="{StaticResource imgError}"
ToolTip="{Binding ElementName=adornedElement,
Path=AdornedElement.(Validation.Errors).CurrentItem.ErrorContent}"
ToolTipService.ShowDuration="30000" />
<AdornedElementPlaceholder Name="adornedElement" />
</DockPanel>
</Border>
</DockPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
With the appropriate implementation of IDataErrorInfo in the ViewModel and setting Textbox in the view accordingly the image and tooltip are shown;
<TextBox Name="txt"
Grid.Column="0"
Height="40"
Background="Aqua"
Style="{StaticResource textStyle}"
Text="{Binding Path=Text,
UpdateSourceTrigger=PropertyChanged,
ValidatesOnDataErrors=True}" />
<TextBlock Grid.Column="1"
Height="40"
Background="AliceBlue"
Text="{Binding ElementName=txt,
Path=(Validation.Errors).CurrentItem.ErrorContent}" />
The above code displays correctly in my previous apps and shows the error in the image tooltip as confirmed by the Textblock.
However, in my current app which is built using Prism I can't get the Image to display. The TextBlock updates correctly and I can set the error to the TextBox tooltip via a style trigger without any issue. The problem is I can't seem to get the image (or anything else) to display in the Adorner. The Image is not shown and border is not changed.
The difference between previous apps and this is that the view is in a Region in a ContentControl and I've used dependency injection to inject the viewmodel into the view constructor and set the DataContext.
I can't figure out why this doesn't work when it did previously. I think I may need to include an AdornerDecorator somewhere but I'm perplexed as to where having tried it in a few places without success. Any ideas how I can ensure the Adorner is shown?
Used an AdornerDecorator to wrap the element containing the texbox and all works fine.

WPF tab control spacing between headers

The default behavior of the WPF Tabcontrol is to place the Tab Headers adjacent to each other, without any empty space in between. What if I wanted to specify a gap between the headers? Do I have to define a control template for this? I'm relatively new to WFP and any help is appreciated.
Thanks
I believe you will need to define a custom control template for the TabItem, maybe even one for the TabControl. Here is an example of a TabItem that uses a spacer for some separation.
<Style
x:Key="SpacedTab"
TargetType="{x:Type TabItem}">
<Setter
Property="Template">
<Setter.Value>
<ControlTemplate
TargetType="{x:Type TabItem}">
<Border
x:Name="Spacer"
Width="Auto"
Height="Auto"
Padding="0 0 5 0"
Margin="0 0 0 0"
BorderBrush="Transparent"
BorderThickness="0">
<Border
x:Name="Border"
MinWidth="150"
Width="Auto"
Height="30"
Background="Gray"
BorderBrush="DarkGray"
BorderThickness="0,0,0,0"
CornerRadius="6,6,0,0"
Cursor="Hand"
VerticalAlignment="Bottom">
<ContentPresenter
x:Name="ContentSite"
TextElement.FontSize="10pt"
TextElement.FontFamily="Arial"
TextElement.Foreground="Black"
VerticalAlignment="Center"
HorizontalAlignment="Center"
ContentSource="Header"
Margin="8,3,8,3"
Width="Auto"
Height="Auto" />
</Border>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Hopefully that is a nudge in the right direction; you will still need to add that as a style resource and reference it from your TabControl -> TabItem.
It is easy to add space by doing it in the designer. Select the Tab you want to move, by starting with the rightmost tab. Then hold ctrl and use the right arrow key to move the tab to the right. Do the same with the rest of the tabs. Then you can manually adjust the margin in the xaml code.

Can I have two ContentPresenter pointing to in single Content or ContentSource in the ContentTemplate?

I have created a NavigationPane just like Outlook 2007. In Outlook, when the Pane is collapsed and the side bar is clicked, it used to popup the Selected NavigationItem content. I mimicked the same behavior using contentpresenter in the ControlTemplete (one for the TabControl's SelectItemHost and another for the Popup). But the problem is when the Popup is open up, the NavigationPane selected content when away and it appears when we switch back to the same navigation item from another navigation item. I am using TabControl and TabItem as NavigationPane and NavigationPaneItem.
I am pointing the "SelectedContent" as the ContentSource for the two ContentPresenter
You can define two ContentPresenter objects within a control template and point them both at the same content source if you like:
<ControlTemplate x:Key="WeirdButton" TargetType="Button">
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Border Grid.RowSpan="2" Background="{TemplateBinding Background}" />
<ContentPresenter ContentSource="Content"/>
<ContentPresenter ContentSource="Content" Grid.Row="1"/>
</Grid>
</ControlTemplate>
This has some rather unusual side effects, however. Because you can't put the same visual into two places in the visual tree, this template will only work as expected if the child content of the button is NOT a visual (or derived from Visual). If the content is some other type of data and the visuals are generated by a data template everything works as expected. Setting the content of the button to a string (<Button Content="OK"/>) works also.
Note that this same effect could be achieved with a visual brush:
<ControlTemplate x:Key="WeirdButton" TargetType="Button">
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Border Grid.RowSpan="2" Background="{TemplateBinding Background}" />
<ContentPresenter x:Name="presenter" ContentSource="Content"/>
<Rectangle Grid.Row="1"
Width="{Binding ActualWidth, ElementName=presenter}" Height="{Binding ActualHeight, ElementName=presenter}">
<Rectangle.Fill>
<VisualBrush Visual="{Binding ElementName=presenter}" Stretch="None" AlignmentX="Left"/>
</Rectangle.Fill>
</Rectangle>
</Grid>
</ControlTemplate>
The drawback of this approach is that you can't interact with controls in the visual brush. So if you want the buttons, textboxes, and other controls on the duplicate to also be interactive, you will have to follow an approach closer to the first template.

Resources