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

标签 c# .net xml wpf winforms

我正在使用 WinFormWPF。我试图弄清楚如何在我的 WinForm 应用程序中单击按钮时更新我的​​ WPF 文本框控件 中的文本。使用 WinForm Textbox 我可以简单地执行 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

最佳答案

像这样在用户控件中绑定(bind)文本框:

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

在用户控件后面的代码中添加一个依赖属性:

    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++;
}

关于c# - 使用 Winform 更新 WPF 文本框用户控件中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40183435/

相关文章:

c# - 在 ASP.NET Web Api 2.0 GET 请求中传递 DateTimeKind

java - 如何将 XML 请求附加到 SOAP Body 的唯一 SOAPElement 子级?

.net - 如何在 Windows 10 PRO 上的 Visual Studio 2019 中添加对 Windows.ApplicationModel.DataTransfer 命名空间的引用

c# - 调用堆栈和评估堆栈如何关联?

c# - 为什么相同的 DateTime 值会为不同的用户产生不同的显示时间?

c# - 删除没有后代的 XML 节点

c# - 替代 WebClient 以防止超时?

c# - 如何确定可以连接到给定远程 IP/DNS 地址的本地 IP 地址

c# - 使用 Quartz.NET 安排 Windows 服务

c# - C#语句中的逗号