从mainpage.xaml更新UserControl Textblock文本

时间:2015-01-05 11:46:36

标签: xaml windows-phone-8 user-controls

我正在编写Windows Phone 8.1 Silverlight应用程序。我做了一个用户控件NotificationsIconUserControl。它只包含一个BELL / ALARM图标和文本块,以显示未读通知的数量。

我想从mainpage.xaml

更新此文本块文本

怎么做?

我尝试使用usercontrol expose properties,但事实恰恰相反。还尝试了this question的帮助。如何使用依赖属性。请编辑以下代码:

Usercontrol XAML:     

<Grid x:Name="LayoutRoot" 
      Background="Transparent"
      Height="Auto"
      Width="Auto">

    <Image
            Name="Alarm_Icon" 
            Source="/Images/Status/Notification_Icon_1.png">
    </Image>

    <Ellipse 
                Name="Counter_Icon"
                Height="45"
                Width="45" 
                Margin="60,14,-6,50"
                StrokeThickness="0" 
        Fill="{StaticResource DefaultTheme_IndianRedColor}">
    </Ellipse>

    <TextBlock
        Name="Counter_Label"
        Foreground="{StaticResource DefaultTheme_LightColor}"
        FontSize="30"
        HorizontalAlignment="Center" 
        VerticalAlignment="Center" 
        TextAlignment="Center" 
       Margin="75,20,8,58"/>
</Grid>

主页XAML部分:

        xmlns:MyUserControls="clr-namespace:Project.Custom.UserControls">

主页.cs部分:

   private void ConfigureNotificationsIcon()
    {
        int NotificationsCounter = 4;
        NotificationsIconUserControl NotificationsIconUserControlObject = new NotificationsIconUserControl();
        NotificationsIconUserControlObject.Counter_Label.Text = NotificationsCounter.ToString();
    }

1 个答案:

答案 0 :(得分:0)

我检查了你的代码并完全正常工作.... 对于添加Dependency属性的部分,请在UserControl的.cs文件中编写以下内容

public partial class NotificationIconUserControl : UserControl

 {

    public NotificationIconUserControl()
    {
        InitializeComponent();

    }

    public string NotificationLabel
    {
        get { return (string)GetValue(NotificationLabelProperty); }
        set { SetValue(NotificationLabelProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Spacing.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty NotificationLabelProperty =
        DependencyProperty.Register("NotificationLabel", typeof(string), typeof(NotificationIconUserControl), new PropertyMetadata("hellllo"));
}

之后,您可以使用TemplateBinding来完成工作