I am trying to pass a simple string between pages but I don't know how to.
I created a test app where I click a button, the the value of "a" will pass on the next page (Page1.xaml.cs)
private void button1_Click(object sender, RoutedEventArgs e)
{
string a = "hello";
Page2 p2 = new Page2();
NavigationService.Navigate(p2, a);
}
Now, I want to extract the data from Page1 (Page2.xaml.cs)
private void NavigationService_LoadCompleted(object sender, NavigationEventArgs e)
{
string str = (string)e.ExtraData;
}
And then subscribing in the constructor (Page2.xaml.cs)
public Page2()
{
InitializeComponent();
NavigationService.LoadCompleted += NavigationService_LoadCompleted;
}
However when I ran the program I get an error. Can someone point out what am I missing?
Without a good Minimal, Complete, and Verifiable code example, it's impossible to know for sure everything that would be needed to address your question. However, if all you're asking is how to allow data to pass from one page to the next when navigating, it seems to me that the NavigationService.Navigate(object, object) overload would be useful for you.
The second parameter is the data you want to pass. The target page can handle the NavigationService.LoadCompleted event (or any other appropriate one you prefer), where the object value that was passed to the Navigate() method can be retrieved via the NavigationEventArgs.ExtraData property.
For example, in your first page:
private void button_Click(object sender, RoutedEventArgs e)
{
Page2 p2 = new Page2();
NavigationService.Navigate(p2, v.str);
}
then in your second page:
private void NavigationService_LoadCompleted(object sender, NavigationEventArgs e)
{
string str = (string)e.ExtraData;
// do whatever with str, like assign to a view model field, etc.
}
Of course, you'll subscribe the event handler, e.g. in your page's constructor or in XAML. For example:
public partial class Page2 : Page
{
public Page2()
{
InitializeComponent();
NavigationService.LoadCompleted += NavigationService_LoadCompleted;
}
private void button_Click(object sender, RoutedEventArgs e)
{
NavigationService.GoBack();
}
private void NavigationService_LoadCompleted(object sender, NavigationEventArgs e)
{
string str = (string)e.ExtraData;
// do whatever with str, like assign to a view model field, etc.
}
}
Instead of setting the textbox DataContext, set the entire page’s datacontext to some class ie the ViewModel for page1. Implement the interface INotifyPropertyChanged and ensure that in the set of the string property, the NotifyPropertyChanged(“ElementName”) is raised.
Now create a new view with a corresponding view model like this which should also implement the interface INotifyPropertyChanged. Create a textbox and bind it to a string property like in first page. Ensure TwoWay binding for both properties to ensure both target and source is updated while data is changed.
Create the instance of both viewModels in MainWindow. When user navigates to 2nd user control, set
Page2ViewModel.TextBoxString = Page1ViewModel.TextBoxString;
Like this do vice versa while navigating from Page2 to Page1.
Page1ViewModel.TextBoxString = Page2ViewModel.TextBoxString;
This way, both the textboxes will be updated during navigation.
This is just an overall idea. You need to learn more about MVVM and WPF from some tutorials. Search in google.
Here is my example, maybe it helps someone
in Page1.cs
examsStr = result.Content.ReadAsStringAsync().Result;
List<Exam> exams = JsonConvert.DeserializeObject<List<Exam>>(examsStr);
for (int i = 0; i < exams.Count; i++)
{
btnExam.Click += BtnExam_OptionsShow;
btnExam.DataContext = exams[i];
}
private void BtnExam_OptionsShow(object sender, EventArgs e)
{
ExamRead examPage = new ExamRead();
examPage.DataContext = ((sender as Button).DataContext as Exam);
this.NavigationService.Navigate(examPage);
}
in Page2.cs
this.Loaded += ExamRead_Loaded;
private void ExamRead_Loaded(object sender, RoutedEventArgs e)
{
examObj = (exam.DataContext as Exam);
(exam.Children[2] as Label).Content = examObj.ExamName + " - Exam Options";
}
Page2 has attribute Name="exam" and examObj is global variable in that Page2 class
Related
I have a cs file for Drag drop Element. In the Method after the drop is completed (OnManipulationCompleted) I would like to initiate/trigger the 3 button clicks from another WPF page which has 3 buttons within the OnManipulationCompleted method.
namespace KinectDemos
{
public class DragDropElementController : IKinectManipulatableController
{
private ManipulatableModel _inputModel;
private KinectRegion _kinectRegion;
private DragDropElement _dragDropElement;
private bool _disposedValue;
public DragDropElementController(IInputModel inputModel, KinectRegion kinectRegion)
{
_inputModel = inputModel as ManipulatableModel;
_kinectRegion = kinectRegion;
_dragDropElement = _inputModel.Element as DragDropElement;
_inputModel.ManipulationStarted += OnManipulationStarted;
_inputModel.ManipulationUpdated += OnManipulationUpdated;
_inputModel.ManipulationCompleted += OnManipulationCompleted;
}
private void OnManipulationCompleted(object sender,
KinectManipulationCompletedEventArgs kinectManipulationCompletedEventArgs)
{**HERE I WOULD LIKE TO INITIATE THE BUTTON CLICKS**
}
The Other Wpf page which has these buttons having function for three buttons .After each button drop it would navigate to another page.
Public partial class Beauty : Usercontrol
{
Public void Tip_Click (object sender, RoutedEventArgs e)
{
Afterdrop page1 = new Afterdrop
this.content = page1;
}
Public void Tricks_Click (object sender, RoutedEventArgs e)
{
Afterdrop2 page2 = new Afterdrop2
this.content = page2;
}
Public void Invent_Click (object sender, RoutedEventArgs e)
{
Afterdrop3 page3 = new Afterdrop3
this.content = page3;
}
}
How will I do that ?Please help
You need to have an instance of the page you want to trigger events on. If that page exists then you can get that instance based on your application architecture otherwise there is no way to call non-static members without instantiating an object.
Once you get that page instance call the respective event handlers as methods. As an example if that instance is named targetPage then
targetPage.Tip_Click(null, new EventArgs());
Ok, so I am new to custom controls, and need be able to get the contents of a text box that is part of a custom user control.
So say I want to access the text that the user has entered in the Name Textbox, how would I do this? What would I have to add to the code for the control? Or is there a way to just reference it from the form that the control is on?
Here is the code for the control:
public partial class CharacterControl : UserControl
{
public CharacterControl()
{
InitializeComponent();
}
private void get_start_Click(object sender, EventArgs e)
{
starttime.Text = DateTime.Now.ToString("HH:mm");
}
private void get_end_Click(object sender, EventArgs e)
{
endtime.Text = DateTime.Now.ToString("HH:mm");
}
}
Turns out all I had to do is set the access modifier to public.
There are two pages in my app. First one is MainPage and second one is SettingsPage There is one textbox in my settings page. I want to save this textbox text and send to MainPage.
Here the new example. Now its working but I can't save the textBox1.text which is in the SettingsPage . It's cleaning when I navigate other page.
public sealed partial class MainPage : Page
{
private NavigationHelper navigationHelper;
public MainPage()
{
this.InitializeComponent();
progRing.IsActive = true;
Window.Current.SizeChanged += Current_SizeChanged;
this.NavigationCacheMode = NavigationCacheMode.Required;
this.navigationHelper = new NavigationHelper(this);
this.navigationHelper.LoadState += this.NavigationHelper_LoadState;
}
public NavigationHelper NavigationHelper
{
get { return this.navigationHelper; }
}
private void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
{
this.txtBoxNotification.Text = (string)e.NavigationParameter;
}
private void btnNotification_Click(object sender, RoutedEventArgs e)
{
webView.Navigate(new Uri("http://teknoseyir.com/u/" + txtBoxNotification ));
}
The standard way to send navigation parameters between pages in WP8 is to use
NavigationService.Navigate(new Uri("/MainPage.xaml?text=" + textBox1.Text, UriKind.Relative));
Then check for the parameter on the OnNavigatedTo() Method on the page you have navigated to.
protected override void OnNavigatedTo(NavigationEventArgs e)
{
string settingsText = NavigationContext.QueryString["text"];
}
For Windows Phone 8.1 you no longer navigate using a URI. The approach is to use:
this.Frame.Navigate(typeof(MainPage), textBox1.Text);
Then on the loadstate for the page you are navigating to you can get the data by using:
private async void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
{
string text = e.NavigationParameter as string;
}
Hope this helps.
You could also do this by using PhoneApplicationService. Set a value like this,
string str = textBox.Text;
PhoneApplicationService.Current.State["TextBoxValue"] = str;
Now you can call that value whereever you want using it key value. And get a value like this,
textblock.Text = PhoneApplicationService.Current.State["TextBoxValue"] as String;
In Windows Phone 8.1, you can transfer values as parameter of Frame.Navigate method.
For example, you want to transfer yourValue of yourType:
Frame.Navigate(typeof(TargetPage), yourValue);
and get it in target page:
protected async override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
{
var value = navigationParameter as yourType;
}
the value is what you want to get.
The best easiest way I used for this is to declare a public static class in the main page so you can use the SAME class methods anywhere in your app pages as like this :
public static class MyClass
{
public static string MyString = null;
}
then you can give it a value from a text box from the settings page as like this :
PhoneApp.MainPage.MyClass.MyString = TextBoxInSettings.Text;
then give this value back to another text box in the main page as like this :
TextBoxInMainPage.Text = MyClass.MyString;
I have 2 Asp button in a page (buttonUsername and buttonReset). First one perform an AD search, and set a private variable, while second button perform an action, using variable previously set.
public partial class ResetPassword : System.Web.UI.Page {
private UserPrincipal tmpPwdUser;
protected void buttonUsername_Click(object sender, EventArgs e) {
this.tmpPwdUser = ...
}
protected void buttonReset_Click(object sender, EventArgs e) {
myObj.myFunction(this.tmpPwdUser); // --> this.tmpPwdUser is void
}
}
My problem: this.tmpPwdUser is correctly set in buttonUsername_Click function, but when buttonReset_Click event is triggered, variable this.tmpPwdUser is null. I guess that when event is triggered, page is reloaded, so each local variable is reset. Is there a way to preserve state when button si clicked?
As you suspect, a new instance of the form is created for the new request. You have to preserve the value of the variable between those requests. One way to do this is to store the value in ViewState.
You can create a helper property that stores and retrieves the value from ViewState:
private UserPrincipal TmpPwdUser
{
get
{
return ViewState["UniqueViewStateKey"] As UserPrincipal;
}
set
{
ViewState["UniqueViewStateKey"] = value;
}
}
try using the OnEvent property instead of the onclick
Poperty on button ( OnCommand="Submit_Command")
in code behind
Submit_Command(object sender, CommandEventArgs e)
{
}
i have a textbox on .aspx page..On this page there is a user control .Inside this user contrl there is a button .I want o get the value of text box on button click which is not inside the user control .How can i do this
Please Help me .
write this line in you button click event of user control
protected void Button_Click(sender obj,EventArgs arg)
{
TextBox txtbox= (((MyPage)parent).FindControl("TextBoxid") as TextBox);
if(txtbox!=null)
(((MyPage)this.Page).FindControl("TextBoxid") as TextBox).Text;
//or
//(((MyPage)this.Parent).FindControl("TextBoxid") as TextBox).Text;
}
or
alternative is create the property in your page and access it in your user control
public string txtValue
{
get
{
return TextboxID.Text;
}
}
in button click event of user control
protected void Button_Click(sender obj,EventArgs arg)
{
string txtvalue = ((Mypage)this.Page).txtValue;
//or
//((MyPage)this.Parent).txtValue;
}
protected void MyButton_Click(object sender, EventArgs e)
{
string TextBoxValue;
TextBoxValue = MyTextBox.Text;
}
Is it what you want ?
Try use the following method,
((TextBox)USerControl.Parent.FindControl("txtbox")).Text
((TextBox)USerControl.Page.FindControl("txtbox")).Text
or
((YourPageType)USerControl.Page).TextBox.Text
With de-coupling in mind, I would recommend that if your user control needs to access information outside of it, then that information should passed in, not vice versa. The control shouldn't be responsible for where the information comes from, it just knows there is information. With this in mind, I would recommend bubbling the event to get the required information.
Event Bubbling
This will involve creating a new delegate, and then triggering it once the Button has been clicked, thus bubbling the event and allowing us to return the desired value, which in this case is the textbox value.
Step 1: Declare the delegate
// declare a delegate
public delegate string MyEventHandler(object sender, EventArgs e);
Step 2: Update the user control
// update the user control
public class MyUserControl : UserControl
{
// add the delegate property to your user control
public event MyEventHandler OnSomeButtonPressed;
// trigger the event when the button is pressed
protected void MyButton_Click(object sender, EventArgs e)
{
string someString = string.Empty;
if (this.OnSomeButtonPressed != null)
{
someString = this.OnSomeButtonPressed(this, e);
}
// do something with the string
}
}
Step 3: Update the page
// be sure to register the event in the page!
public class MyPage : Page
{
protected override void OnLoad(object sender, EventArgs e)
{
base.OnLoad(sender, e);
myUserControl.OnSomeButtonPressed += this.HandleUserControl_ButtonClick;
}
public string HandleUserControl_ButtonClick(object sender, EventArgs e)
{
return this.SomeTextBox.Text;
}
}