Growing UserControl Size with Style Trigger? - wpf

I would like to cause a custom UserControl to grow by a multiplier when an "IsSelected" DP is set to true. My current XAML looks like this:
<ctrl:MyBaseControl x:Class="MyDemo.Controls.MyCustomControl"
...>
<ctrl:MyBaseControl.Resources>
<Style TargetType="{x:Type ctrl:MyCustomControl}">
<Setter Property="BorderBrush" Value="White" />
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="BorderThickness" Value="2" />
<Setter Property="Width" Value="340" />
<Setter Property="Height" Value="260" />
</Trigger>
</Style.Triggers>
</Style>
</ctrl:MyBaseControl.Resources>
<Border>
<StackPanel>
...
</StackPanel>
</Border>
In the above sample, "MyBaseControl" extends UserControl, and defines the IsSelected DP.
This code just plain isn't working at the moment, which is one of my issues. The other is that I would like to grow the Width/Height for a certain amount (for example: 0.10) instead of setting it to a hard number. This way I can set the size when I define the control at the source.
Thanks for any help!
ADDITION CODE:
MyBaseControl Code:
public abstract class MyBaseControl: UserControl
{
public static readonly DependencyProperty IsSelectedProperty =
DependencyProperty.Register(
"IsSelected",
typeof(Boolean),
typeof(MyBaseControl),
new PropertyMetadata(null));
public MyBaseControl() : base() { }
#region Properties
public Boolean IsSelected
{
get { return (Boolean)GetValue(IsSelectedProperty); }
set { SetValue(IsSelectedProperty, value); }
}
#endregion Properties
}
MyCustomControl Code:
public partial class MyCustomControl: MyBaseControl
{
public static readonly DependencyProperty IconProperty =
DependencyProperty.Register(
"Icon",
typeof(ImageSource),
typeof(MyCustomControl),
new PropertyMetadata(null));
public static readonly DependencyProperty BlurbProperty =
DependencyProperty.Register(
"Blurb",
typeof(String),
typeof(MyCustomControl),
new PropertyMetadata(null));
public MyCustomControl()
{
InitializeComponent();
}
#region Properties
public ImageSource Icon
{
get { return (ImageSource)GetValue(IconProperty); }
set { SetValue(IconProperty, value); }
}
public String Blurb
{
get { return (String)GetValue(BlurbProperty); }
set { SetValue(BlurbProperty, value); }
}
#endregion Properties
}
Example of working trigger on internal elements:
<Style TargetType="{x:Type Border}">
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ctrl:MyCustomControl}}, Path=IsSelected}" Value="True">
<Setter Property="BorderThickness" Value="5" />
</DataTrigger>
</Style.Triggers>
</Style>

Try this
<ctrl:MyBaseControl.Resources>
<Style TargetType="{x:Type ctrl:MyCustomControl}">
<Setter Property="BorderBrush" Value="White" />
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="BorderThickness" Value="2" />
<Setter Property="RenderTransform" >
<Setter.Value>
<ScaleTransform ScaleX="1.1" ScaleY="1.1" />
</Setter.Value>
</Setter>
<Setter Property="RenderTransformOrigin" Value="0.5, 0.5"/>
</Trigger>
</Style.Triggers>
</Style>
</ctrl:MyBaseControl.Resources>

Related

Target type does not match type of element, control will not show in designer

