代码之家  ›  专栏  ›  技术社区  ›  ScottG

如何更新WPF中工具栏的ControlTemplate中的标签?

  •  1
  • ScottG  · 技术社区  · 17 年前

    我有一个由工具栏托盘和工具栏组成的ControlTemplate。在我的工具栏中,我有几个按钮和一个标签。我希望能够用“1/10”之类的内容更新工具栏中的标签

    我的第一个想法是用程序找到标签并设置它,但我读到这应该用触发器来完成。我很难理解如何做到这一点。有什么想法吗?

       <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"  .. />
    
    3 回复  |  直到 14 年前
        1
  •  1
  •   EFrank    17 年前

    ControlTemplate的目的是定义控件的外观。对于您的问题,我不确定控制模板是否是正确的解决方案。

    正如Bryan所指出的,你应该绑定 所容纳之物 将标签的属性转换为控件中已存在的属性。这应该通过以下方式完成 模板绑定 .

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

    财产 MyStatusLabelProperty 然后必须存在于你的控制类中。 通常,你会创建自己的 对象 其具有名为MyStatusLabelProperty的正确类型(对象或字符串)的依赖属性。

        2
  •  1
  •   Bryan Anderson    17 年前

    我会将标签设置为控件的“Content”属性,例如。

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

    然后,您可以使用顶级对象的Content属性设置标签的文本。

        3
  •  0
  •   pousi    17 年前

    我将创建一个实现INNotifyPropertyInterface的视图模型,并使用DataTemplate来显示它,如下所示:

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

    使用绑定,您不必显式更新标签的内容。您所要做的就是在视图模型中设置属性的值,并引发适当的PropertyEvent,使标签更新其内容。