如何在 WPF 中将值从窗口传递到用户控件 [英] How to Pass a Value From a Window to a UserControl in WPF

查看:43
本文介绍了如何在 WPF 中将值从窗口传递到用户控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个值从 MainWindow 传递到我的 UserControl 中!我向我的 UserControl 传递了一个值,UserControl 向我显示了 MessageBox 中的值,但它没有显示 TextBox 中的值.这是我的代码:

I want to pass a value from MainWindow into my UserControl! I passed a value to my UserControl and the UserControl showed me the value in a MessageBox, but it is not showing the value in a TextBox. Here is my code:

MainWindow(将值传递给 UserControl)

try
{
    GroupsItems abc = null;
    if (abc == null)
    {
        abc = new GroupsItems();
        abc.MyParent = this;
        abc.passedv(e.ToString(), this);

    }
}
catch (Exception ee)
{
    MessageBox.Show(ee.Message);
}

用户控件

public partial class GroupsItems : UserControl
{
    public MainWindow MyParent { get; set; }
    string idd = "";
    public GroupsItems()
    {
        InitializeComponent();
        data();
    }

    public void passedv(string id, MainWindow mp)
    {
        idd = id.ToString();
        MessageBox.Show(idd);
        data();
    }

    public void data()
    {
        if (idd!="")
        {
            MessageBox.Show(idd);
            texbox.Text = idd;
        }
    }
}

编辑(使用 BINDING 和 INotifyProperty )

.....

   public GroupsItems()
      {
            InitializeComponent();
      }

    public void passedv()
    {
        textbox1.Text = Text;
    }

}

public class Groupitm : INotifyPropertyChanged
{

    private string _text = "";

    public string Text
    {
        get { return _text; }
        set
        {
            if (value != _text)
            {
                _text = value;
                NotifyPropertyChanged();
            }
        }
    }



    public event PropertyChangedEventHandler PropertyChanged;

    protected void NotifyPropertyChanged(String propertyName = "")
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

推荐答案

这里的问题供参考.

当您在代码中创建新对象时,将创建新对象,这与您在 xaml 代码中拥有的对象不同.所以你应该使用以下代码:

When you create new object in code behind, new object will be created and this is not the same object which you have in xaml code. So you should use following code:

<local:GroupsItems x:Name="myGroupsItems"/>

在后面的代码中,您不必创建新对象.您应该使用您在 XAML 中添加的对象:

and in code behind you don't have to create new object. You should use object that you added in XAML:

...
myGroupsItems.MyParent = this;
myGroupsItems.passedv(e.ToString(), this);
...

这里是示例解决方案(示例项目).

Here is example solution (sampleproject).

这篇关于如何在 WPF 中将值从窗口传递到用户控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