We've got a few Custom Controls with their own styles, templates. Basically something like that: (I'll post the full styles/templates at the end)
public class CustomBtn : Button
{
public propdp DependencyProp1...
public propdp DependencyProp2...
...
}
<Style x:Key="XStyle.CustomBtnStyle" TargetType="{x:Type cc:CustomBtn}">
...
<Setter Property="Template" Value="{StaticResource XControlTemplate.CustomButton}"/>
<ControlTemplate x:Key="XControlTemplate.CustomButton" TargetType="{x:Type cc:CustomBtn}">
...
Some of the properties defined are used in the templates, some in the styles proper.
The issue we've been facing is that those controls will not display in the designer (most of the time), instead showing as if they're broken. With the error being "Target type does not match type of element"
There are no issues at run time
There are no private/none default constructors in any of our custom controls.
I've got an updated DesignTimeResources
There's a strange discrepancy I've noticed in the error, between the numbers following the control name
There are a bunch of similar questions out there, but the answers attached did not work/apply for me.
Although sometimes after tinkering with the styles/classes the designer will display them in a very basic form.. until it doesn't again.
Styles, classes (apologies for the wall of code):
public class ButtonIcon : Button
{
// VisualTheme determines color theme
public EVisualTheme VisualTheme
{
get { return (EVisualTheme)GetValue(VisualThemeProperty); }
set { SetValue(VisualThemeProperty, value); }
}
// Using a DependencyProperty as the backing store for VisualTheme. This enables animation, styling, binding, etc...
public static readonly DependencyProperty VisualThemeProperty =
DependencyProperty.Register("VisualTheme", typeof(EVisualTheme), typeof(ButtonIcon), new PropertyMetadata(EVisualTheme.Common));
// Icon for Button
public Geometry IconGeometry
{
get { return (Geometry)GetValue(IconGeometryProperty); }
set { SetValue(IconGeometryProperty, value); }
}
// Using a DependencyProperty as the backing store for IconGeometry. This enables animation, styling, binding, etc...
public static readonly DependencyProperty IconGeometryProperty =
DependencyProperty.Register("IconGeometry", typeof(Geometry), typeof(ButtonIcon), new PropertyMetadata(new PathGeometry()));
public double IconSize
{
get { return (double)GetValue(IconSizeProperty); }
set { SetValue(IconSizeProperty, value); }
}
// Using a DependencyProperty as the backing store for IconSize. This enables animation, styling, binding, etc...
public static readonly DependencyProperty IconSizeProperty =
DependencyProperty.Register("IconSize", typeof(double), typeof(ButtonIcon), new PropertyMetadata(40.0));
// Text to be set on Button
public object Caption
{
get { return (object)GetValue(CaptionProperty); }
set { SetValue(CaptionProperty, value); }
}
// Using a DependencyProperty as the backing store for Caption. This enables animation, styling, binding, etc...
public static readonly DependencyProperty CaptionProperty =
DependencyProperty.Register("Caption", typeof(object), typeof(ButtonIcon), new PropertyMetadata(null));
// For running Animations from 0 to 1 in order to change Animation property during Runtime (see examples of usage in code)
public double GradientPercentage
{
get { return (double)GetValue(GradientPercentageProperty); }
set { SetValue(GradientPercentageProperty, value); }
}
// Using a DependencyProperty as the backing store for GradientPercentage. This enables animation, styling, binding, etc...
public static readonly DependencyProperty GradientPercentageProperty =
DependencyProperty.Register("GradientPercentage", typeof(double), typeof(ButtonIcon), new PropertyMetadata(0.0));
public Point IconRenderTransformOrigin
{
get { return (Point)GetValue(IconRenderTransformOriginProperty); }
set { SetValue(IconRenderTransformOriginProperty, value); }
}
// Using a DependencyProperty as the backing store for IconRenderTransformOrigin. This enables animation, styling, binding, etc...
public static readonly DependencyProperty IconRenderTransformOriginProperty =
DependencyProperty.Register("IconRenderTransformOrigin", typeof(Point), typeof(ButtonIcon), new PropertyMetadata(new Point(0.5, 0.5)));
// Angle at which to rotate Icon
public double IconRotationAngle
{
get { return (double)GetValue(IconRotationAngleProperty); }
set { SetValue(IconRotationAngleProperty, value); }
}
// Using a DependencyProperty as the backing store for IconRotationAngle. This enables animation, styling, binding, etc...
public static readonly DependencyProperty IconRotationAngleProperty =
DependencyProperty.Register("IconRotationAngle", typeof(double), typeof(ButtonIcon), new PropertyMetadata(0.0));
// CenterX for Icon rotation
public double IconRotationCenterX
{
get { return (double)GetValue(IconRotationCenterXProperty); }
set { SetValue(IconRotationCenterXProperty, value); }
}
// Using a DependencyProperty as the backing store for IconRotationCenterX. This enables animation, styling, binding, etc...
public static readonly DependencyProperty IconRotationCenterXProperty =
DependencyProperty.Register("IconRotationCenterX", typeof(double), typeof(ButtonIcon), new PropertyMetadata(0.0));
// CenterY for Icon rotation
public double IconRotationCenterY
{
get { return (double)GetValue(IconRotationCenterYProperty); }
set { SetValue(IconRotationCenterYProperty, value); }
}
// Using a DependencyProperty as the backing store for IconRotationCenterY. This enables animation, styling, binding, etc...
public static readonly DependencyProperty IconRotationCenterYProperty =
DependencyProperty.Register("IconRotationCenterY", typeof(double), typeof(ButtonIcon), new PropertyMetadata(0.0));
// ScaleX of Icon
public double IconScaleX
{
get { return (double)GetValue(IconScaleXProperty); }
set { SetValue(IconScaleXProperty, value); }
}
// Using a DependencyProperty as the backing store for IconScaleX. This enables animation, styling, binding, etc...
public static readonly DependencyProperty IconScaleXProperty =
DependencyProperty.Register("IconScaleX", typeof(double), typeof(ButtonIcon), new PropertyMetadata(1.0));
// ScaleY of Icon
public double IconScaleY
{
get { return (double)GetValue(IconScaleYProperty); }
set { SetValue(IconScaleYProperty, value); }
}
// Using a DependencyProperty as the backing store for IconScaleY. This enables animation, styling, binding, etc...
public static readonly DependencyProperty IconScaleYProperty =
DependencyProperty.Register("IconScaleY", typeof(double), typeof(ButtonIcon), new PropertyMetadata(1.0));
// CenterX for Icon scale
public double IconScaleCenterX
{
get { return (double)GetValue(IconScaleCenterXProperty); }
set { SetValue(IconScaleCenterXProperty, value); }
}
// Using a DependencyProperty as the backing store for IconScaleCenterX. This enables animation, styling, binding, etc...
public static readonly DependencyProperty IconScaleCenterXProperty =
DependencyProperty.Register("IconScaleCenterX", typeof(double), typeof(ButtonIcon), new PropertyMetadata(0.0));
// CenterY for Icon scale
public double IconScaleCenterY
{
get { return (double)GetValue(IconScaleCenterYProperty); }
set { SetValue(IconScaleCenterYProperty, value); }
}
// Using a DependencyProperty as the backing store for IconScaleCenterY. This enables animation, styling, binding, etc...
public static readonly DependencyProperty IconScaleCenterYProperty =
DependencyProperty.Register("IconScaleCenterY", typeof(double), typeof(ButtonIcon), new PropertyMetadata(0.0));
public double IconTranslateX
{
get { return (double)GetValue(IconTranslateXProperty); }
set { SetValue(IconTranslateXProperty, value); }
}
// Using a DependencyProperty as the backing store for IconTranslateX. This enables animation, styling, binding, etc...
public static readonly DependencyProperty IconTranslateXProperty =
DependencyProperty.Register("IconTranslateX", typeof(double), typeof(ButtonIcon), new PropertyMetadata(0.0));
public double IconTranslateY
{
get { return (double)GetValue(IconTranslateYProperty); }
set { SetValue(IconTranslateYProperty, value); }
}
// Using a DependencyProperty as the backing store for IconTranslateY. This enables animation, styling, binding, etc...
public static readonly DependencyProperty IconTranslateYProperty =
DependencyProperty.Register("IconTranslateY", typeof(double), typeof(ButtonIcon), new PropertyMetadata(0.0));
}
<Style x:Key="XStyle.ButtonIcon.Action" TargetType="{x:Type cc:ButtonIcon}">
<Setter Property="FocusVisualStyle" Value="{x:Null}"/>
<Setter Property="Height" Value="{StaticResource XDouble.Height.Button.Default}"/>
<Setter Property="Template" Value="{StaticResource XControlTemplate.ButtonIcon.Action}"/>
<Setter Property="IconSize" Value="30"/>
<Setter Property="GradientPercentage" Value="0.0"/>
<Setter Property="IconGeometry" Value="{x:Null}"/>
<Setter Property="FontSize" Value="{StaticResource XDouble.FontSize.Header3}"/>
<Setter Property="Foreground" Value="{Binding VisualTheme, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type cc:ButtonIcon}}, Converter={rconv:VisualThemeToForegroundConverter}}"/>
<Setter Property="BorderBrush" Value="{StaticResource XBrush.Frame}"/>
<Setter Property="BorderThickness" Value="0"/>
<Style.Triggers>
<Trigger Property="VisualTheme" Value="ListItem">
<Setter Property="BorderThickness" Value="{StaticResource XThickness.Border.Frame}"/>
</Trigger>
<Trigger Property="VisualTheme" Value="DarkOnLight">
<Setter Property="BorderThickness" Value="{StaticResource XThickness.Border.Frame}"/>
</Trigger>
</Style.Triggers>
</Style>
<ControlTemplate x:Key="XControlTemplate.ButtonIcon.Action" TargetType="{x:Type cc:ButtonIcon}">
<Border
x:Name="OuterBorder"
Width="{TemplateBinding Width}"
Height="{TemplateBinding Height}"
BorderBrush="{TemplateBinding BorderBrush}"
Padding="10,0"
BorderThickness="{TemplateBinding BorderThickness}"
CornerRadius="{StaticResource XCornerRadius.Frame}">
<Border.Background>
<MultiBinding Converter="{rconv:PercentageToBrushConverter}">
<Binding Path="GradientPercentage" RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type cc:ButtonIcon}}" />
<Binding Path="VisualTheme" RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type cc:ButtonIcon}}" />
</MultiBinding>
</Border.Background>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition x:Name="IconColumn" Width="Auto" />
<ColumnDefinition x:Name="SpacerColumn" Width="10" />
<ColumnDefinition x:Name="CaptionColumn" Width="*" />
</Grid.ColumnDefinitions>
<Border
x:Name="IconBorder"
Width="{TemplateBinding IconSize}"
Height="{TemplateBinding IconSize}"
HorizontalAlignment="Center"
VerticalAlignment="Center">
<Path
x:Name="IconPart"
Data="{TemplateBinding IconGeometry}"
Fill="{TemplateBinding Foreground}"
RenderTransformOrigin="{Binding Path=IconRenderTransformOrigin, RelativeSource={RelativeSource TemplatedParent}}"
Stretch="Uniform">
<Path.RenderTransform>
<TransformGroup>
<ScaleTransform
CenterX="{Binding Path=IconScaleCenterX, RelativeSource={RelativeSource TemplatedParent}}"
CenterY="{Binding Path=IconScaleCenterY, RelativeSource={RelativeSource TemplatedParent}}"
ScaleX="{Binding Path=IconScaleX, RelativeSource={RelativeSource TemplatedParent}}"
ScaleY="{Binding Path=IconScaleY, RelativeSource={RelativeSource TemplatedParent}}" />
<RotateTransform
Angle="{Binding Path=IconRotationAngle, RelativeSource={RelativeSource TemplatedParent}}"
CenterX="{Binding Path=IconRotationCenterX, RelativeSource={RelativeSource TemplatedParent}}"
CenterY="{Binding Path=IconRotationCenterY, RelativeSource={RelativeSource TemplatedParent}}" />
</TransformGroup>
</Path.RenderTransform>
</Path>
</Border>
<ContentPresenter
x:Name="ContentPresenter"
Grid.Column="2"
HorizontalAlignment="Left"
VerticalAlignment="Center"
Content="{TemplateBinding Caption}"
Focusable="False"
SnapsToDevicePixels="True"
TextBlock.FontSize="{TemplateBinding FontSize}"
TextBlock.Foreground="{TemplateBinding Foreground}"/>
</Grid>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="Opacity" Value="{StaticResource XDouble.Opacity.Disabled}" />
</Trigger>
<Trigger Property="IsMouseOver" Value="True">
<Trigger.EnterActions>
<BeginStoryboard x:Name="StoryBoardMouseEnter" Storyboard="{StaticResource XStoryboard.DoubleAnimation.GradientPercentage.RunUp}" />
</Trigger.EnterActions>
<Trigger.ExitActions>
<BeginStoryboard x:Name="StoryBoardMouseLeave" Storyboard="{StaticResource XStoryboard.DoubleAnimation.GradientPercentage.RunDown}" />
</Trigger.ExitActions>
</Trigger>
<Trigger Property="Caption" Value="{x:Null}">
<Setter TargetName="ContentPresenter" Property="Visibility" Value="Collapsed" />
<Setter TargetName="IconColumn" Property="Width" Value="*" />
<Setter TargetName="SpacerColumn" Property="Width" Value="0" />
<Setter TargetName="CaptionColumn" Property="Width" Value="0" />
</Trigger>
<Trigger Property="Caption" Value="">
<Setter TargetName="ContentPresenter" Property="Visibility" Value="Collapsed" />
<Setter TargetName="IconColumn" Property="Width" Value="*" />
<Setter TargetName="SpacerColumn" Property="Width" Value="0" />
<Setter TargetName="CaptionColumn" Property="Width" Value="0" />
</Trigger>
<Trigger Property="IconGeometry" Value="{x:Null}">
<Setter TargetName="IconPart" Property="Visibility" Value="Collapsed"/>
<Setter TargetName="SpacerColumn" Property="Width" Value="0"/>
<Setter TargetName="IconColumn" Property="Width" Value="0"/>
<Setter TargetName="ContentPresenter" Property="Grid.Column" Value="0"/>
<Setter TargetName="ContentPresenter" Property="Grid.ColumnSpan" Value="3"/>
<Setter TargetName="ContentPresenter" Property="HorizontalAlignment" Value="Center"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>

