我有一个由ToolBarTray和ToolBar组成的ControlTemplate。在我的工具栏中,我有几个按钮,然后是一个标签。我希望能够使用类似“1 of 10”的内容更新工具栏中的标签。

我的第一个想法是以编程方式找到标签并设置它,但我读到这应该用Triggers来完成。我很难理解如何实现这一目标。有什么想法吗?

   <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"  .. />
有帮助吗?

解决方案

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

正如Bryan所指出的,您应该将Label的 Content 属性绑定到控件中已存在的属性。这应该通过 TemplateBinding 完成。

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

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

其他提示

我会将标签设置为“内容”。控制的属性,例如。

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

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

我会创建一个实现INotifyPropertyChanged接口的视图模型,并使用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>

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top