问题
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.Textproperty inside yourUserControlso that you can modify it from yourMainPagelike this
myUserControl.SetText("MyText");
- With binding: You should define a dependency property inside your user control that will wrap your
TextBox.Textproperty. Then in the xaml of your main page you can bind this new defined property of yourUserControlas if it was aTextBlock. 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