问题
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.
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>
And the codebehind
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); }
}
In the calling bit I instantiate by 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!
回答1:
Change LabelCaptionDP
to LabelCaptionProperty
.
From Dependency Properties Overview:
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.
来源:https://stackoverflow.com/questions/16403993/how-can-i-set-the-text-of-a-label