I have a toggle button in UI and would like to perform some action when it is clicked.
xaml for this button:
<ToggleButton x:Name="markToggle" Click="markToggle_Click" Style="{StaticResource StyleMarkToggle}" >
<ToggleButton.Content>
<StackPanel x:Name="markToggle_Button" Orientation="Horizontal">
<Image x:Name="Icon" Source="{Binding MarkToggleIcon}" Stretch="None" />
<TextBlock x:Name="Counter" TextWrapping="Wrap" Text="{Binding ButtonText}" Margin="6,0,0,0" />
</StackPanel>
</ToggleButton.Content>
</ToggleButton>
When this toggleButton is clicked, I want to change the Foreground color of textblock (name: Counter).
How do I access this textbox element from Storyboard.Target (or TargetName)?
Here is the xaml code for ‘StyleMarkToggle’ style.
(Only visual state ‘checked’ is shown in the below code.)
<VisualState x:Name="Checked">
<Storyboard>
<ColorAnimation Duration="0" To="White" Storyboard.TargetName="{Binding ElementName=Counter}" Storyboard.TargetProperty="(Control.Foreground).(SolidColorBrush.Color)" />
</Storyboard>
It shows this runtime error:
MS.Internal.WrappedException: Cannot resolve TargetName System.Windows.Controls.TextBlock. ---> System.InvalidOperationException: Cannot resolve TargetName System.Windows.Controls.TextBlock.
at MS.Internal.XcpImports.VisualStateManager_GoToStateInternal(Control reference, FrameworkElement root, VisualStateGroup group, VisualState state, Boolean useTransitions, Boolean& refreshInheritanceContext)
at System.Windows.VisualStateManager.RetryGoToStateAfterRefreshingInheritanceContext(Control control, FrameworkElement templateRoot, VisualStateGroup group, VisualState state, Boolean useTransitions)
at System.Windows.VisualStateManager.GoToState(Control control, String stateName, Boolean useTransitions)
at System.Windows.Controls.Primitives.ToggleButton.ChangeVisualState(Boolean useTransitions)
at System.Windows.Controls.Primitives.ToggleButton.OnApplyTemplate()
at System.Windows.FrameworkElement.OnApplyTemplate(IntPtr nativeTarget)
Instead of using a
Storyboard, you could just bind theForegroundproperty of theTextBlockelement to theIsCheckedproperty of theToggleButtonelement and use aConverterto convert frombooltoSolidColorBrush.Here is the modified XAML:
And the code for the converter: