How do i update UserControl textblock text from mainpage.xaml

白昼怎懂夜的黑 提交于 2019-12-24 12:12:59

问题


I have textblock inside usercontrol.Now i want to update the text of textblock when i enter the text in mainpage.xaml.Please help

i tried this example but it does not update text.

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:


I'll suppose your user control contains other elements and not just the TextBox, if it's not the case, you can put your TextBox directly into your MainPage.xaml as it's easier.

Given that assumption, you have two options to change the text insideyour UserControl:

  • Without Binding: You should publicly expose a setter of your TextBox.Text property inside your UserControl so that you can modify it from your MainPage like this

myUserControl.SetText("MyText");

  • With binding: You should define a dependency property inside your user control that will wrap your TextBox.Text property. Then in the xaml of your main page you can bind this new defined property of your UserControl as if it was a TextBlock. Here's how you'd do this:

In your UserControl's codebehind:

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); }
}

Now your UserControl have a Bindable Text property that you can use in your MainPage.xaml like this:

<UserControl
    Text = "{Binding PropertyToBindTo}"
</UserControl>

So now if you set up your binding correctly, when you change the bound property and fire up the NotifyChanged event, the defined Text property of your UserControl will get the notification and will call its setter, which will set the real Text property of your txtCartcount.

Hope this helps.



来源:https://stackoverflow.com/questions/22376150/how-do-i-update-usercontrol-textblock-text-from-mainpage-xaml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!