WPF-如何将实际输入的文本从UserControl文本框获取到窗口

时间:2019-06-15 17:19:34

标签: visual-studio xaml textbox

我正在尝试将实际输入的文本从UserControl记录到Window。

用户控制代码为:

public partial class FormGenerals : UserControl
{
    public FormGenerals()
    {
        InitializeComponent();
    }

    public string ProductTitle
    {
        get { return txtProductTitle.Text; }
        set { txtProductTitle.Text = value; }
    }

    public string ProductDescription
    {
        get { return txtProductDescription.Text;  }
        set { txtProductDescription.Text = value; }
    }

    public string ProductPrice
    {
        get { return txtProductPrice.Text; }
        set { txtProductPrice.Text = value; }
    }

    public static readonly RoutedEvent TextFieldChangedEvent =
   EventManager.RegisterRoutedEvent("TextFieldChangedEvent", RoutingStrategy.Bubble,
   typeof(RoutedEventHandler), typeof(FormGenerals));

    public event RoutedEventHandler TextFieldChanged
    {
        add { AddHandler(TextFieldChangedEvent, value); }
        remove { RemoveHandler(TextFieldChangedEvent, value); }
    }

    private void TxtProductTitle_TextChanged(object sender, TextChangedEventArgs e)
    {
        RaiseEvent(new RoutedEventArgs(TextFieldChangedEvent));
    }

    private void TxtProductDescription_TextChanged(object sender, TextChangedEventArgs e)
    {
        RaiseEvent(new RoutedEventArgs(TextFieldChangedEvent));
    }

    private void TxtProductPrice_TextChanged(object sender, TextChangedEventArgs e)
    {
        RaiseEvent(new RoutedEventArgs(TextFieldChangedEvent));
    }

窗口部分:

public partial class AddNotebookSmall : Window
{

    static FormGenerals formGenerals = new FormGenerals();
    public AddNotebookSmall()
    {
        InitializeComponent();
        btnSaveFormula.IsEnabled = false;
        AddHandler(FormGenerals.TextFieldChangedEvent, new RoutedEventHandler(Window_UserControl_TextFieldChangedEventHandlerMethod));
    }

    private void Window_UserControl_TextFieldChangedEventHandlerMethod(object sender, RoutedEventArgs e)
    {
        Console.WriteLine(formGenerals.ProductTitle);
        Console.WriteLine(formGenerals.ProductDescription);
        Console.WriteLine(formGenerals.ProductPrice);
    }
}

XAML类似于TextBox Text =“ enter title”,其中输入标题应为占位符。例如,现在输入abc时,它应该记录a,ab,abc,这是从UserControl本身而不是从窗口登录时实际执行的操作。

当尝试从窗口执行日志记录时,它会识别出更改,这意味着传递EventHandler是有效的,而不是文本本身。

因此,当我在产品标题字段中输入例如abc时,它会记录我输入标题,输入标题和标题的信息。如何将实际的插补文本传递到窗口?

我也通过DependencyProperty尝试过,但是得到了相同的结果。我不知道那里有那个。

感谢您的帮助,在此先感谢您!

0 个答案:

没有答案