简体   繁体   中英

UWP: Passing value from UserControl to MainPage

I have created a UserControl where everything is done in the UserControl.xaml.cs and I want a specific property (called "Value") from the UserControl to be passed to a TextBlock which is created in the MainPage. To test the access of the property, I have created a TextBlock within the UserControl and Bind to Text to "Value" via Text={Binding Path=Value} and it works fine. How do I have to bind the TextBlock from the MainPage to achieve the same?

You might be able to use the ElementName part of the Binding to access the Value from the UserControl. To do this you'll have to give your UserControl an x:Name then set up your Binding like so:

Text="{Binding Value, ElementName=MyUserControl}"

Make sure you have created your Property as a DependencyProperty. You can do it using below code

public string Value
{
    get { return (string)GetValue(ValueProperty); }
    set { SetValue(ValueProperty, value); }
}

public static readonly DependencyProperty ValueProperty =
    DependencyProperty.Register("Value", typeof(string), typeof(UserControl ), new PropertyMetadata(""));

You can get the value in XAML using below code

<TextBlock Text="{Binding ElementName=UserControl, Path=Value}"/>

(OR)

<TextBlock Text="{x:Bind CustomInkControl.Value, Mode=OneWay}"/>

Note: Use x:Bind because It is efficient than Binding

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM