سؤال

I have a UserControl that needs to change the .text of a TextBox on a Page. My problem is that I can't find a way to access the TextBox from the code-behind for the UC. By the way, I am using Visual C++, not C#.

Basically the UserControl has a TextBox and when the text in it changes I need the text from the TextBox on the Page to change. If that makes sense.

I've tried binding the Page TextBox to the UserControl TextBox, but I can't get either TextBox to find the other. I've tried #include the Page .h in the UserControl, but that still doesn't give me access to the TextBox on the Page. I also looked into using Window::Current::Content on the UserControl but that doesn't seem to give me access to the Page TextBox either (Unless I misunderstand how that works).

If you need any of my code let me know, but right now it's part of a larger project and wouldn't make any sense unless I delete a bunch of stuff, but then you wouldn't be able to copy it and try to run it so I've tried to ask my question by giving as much detail as possible but keeping it simple. I've scoured the internet searching for "XAML binding TextBox to UserControl" and while the results are limited, I've been through all of them (I've been stuck trying to figure this out on my own for almost a week now).

هل كانت مفيدة؟

المحلول

First, I have three links for you and I really hope for your sake, that you read the linked pages. The first link from MSDN should help you to get started with WPF as it's clear that you have no idea how to use it yet:

Walkthrough: Getting Started with WPF

The second and third links are from the StackOverflow Help Center because it's also clear that you haven't read these pages either and they will help you to get the most out of this website (and get your questions answered quicker):

How do I ask a good question?
How to create a Minimal, Complete, Tested and Readable example

Now to address your question... you can simply add a DependencyProperty to your UserControl and data bind to it from both inside and outside the control. In code behind:

public static readonly DependencyProperty ValueProperty = DependencyProperty.Register(
    "Value", typeof(string), typeof(MainWindow), new UIPropertyMetadata("Some text"));

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

The XAML inside UserControl:

<TextBlock Text="{Binding Value, RelativeSource={RelativeSource AncestorType={x:Type 
    YourLocalPrefix:YourControlname}}}" />

The XAML outside UserControl:

<YourLocalPrefix:YourControlname Value="{Binding SomePropertyOutsideControl}}}" />
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top