WPF. Check and disable a checkbox if another checkbox is checked

I have 2 checkboxes.
when one is checked, the other one must be checked and disabled.
The code I have so far is like so
Xaml
<CheckBox x:Name="chkSABranches" Content="Apply to all branches" IsChecked="{Binding IsSABranches,ElementName=pgPageTemplate}" Grid.Row="0" Grid.Column="2"/>
In xaml.cs:
public static DependencyProperty IsSABranchesProperty = DependencyProperty.Register("IsSABranches", typeof(bool), typeof(pgAccounts), new PropertyMetadata(false));
public static DependencyProperty IsSAWarehousesProperty = DependencyProperty.Register("IsSAWarehouses", typeof(bool), typeof(pgAccounts), new PropertyMetadata(false));
public Boolean IsSABranches
{
get
{
return (bool)GetValue(IsSABranchesProperty);
}
set
{
SetValue(IsSABranchesProperty, value);
NotifyPropertyChanged("IsSABranches");
NotifyPropertyChanged("IsSAWarehouses");
}
}
public Boolean IsSAWarehouses
{
get
{
return (bool)GetValue(IsSAWarehousesProperty) || (bool)GetValue(IsSABranchesProperty);
}
set
{
SetValue(IsSAWarehousesProperty, value);
NotifyPropertyChanged("IsSAWarehouses");
}
}
This doesn't seem to work.. Could anyone please provide some guidance. thanks
Here how to do it entirely in Xaml using DataTrigers
<StackPanel>
<CheckBox x:Name="CheckBox1"></CheckBox>
<CheckBox >
<CheckBox.Style>
<Style TargetType="CheckBox">
<Setter Property="IsEnabled" Value="True"></Setter>
<Setter Property="IsChecked" Value="False"></Setter>
<Style.Triggers>
<DataTrigger Binding="{Binding IsChecked,ElementName=CheckBox1}" Value="True">
<Setter Property="IsChecked" Value="True"/>
<Setter Property="IsEnabled" Value="False"/>
</DataTrigger>
</Style.Triggers>
</Style>
</CheckBox.Style>
</CheckBox>
</StackPanel>

How can I fall back to a high contrast color in WPF?

I have some XAML which sets the foreground color directly:
<Style x:Key="HomeHeaderText" TargetType="TextBlock">
<Setter Property="FontSize" Value="24" />
<Setter Property="FontFamily" Value="Segoe Light UI" />
<Setter Property="Foreground" Value="#FF606060" />
<Setter Property="Margin" Value="0,50,0,30" />
</Style>
I would like to detect in the style whether or not the system is in high contrast mode, and fall back to one of the system colors if so.
How can one do this using styles?
I tried setting this using a trigger, but this results in XamlParseException at runtime:
<Style x:Key="HomeHeaderText" TargetType="TextBlock">
<Setter Property="FontSize" Value="24" />
<Setter Property="FontFamily" Value="Segoe Light UI" />
<Setter Property="Foreground" Value="#FF606060" />
<Setter Property="Margin" Value="0,50,0,30" />
<Style.Triggers>
<DataTrigger Binding="{x:Static SystemParameters.HighContrast}" Value="True">
<Setter Property="Foreground"
Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}" />
</DataTrigger>
</Style.Triggers>
</Style>
The problem with your attempt is that DataTrigger.Binding wants a binding, but you gave it a direct value. You can solve this by setting the binding source:
{Binding Source={x:Static SystemParameters.HighContrast}}
However, this will not be dynamic -- the style would not update if someone toggles high-contrast while the application is running. Ideally it would be nice to have something like this:
{Binding Source={x:Static SystemParameters}, Path=HighContrast}
But unfortunately that isn't possible since it's a static property. So, binding to the HighContrastKey resource is the better option. Instead of using Tag, you could bind this to an attached property. Come to think of it, Microsoft probably should have implemented SystemParameters as attached properties in the first place. Try something like this:
public static class SystemParameterProperties {
public static readonly DependencyProperty HighContrastProperty =
DependencyProperty.RegisterAttached("HighContrast", typeof(bool), typeof(SystemParameterProperties),
new FrameworkPropertyMetadata() {Inherits = true});
public static bool GetHighContrast(DependencyObject obj) {
return (bool)obj.GetValue(HighContrastProperty);
}
public static void SetHighContrast(DependencyObject obj, bool value) {
obj.SetValue(HighContrastProperty, value);
}
}
I used Inherits = true on the property so that we can just set it on the outermost container and let it be accessible everywhere, i.e.:
<Window ...
xmlns:attachedProperties="..."
attachedProperties:SystemParameterProperties.HighContrast="{DynamicResource ResourceKey={x:Static Member=SystemParameters.HighContrastKey}}">
...
</Window>
Finally, your trigger would be:
<Trigger Property="attachedProperties:SystemParameterProperties.HighContrast" Value="True">
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}" />
</Trigger>
I'd have solved leveraging an helper:
public class HighContrastHelper
: DependencyObject
{
#region Singleton pattern
private HighContrastHelper()
{
SystemParameters.StaticPropertyChanged += SystemParameters_StaticPropertyChanged;
}
private static HighContrastHelper _instance;
public static HighContrastHelper Instance
{
get
{
if (_instance == null)
_instance = new HighContrastHelper();
return _instance;
}
}
#endregion
void SystemParameters_StaticPropertyChanged(object sender, PropertyChangedEventArgs e)
{
Console.WriteLine(e.PropertyName);
if (e.PropertyName == "HighContrast")
{
HighContrastHelper.Instance.IsHighContrast = SystemParameters.HighContrast;
}
}
#region DP IsHighContrast
public static readonly DependencyProperty IsHighContrastProperty = DependencyProperty.Register(
"IsHighContrast",
typeof(bool),
typeof(HighContrastHelper),
new PropertyMetadata(
false
));
public bool IsHighContrast
{
get { return (bool)GetValue(IsHighContrastProperty); }
private set { SetValue(IsHighContrastProperty, value); }
}
#endregion
}
Afterward, the usage in your code is straightforward:
<Style x:Key="HomeHeaderText" TargetType="TextBlock">
<Setter Property="FontSize" Value="24" />
<Setter Property="FontFamily" Value="Segoe Light UI" />
<Setter Property="Foreground" Value="#FF606060" />
<Setter Property="Margin" Value="0,50,0,30" />
<Style.Triggers>
<DataTrigger Binding="{Binding Path=IsHighContrast, Source={x:Static local:HighContrastHelper.Instance}}" Value="True">
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}" />
</DataTrigger>
</Style.Triggers>
</Style>
Hope it helps.
You can bind it to Tag property of textblock and use that in DataTrigger like below:
<Style x:Key="MyTextBoxStyle" TargetType="{x:Type TextBlock}">
<Setter Property="Tag" Value="{DynamicResource {x:Static SystemParameters.HighContrastKey}}"/>
<Style.Triggers>
<DataTrigger Binding="{Binding Path=Tag , RelativeSource= {x:Static RelativeSource.Self}}" Value="True">
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}" />
</DataTrigger>
</Style.Triggers>
</Style>

Function call within XAML code?

I'd like to set a style on all my TextBox controls that does the following when it receives keyboard focus:
1) Change the background color
2) Call .SelectAll() to highlight all text
I have this so far:
<Style TargetType="TextBox">
<Style.Triggers>
<Trigger Property="IsKeyboardFocusWithin" Value="True">
<Setter Property="Background">
<Setter.Value>
<SolidColorBrush Color="#FFFFD1D9"/>
</Setter.Value>
</Setter>
</Trigger>
</Style.Triggers>
</Style>
Is there a way to also call .SelectAll() ? Thanks.
You can do this using attached behaviours.
Example
public static class TextBoxBehaviour
{
public static bool GetSelectAll(TextBoxBase target)
{
return (bool)target.GetValue(SelectAllAttachedProperty);
}
public static void SetSelectAll(TextBoxBase target, bool value)
{
target.SetValue(SelectAllAttachedProperty, value);
}
public static readonly DependencyProperty SelectAllAttachedProperty = DependencyProperty.RegisterAttached("SelectAll", typeof(bool), typeof(TextBoxBehaviour), new UIPropertyMetadata(false, OnSelectAllAttachedPropertyChanged));
static void OnSelectAllAttachedPropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
((TextBoxBase)o).SelectAll();
}
}
Usage
<Style TargetType="{x:Type TextBox}" xmlns:behaviours="clr-namespace:Controls.Behaviours">
<Style.Triggers>
<Trigger Property="IsKeyboardFocusWithin" Value="True">
<Setter Property="Background" Value="#FFFFD1D9"/>
<Setter Property="behaviours:TextBoxBehaviour.SelectAll" Value="True"/>
</Trigger>
</Style.Triggers>
</Style>
References
Josh Smith on Attached Behaviours
NB: Wasn't able to test the above implementation, in theory though it should just work™.
HTH,

