【问题标题】:How can I set the text of a label如何设置标签的文本
【发布时间】:2013-05-06 17:30:58
【问题描述】:

我有一个想要放入 FixedDocument 的用户控件,但在此之前我需要更改标签的文本。我想我需要使用依赖属性。

这是简化的 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(); 实例化

我做错了什么,因为我无法访问新控件副本中的属性?谢谢!

【问题讨论】:

  • 感谢 LPL - 进行了这些命名约定更改。在我的调用代码中,我尝试了 UserControl TestControl = new TestControl(); (TestControl)TestControl.LabelCaptionProperty = "测试";但我得到一个 System.Windows.Controls.UserControl 不包含 LabelCaptionProperty 的定义,我在 Intellisense 中看不到任何内容。我在做什么蠢事?

标签: wpf user-controls dependency-properties


【解决方案1】:

LabelCaptionDP 更改为LabelCaptionProperty

来自Dependency Properties Overview

属性的命名约定及其支持 DependencyProperty 字段很重要。字段名称始终为 属性的名称,附加后缀 Property。更多 有关此约定及其原因的信息,请参阅自定义 依赖属性。

请阅读Custom Dependency Properties中的依赖属性名称约定

【讨论】:

  • 感谢 LPL - 进行了这些命名约定更改。在我的调用代码中,我尝试了 UserControl TestControl = new TestControl(); (TestControl)TestControl.LabelCaptionProperty = "测试";但我得到一个 System.Windows.Controls.UserControl 不包含 LabelCaptionProperty 的定义,我在 Intellisense 中看不到任何内容。我在做什么蠢事?
  • 为此使用 Back CLR 属性:((TestControl)TestControl).LabelCaption = "Test";
  • 谢谢。语法排序!这是我第一篇探讨 WPF 乐趣的文章。敢说,一旦我的教科书到了,我可能会掌握它的窍门。现在我所要做的就是与我的网格轮廓搏斗。再次感谢您解除了我的挫败感。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多