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
ToggleTrueText
ifIsToggled
is true; or displayToggleFalseText
ifIsToggled
is false. - When
IsToggled
changes during runtime, the text automatically changes to eitherToggleTrueText
orToggleFalseText
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.
Grid
and itsTextBlock
are in theUserControl
XAML, then you should have a view model private to theUserControl
that can be used as the data context for theTextBlock
. Either that or just set the property explicitly asTheTextBlock.Text
in theOnToggleStateChanged()
method. Please improve the question so it's clear what you're doing and what specifically you need help with. - Peter Duniho