Using custom dependency properties as DataTrigger in WPF

I have a custom dependency property that I would like to use as a data trigger. Here is the code behind:
public static readonly DependencyProperty BioinsulatorScannedProperty =
DependencyProperty.Register(
"BioinsulatorScanned",
typeof(bool),
typeof(DisposablesDisplay),
new FrameworkPropertyMetadata(false));
public bool BioinsulatorScanned
{
get
{
return (bool)GetValue(BioinsulatorScannedProperty);
}
set
{
SetValue(BioinsulatorScannedProperty, value);
}
}
I have created a style and control template. My goal is to change the color of some text when the dependency prop is set to true...
<Style x:Key="TreatEye" TargetType="Label">
<Setter Property="Foreground" Value="#d1d1d1" />
<Setter Property="FontWeight" Value="Bold" />
<Setter Property="FontSize" Value="30" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Label">
<Canvas>
<TextBlock x:Name="bioinsulatorText"
Canvas.Left="21" Canvas.Top="33"
Text="Bioinsulator" />
<TextBlock Canvas.Left="21" Canvas.Top="70"
Text="KXL Kit" />
</Canvas>
<ControlTemplate.Triggers>
<DataTrigger Binding="{Binding BioinsulatorScanned}"
Value="True">
<Setter TargetName="bioinsulatorText"
Property="Foreground" Value="Black" />
</DataTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Despite successfully setting the dependency prop to true programmatically, This trigger condition never fires. This is a real pain to debug!
Thanks in advance.
In this case I am switching the visibility of a button using a datatrigger based on a dependency property FirstLevelProperty.
public static readonly DependencyProperty FirstLevelProperty = DependencyProperty.Register("FirstLevel", typeof(string), typeof(MyWindowClass));
public string FirstLevel
{
get
{
return this.GetValue(FirstLevelProperty).ToString();
}
set
{
this.SetValue(FirstLevelProperty, value);
}
}
You can reference the dependency property FirstLevel(Property) contained (in this case) in a window by using the RelativeSource binding. Also you should set the default setting in the style, that will be overridden by the datatrigger.
<Button.Style>
<Style TargetType="Button">
<Style.Triggers>
<DataTrigger
Binding="{Binding Path=FirstLevel,
RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type Window}}}"
Value="SomeValue">
<Setter Property="Visibility"
Value="Hidden" />
</DataTrigger>
</Style.Triggers>
<Setter Property="Visibility" Value="Visible" />
</Style>
</Button.Style>
It looks like your dependency property is defined inside a DisposableDisplay object that you created. In order for the binding specified to work, an instance of that DisposableDisplay object must be set as the DataContext of the control (label in this case) or any of its ancestors.

Resources