如何从mainpage.xaml更新UserControl文本块文本

时间:2014-03-13 10:46:23

标签: windows-phone-8

我在usercontrol中有textblock.Now我想在mainpage.xaml中输入文本时更新textblock的文本。请帮助

我试过这个例子,但它没有更新文本。

UserControl.xaml

<TextBlock 
    x:Name="txtCartcount" 
    Text="{Binding CartCount}"      
    VerticalAlignment="Center" 
    FontWeight="Bold" 
    FontSize="15" 
    Foreground="#E4328A"   
    HorizontalAlignment="Center">
</TextBlock>

MainPage.xaml中

private string _CartCount;

public string CartCount
{
    get { return _CartCount; }
    set { _CartCount = value; NotifyPropertyChanged("CartCount"); }
}

CartCount=txtMessage.text;

1 个答案:

答案 0 :(得分:1)

我假设您的用户控件包含其他元素,而不仅仅是TextBox,如果不是这样,您可以将TextBox直接放入{{1}因为它更容易。

考虑到这一假设,您有两种方法可以更改MainPage.xaml内的文字:

  • 没有绑定:您应该在UserControl内公开展示TextBox.Text属性的setter,以便您可以从UserControl这样修改< / LI>
  

myUserControl.SetText(&#34; MYTEXT&#34);

  • 使用绑定:您应该在用户控件中定义一个依赖项属性,它将包装您的MainPage属性。然后在主页面的xaml中,您可以绑定TextBox.Text的新定义属性,就好像它是UserControl一样。以下是您的工作方式:

TextBlock代码隐藏中:

UserControl

现在您的UserControl有一个可绑定的public static readonly DependencyProperty TextProperty = DependencyProperty.Register( "Text", typeof(String),typeof(UserControl), null ); //This dependency property defined above will wrap the TextBlock's Text property public String Text { get { return (String)GetValue(txtCartcount.Text); } set { SetValue(txtCartcount.Text, value); } } 属性,您可以在Text中使用这样的属性:

MainPage.xaml

现在,如果您正确设置绑定,当您更改绑定属性并启动<UserControl Text = "{Binding PropertyToBindTo}" </UserControl> 事件时,NotifyChanged的已定义Text属性将收到通知,将调用其setter,它将设置UserControl的真实Text属性。

希望这有帮助。

相关问题