如何设置标签的文本 [英] How can I set the text of a label

查看:18
本文介绍了如何设置标签的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个想要放入 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.

Here's the simplified 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