taji01 taji01 - 1 month ago 7
C# Question

Update text in WPF textbox user control using Winform

I'm using both

WinForm
and
WPF
. I'm trying to figure out how to update the text in my
WPF textbox control
in my
WinForm
application on button click. Using
WinForm
Textbox I can simply do
MyTextBox.Text = counter
, but with WPF I'm not able to. Why, and how do you do this?

For example, if i click on the button my WPF textbox should count up 1,2,3,4,5...but it doesn't.

WinForm Code

int counter = 0;

private void counter_btn_Click(object sender, EventArgs e)
{
counter++;
CountTxtBx.Text = counter.ToString();
CountTxtBx.Update();
Console.WriteLine(counter);

}


WPF User TextBox User Control

<UserControl x:Class="textbox_Update.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:textbox_Update"
mc:Ignorable="d"
d:DesignHeight="50
" d:DesignWidth="239">
<Grid>
<TextBox x:Name="textBox" HorizontalAlignment="Left" Height="50" TextWrapping="Wrap" Text="{Binding ElementName=textBox1, Path=Text}" VerticalAlignment="Top" Width="239" FontSize="20" Padding="0,7,0,0"/>

</Grid>




enter image description here

My WPF User Control Settings in WinForms

enter image description here

Answer

Bind your textbox in the user control like this:

<TextBox x:Name="textBox" HorizontalAlignment="Left" Height="50" TextWrapping="Wrap" Text="{Binding RelativeSource={RelativeSource AncestorType=UserControl}, Path=CounterValue}" VerticalAlignment="Top" Width="239" FontSize="20" Padding="0,7,0,0"/>

In code behind of the usercontrol you add a dependency property:

    public int CounterValue
    {
      get { return (int)GetValue(CounterValueProperty); }
      set { SetValue(CounterValueProperty, value); }
    }

    // Using a DependencyProperty as the backing store for CounterValue.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty CounterValueProperty =
        DependencyProperty.Register("CounterValue", typeof(int), typeof(UserControl1), new PropertyMetadata(0));

  }

In your WinForm Button.Click event you can update like this:

private void button1_Click(object sender, EventArgs e)
{
  (CountTxBx.Child as UserControl1).CounterValue++;
}
Comments