Nigel-Lee
Nigel-Lee

Reputation: 155

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?

Upvotes: 0

Views: 832

Answers (2)

Vijay Nirmal
Vijay Nirmal

Reputation: 5837

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

Upvotes: 1

jsmyth886
jsmyth886

Reputation: 531

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}"

Upvotes: 1

Related Questions