将User Control Dependency Property值设置为标签控件

时间:2012-04-03 04:34:23

标签: wpf user-controls dependency-properties

我正在创建一个用户控件,在控件内部我有一个Label Control。 (例如:电子邮件控件,包含标签和文本框)。

在电子邮件地址控件中,我定义了一个Title属性,当用户更改属性值时,我想将字符串值设置为Label。

bellow是XAML和代码:

XAML:

<UserControl x:Class="SIMind.ClinicManagement.GUI.Controls.CommonControl.EmailAddressCtrl"
             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" Height="32" MinHeight="32" MaxHeight="32" Width="386" MinWidth="386">
    <Grid>
      <Grid.RowDefinitions>
         <RowDefinition />
      </Grid.RowDefinitions>
      <StackPanel HorizontalAlignment="Stretch" Margin="0" Name="stackPanel1" VerticalAlignment="Stretch" Orientation="Horizontal">
         <Label Content="Email :" Height="24" HorizontalContentAlignment="Right" Name="lblEmailCaption" Tag="PhoneType" Width="140" />
         <TextBox MaxLength="100" Name="txtEmail" Text="email@server.com" Width="240" Margin="1" Height="23" />
      </StackPanel>
   </Grid>
</UserControl>

代码:


namespace SIMind.ClinicManagement.GUI.Controls.CommonControl
{
/// <summary>
/// Interaction logic for EmailAddressCtrl.xaml
/// </summary>
public partial class EmailAddressCtrl : UserControl
{
    public EmailAddressCtrl()
   {
       InitializeComponent();
   }

   #region Dependency Property

   #region Title Property

   /// <summary>
   /// Title property
   /// </summary>
   public static readonly DependencyProperty TitleProperty =
      DependencyProperty.Register("Title", typeof(String),
      typeof(EmailAddressCtrl), new PropertyMetadata("Phone Number :"));

   /// <summary>
   /// Gets and Sets the main label of the control.
   /// </summary>
   public string Title
   {
       get { return (string)GetValue(TitleProperty); }
       set { 
          SetValue(TitleProperty, value);
          lblEmailCaption.Content = value; 
       }
   }

   #endregion


   #endregion

   }
}


但它似乎没有按照我希望的方式工作:依赖属性已设置,但标签未刷新为属性集。

有人得到了一个很好的答案吗? :-)

1 个答案:

答案 0 :(得分:1)

希望这对你有用

<Label Content="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type EmailAddressCtrl}},Path=Title}" Height="24" HorizontalContentAlignment="Right" Name="lblEmailCaption" Tag="PhoneType" Width="140" />