Search code examples
wpftemplatebinding

How do I update a label that is in a ControlTemplate of a Toolbar in WPF?


I have a ControlTemplate that is made up of a ToolBarTray and a ToolBar. In my ToolBar, I have several buttons and then a label. I want to be able to update the label in my toolbar with something like "1 of 10"

My first thought is to programatically find the label and set it, but I'm reading that this should be done with Triggers. I am having a hard time understanding how to accomplish this. Any ideas?

   <Style x:Key="DocViewerToolBarStyle" TargetType="{x:Type ContentControl}">
   <Setter Property="Template">
     <Setter.Value>
           <ControlTemplate TargetType="{x:Type ContentControl}">
              <ToolBarTray... />
              <ToolBar.../>
              <Button../>             
              <Button..>

             <Label x:Name="myStatusLabel"  .. />

Solution

  • The purpose of a ControlTemplate is to define the look of a control. For your problem, I'm not sure if a control template is the right solution.

    As Bryan also points out, you should bind the Content property of the Label to a property that is already present in your control. This should be done via TemplateBinding.

    <Label x:Name="myStatusLabel" Content={TemplateBinding MyStatusLabelProperty} ../>
    

    The property MyStatusLabelProperty then has to exist at your control class. Usually, you would create your own UserControl that has a dependency property of the correct type (either object or string) that is named MyStatusLabelProperty.