2013-05-06 87 views
0

我有一个用户控件,我想把它放在一个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();

实例我是什么做错了,因为我不能在控制的新副本访问属性?谢谢!

+0

谢谢LPL - 对命名约定进行了修改。 在我的调用代码中,我试过 UserControl TestControl = new TestControl(); (TestControl)TestControl.LabelCaptionProperty =“Test”; 但我得到一个System.Windows.Controls.UserControl不包含LabelCaptionProperty的定义,我无法在Intellisense中看到任何东西。我在做什么愚蠢的事情? – 2013-05-06 20:02:13

回答

2

变化LabelCaptionDP变为LabelCaptionProperty

Dependency Properties Overview

财产,其支持 的DependencyProperty字段的命名规则是很重要的。该字段的名称始终为 属性的名称,后缀为Property。有关此惯例的更多信息 以及其原因,请参阅自定义 依赖属性。

请阅读有关依赖项属性名称约定Custom Dependency Properties

+0

感谢LPL - 制定了这些命名约定的更改。在我的调用代码中,我尝试了UserControl TestControl = new TestControl(); (TestControl)TestControl.LabelCaptionProperty =“Test”;但是我得到一个System.Windows.Controls.UserControl不包含LabelCaptionProperty的定义,我在Intellisense中看不到任何东西。我在做什么愚蠢的事情? – 2013-05-06 20:05:27

+0

为此使用后端CLR属性:'((TestControl)TestControl).LabelCaption =“Test”;'。 – LPL 2013-05-06 22:12:23

+0

谢谢。语法排序!这是我写入WPF乐趣的第一篇文章。我敢说,一旦我的课本到达,我可能会得到它的诀窍。 现在我所要做的就是与我的网格轮廓搏斗。再次感谢我解除了我的沮丧。 – 2013-05-06 22:39:19

相关问题