Question

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"  .. />
Was it helpful?

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.

OTHER TIPS

I would set the label to the "Content" attribute of your control e.g.

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

Then you can set your label's text with your top level object's Content attribute.

I would create a view model which implements INotifyPropertyChanged interface and use DataTemplate to display it using something like this:

<DataTemplate DataType={x:Type viewmodel:MyToolBarViewModel}>
    <Label Content={Binding CurrentPage} />
    <Label Content={Binding TotalPages} ContentStringFormat="{}of {0}" />
</DataTemplate>

<ToolBar>
    <ContentPresenter Content={Binding <PathtoViewModel>} />
</ToolBar>

With using bindings you don't have to explicitly update label's content. All you have to do is set property's value in view model and raise proper PropertyChanged event which causes the label to update its content.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top