How to set value of a textbox field in UserControlA from UserControlB

Kalpana 286 Reputation points
2020-08-06T08:23:32.253+00:00

Hi

I have a got a window that has UserControl A. This User Control A contains a TextBoxUCA field. I have got another UserControl, which is named as UserControlB.
I would need to set the value TextBoxUCA from UserControlB. How can I achieve that, so blur about dependency property, do I need to use dependency property or can I just create a property for the TextBoxUCA at UserControl A. Would appreciate anyone who can point me to the right direction.

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,676 questions
0 comments No comments
{count} votes

Accepted answer
  1. Peter Fleischer (former MVP) 19,231 Reputation points
    2020-08-06T09:44:15.973+00:00

    Hi,
    the easiest way to communicate between 2 UserControls is Binding to properties in the same instance of ViewModel, like this:

    Main window with UserControls and DataContext (ViewModel instance)

    <Window x:Class="Window046"  
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"  
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"  
            xmlns:local="clr-namespace:WpfApp1.WpfApp046"  
            mc:Ignorable="d"  
            Title="Window046" Height="450" Width="800">  
      <Window.DataContext>  
        <local:ViewModel/>  
      </Window.DataContext>  
      <StackPanel>  
        <local:Window046UC1 Height="100"/>  
        <local:Window046UC2 Height="100"/>  
      </StackPanel>  
    </Window>  
    

    First UserControl with TextBox:

    16120-x.png
    16093-06-08-2020-11-50-14.gif

    1 person found this answer helpful.
    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. DaisyTian-1203 11,616 Reputation points
    2020-08-10T03:49:56.84+00:00

    I will show you a demo with C# code.
    The Xaml code:
    16655-capture.png

    The cs code is:
    16656-capture2.png

    The result is as below shown:
    16540-4.gif


  2. Kalpana 286 Reputation points
    2020-08-12T03:48:11.687+00:00

    HI

    Thank you for replying. Solved it

    0 comments No comments