DaveS
DaveS

Reputation: 915

Creating a self-updating Textblock user control in WPF

I'm trying to create a re-usable textblock user control in WPF. The basic idea is as follows:

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.

Upvotes: 0

Views: 352

Answers (2)

A. S. Mahadik
A. S. Mahadik

Reputation: 625

You can used trigger for this Please check below code

<TextBlock x:Name="TheTextBlock">
    <TextBlock.Style>
        <Style TargetType="{x:Type TextBlock}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsToggled}" Value="True">
                    <Setter Property="Text" Value="{Binding ToggleTrueText}"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding IsToggled}" Value="False">
                    <Setter Property="Text" Value="{Binding ToggleFalseText}"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </TextBlock.Style>
</TextBlock> 

Upvotes: 0

mm8
mm8

Reputation: 169400

Try this:

private static void OnToggleStateChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    TagToggle ctrl = d as TagToggle;
    if (ctrl != null)
    {
        TheTextBlock.Text = ctrl.IsToggled ? ToggleTrueText. : ToggleFalseText;
    }
}

If you want to bind the Text property of the TextBlock you need to make sure that you are binding to properties of the UserControl. You could do this by setting the DataContext property of the TextBlock:

<TextBlock x:Name="TheTextBlock" DataContext="{Binding RelativeSource={RelativeSource AncestorType=UserControl}}">
    <TextBlock.Style>
        <Style TargetType="{x:Type TextBlock}">
            <Setter Property="Text" Value="{Binding ToggleTrueText}" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsToggled}" Value="False">
                    <Setter Property="Text" Value="{Binding ToggleFalseText}"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </TextBlock.Style>
</TextBlock>

Upvotes: 1

Related Questions