How to Pass a Value From a Window to a UserControl in WPF

末鹿安然 提交于 2020-01-11 11:06:13

问题


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(Passing Value To 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);
}

UserControl

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

EDIT(using BINDING and 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));
        }
    }

回答1:


Problem here is with reference.

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

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




回答2:


You are calling data in the constructor when idd is still "" which results in the text box still being empty. Changing the MyParent property does not change that. Only passedv does. But at that point you do not have the parent set. Just call data in passedv, too.




回答3:


Try this:

public partial class GroupsItems : UserControl
{
   //properties and methods

    private string idd="";

    public string IDD
    {
    get{return idd;}
    set{
        idd=value; 
        textBox1.Text=idd;
        }
    }

   //other properties and methods
}

Usage:

In your Main form:

    abc = new GroupsItems();
    abc.IDD="sometext";
    MainGrid1.Children.Add(abc);   //Grid or any other container for your UserControl



回答4:


In your Binding example, your GroupItem class looks ok, except that you need to pass in the name of the changed property:

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

Now, in GroupsItems, you shouldn't be accessing the TextBox. In WPF, we manipulate the data, not the UI... but as we use Binding objects to data bind the data to the UI controls, they automatically update (if we correctly implement the INotifyPropertyChanged interface).

So first, let's add a data property into your code behind (which should also implement the INotifyPropertyChanged interface) like you did in your GroupItem class:

private GroupItem _item = new GroupItem();

public GroupItem Item
{
    get { return _item; }
    set
    {
        if (value != _item)
        {
            _item = value;
            NotifyPropertyChanged("Item");
        }
    }
}

Now let's try using a Binding on a TextBox.Text property:

<TextBox Text="{Binding Item.Text}" />

See how we bind the Text property of your GroupItem class to the TextBox.Text property... now all we need to do is to change the value of the Item.Text property and watch it update in the UI:

<Button Content="Click me" Click="Button_Click" />

...

private void Button_Click(object sender, RoutedEventArgs e)
{
    Item.Text = "Can you see me now?";
}

Alternatively, you could put this code into your passedv method if you are calling that elsewhere in your project. Let me know how you get on.


UPDATE >>>

In your GroupItem class, try changing the initialization to this:

private string _text = "Any text value";

Can you now see that text in the UI when you run the application? If not, then try adding/copying the whole Text property into your code behind and changing the TextBox declaration to this:

<TextBox Text="{Binding Text}" />

If you can't see the text value now, you've really got problems... you have implemented the INotifyPropertyChanged interface in your code behind haven't you?



来源:https://stackoverflow.com/questions/19514617/how-to-pass-a-value-from-a-window-to-a-usercontrol-in-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!