Another subject and a difficulty along with it surfaced while playing with WPF and it lies in an attempt to call a function from within a dynamically added user control passing it a value.
For current example I have a user control that has a property "Secret" and a button in it named "PublishSecret", constructor sets the value of the Secret to a random number. In MainWindow I have another button named "AddSecretContainer" that adds to the window an additional instance of this user control, next to it I have a textbox named "PublishedSecret". A simple method in MainWindow also was defined, here it is:
public void PublishSecret(int secret)
{
this.PublishedSecret = secret;
}
Now without passing this Secret I could use routed commands with their bubbling effect. But how can I call PublishSecret providing it with the local value of Secret from user control when PublishSecret button was clicked?
If your UserControl
was added dynamically, then I assume that you have access to a reference of it in your main view model/code behind. This makes your situation nice and simple. You said there is a Button
named PublishSecret
, well I also assume that clicking it initiates some functionality.
My first suggestion would be the simplest. Put that functionality into a public
method which would be called from your Click
or ICommand
handler and then simply call that method from your main view model:
childUserControl.PublishSecret();
Please let me know if I have misunderstood your problem.
UPDATE >>>
Ok sorry, I've got you now. You can declare a delegate
, add a property of that type to your child UserControl
and attach a handler in the main view model. Then you can call the delegate
and in the handler in the parent view model, you can call your method. For more information on this technique, please see my answer to the Passing parameters between viewmodels question.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.