使用Winform更新WPF文本框用户控件中的文本

时间:2016-10-21 18:39:53

标签: c# .net xml wpf winforms

我正在使用WinFormWPF。我试图找出如何在点击按钮时更新WPF textbox control应用程序WinForm中的文本。使用WinForm文本框我可以简单地执行MyTextBox.Text = counter,但是使用WPF我无法做到。为什么,你是怎么做到的?

例如,如果我点击按钮,我的WPF文本框应该计数1,2,3,4,5 ...但它没有。

WinForm代码

    int counter = 0;

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

    }

WPF用户文本框用户控件

<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

WinForms中的我的WPF用户控件设置

enter image description here

1 个答案:

答案 0 :(得分:2)

将文本框绑定在用户控件中,如下所示:

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

在usercontrol的代码后面添加依赖项属性:

    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));

  }

在WinForm Button.Click事件中,您可以像这样更新:

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