I'm trying to create a re-usable textblock user control in WPF. The basic idea is as follows:
- User does not directly specify the content of the textblock
- There are three dependancy properties in my user control called
IsToggled,ToggleTrueText, andToggleFalseText. - The control will display
ToggleTrueTextifIsToggledis true; or displayToggleFalseTextifIsToggledis false. - When
IsToggledchanges during runtime, the text automatically changes to eitherToggleTrueTextorToggleFalseText
I started by adding a PropertyChangedCallback to the IsToggled DP:
Code-behind of the UserControl:
public static readonly DependencyProperty IsToggledProperty =
DependencyProperty.Register("IsToggled", typeof(bool),
typeof(TagToggle), new PropertyMetadata(new
PropertyChangedCallback(OnToggleStateChanged)));
public bool IsToggled
{
get { return (bool)GetValue(IsToggledProperty); }
set { SetValue(IsToggledProperty, value); }
}
//ToggleTrueText and ToggleFalseText are declared similarly to IsToggled
...
private static void OnToggleStateChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
...
}
Xaml of the user control:
<Grid x:Name="LayoutRoot">
<TextBlock x:Name="TheTextBlock" Text="{Binding WhatDoIBindTo}"/>
</Grid>
However, I'm not sure what would be the best way to ensure that TheTextBlock updates its text whenever IsToggled changes during runtime.
Gridand itsTextBlockare in theUserControlXAML, then you should have a view model private to theUserControlthat can be used as the data context for theTextBlock. Either that or just set the property explicitly asTheTextBlock.Textin theOnToggleStateChanged()method. Please improve the question so it's clear what you're doing and what specifically you need help with. - Peter Duniho