如何设置标签文字 [英] How can I set the text of a label
问题描述
我有一个要放入FixedDocument中的用户控件,但是在此之前,我需要更改标签的文本。我想我需要使用依赖项属性。
I've got a usercontrol that I want to put in a FixedDocument, but before I do that I need to change the text of a label. I think I need to use Dependency Properties.
这是简化的XAML。
<UserControl x:Class="PrinterTest.TestControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Grid>
<Label Content="{Binding LabelCaption}"
Height="24" HorizontalContentAlignment="Right" Name="lblCaption"
Width="140" />
</Grid>
</UserControl>
后面的代码
public partial class TestControl : UserControl
{
public TestControl()
{
InitializeComponent();
}
public readonly static DependencyProperty
LabelCaptionDP = DependencyProperty.Register("LabelCaption",
typeof(string),
typeof(TestControl),
new FrameworkPropertyMetadata("no data"));
public string LabelCaption
{
get { return (string)GetValue(LabelCaptionDP); }
set { SetValue(LabelCaptionDP, value); }
}
在调用位中,我用 TestControl myControl实例化= new TestControl();
我做错了什么,因为无法访问控件的新副本中的属性?谢谢!
What am I doing wrong, because I can't access the properties in the new copy of the control? Thank you!
推荐答案
将 LabelCaptionDP
更改为 LabelCaptionProperty
。
来自相关属性概述:
该属性及其支持的命名约定
DependencyProperty字段很重要。字段的名称始终是
属性的名称,后缀Property。有关此约定及其原因的更多
信息,请参见自定义
依赖项属性。
The naming convention of the property and its backing DependencyProperty field is important. The name of the field is always the name of the property, with the suffix Property appended. For more information about this convention and the reasons for it, see Custom Dependency Properties.
Please read about Dependency Property Name Conventions in Custom Dependency Properties.
这篇关于如何设置标签文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!