如何更新 WPF 中工具栏的 ControlTemplate 中的标签?
我有一个由 ToolBarTray 和 ToolBar 组成的 ControlTemplate。 在我的工具栏中,我有几个按钮和一个标签。 我希望能够使用“1 of 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" .. />
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" .. />
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
ControlTemplate 的目的是定义控件的外观。 对于您的问题,我不确定控件模板是否是正确的解决方案。
正如 Bryan 还指出的那样,您应该将 Label 的 Content 属性绑定到控件中已存在的属性。 这应该通过TemplateBinding来完成。
然后,属性 MyStatusLabelProperty 必须存在于您的控件类中。
通常,您会创建自己的UserControl,它具有正确类型(对象或字符串)的依赖属性,名为 MyStatusLabelProperty。
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.
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.
我会将标签设置为控件的“内容”属性,例如
然后您可以使用顶级对象的内容属性设置标签的文本。
I would set the label to the "Content" attribute of your control e.g.
Then you can set your label's text with your top level object's Content attribute.
我将创建一个实现 INotifyPropertyChanged 接口的视图模型,并使用 DataTemplate 来显示它,如下所示:
使用绑定,您不必显式更新标签的内容。 您所要做的就是在视图模型中设置属性的值并引发适当的 PropertyChanged 事件,这会导致标签更新其内容。
I would create a view model which implements INotifyPropertyChanged interface and use DataTemplate to display it using something like this:
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.