How to execute a binding for a metro control - windows-8

I want to write the contents of a per occasion active TextBox back to the bound property of the ViewModel when the user presses the key combination for save (Ctrl-S).
My Problem with it is, that I'm not able to trigger the execution of the binding so that the bound Text-Property reflects the contents of the TextBox.
-There seems to be no GetBinding-method. Therefore I can not get the Binding and execute it manualy.
-There is no Validate-method such as in WinForms which executes the Binding
-Giving focus to another control from within KeyDown seems not to work, the binding does not execute
How can I achieve this?

Take a look at Aaron's discussion about this in his WiredPrarie blog post : http://www.wiredprairie.us/blog/index.php/archives/1701

I think I understand your question better now. One way around this would be to use a sub-classed textbox with a new property like this from here:
public class BindableTextBox : TextBox
{
public string BindableText
{
get { return (string)GetValue(BindableTextProperty); }
set { SetValue(BindableTextProperty, value); }
}
// Using a DependencyProperty as the backing store for BindableText. This enables animation, styling, binding, etc...
public static readonly DependencyProperty BindableTextProperty =
DependencyProperty.Register("BindableText", typeof(string), typeof(BindableTextBox), new PropertyMetadata("", OnBindableTextChanged));
private static void OnBindableTextChanged(DependencyObject sender, DependencyPropertyChangedEventArgs eventArgs)
{
((BindableTextBox)sender).OnBindableTextChanged((string)eventArgs.OldValue, (string)eventArgs.NewValue);
}
public BindableTextBox()
{
TextChanged += BindableTextBox_TextChanged;
}
private void OnBindableTextChanged(string oldValue, string newValue)
{
Text = newValue ? ? string.Empty; // null is not allowed as value!
}
private void BindableTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
BindableText = Text;
}
}
Then bind to the BindableText property.

Solution for command-instances
Here a solution I have found which is relatively leightweight, but also a bit "hackish":
btn.Focus(Windows.UI.Xaml.FocusState.Programmatic);
Dispatcher.ProcessEvent(CoreProcessEventsOption.ProcessAllIfPresent);
btn.Command.Execute(null);
First I give the focus to another control (In my case the button which has the bound command). Then I give the system time to execute the bindings and in the end I raise the command which is bound to the button.
Solution without bound commands
Give the Focus to another control and call the Dispatcher.ProcessEvent(...).
anotherControl.Focus(Windows.UI.Xaml.FocusState.Programmatic);
Dispatcher.ProcessEvent(CoreProcessEventsOption.ProcessAllIfPresent);
// Do your action here, the bound Text-property (or every other bound property) is now ready, binding has been executed
Please see also the solution of BStateham.
It's another way to solve the problem

Related

Helix Toolkit How to use MouseWheelEventHandler to run specific methods in other classes

I would like to run particular methods of a custom Camera class whenever the user zooms in or out in the helix toolkit view that my program is running inside of.
A key feature of this functionality is getting the mouseargs from the event so I can adjust the camera in a way that is proportional to the number of scroll ticks.
I began to try this:
public event PropertyChangedEventHandler PropertyChanged;
public virtual void onMouseWheeled(MouseDevice Mouse, int time,
MouseWheelEventArgs e) {
MouseWheel?.Invoke(this, new MouseWheelEventArgs(Mouse, time,
e.Delta)); }
//This next line goes in a MainWindow_Loaded method that gets called in the
//MainWindowConstructor
void MainWindow_Loaded(object sender, RoutedEventArgs e) {
view1.MouseWheel += new MouseWheelEventHandler(onMouseWheeled(Cursor,
Time.simTime, view1.MouseWheeledEventArgs)); }
but was having a lot of trouble figuring out how to pass a MouseWheelEventArgs object into the onMouseWheeled method when I'm trying to add the onMouseWheeled method to the MouseWheelEventHandler. Assuming nothing is fundamentally wrong with that sentence, which is nothing more than wishful thinking, The last thing I am trying to figure out is how to get mouse wheel event args so that I can pass it into a method.
Then I tried this:
public event MouseWheelEventHandler MouseWheel;
public virtual void onMouseWheeled(object sender, MouseWheelEventArgs e)
{
Console.WriteLine(e.Delta);
}
//In Main Window Loaded method...
void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
view1.MouseWheel += onMouseWheeled;
}
But I get no output when i scroll the wheel. I assumed this might actually work because view1 is the helix window I'm attaching all of my objects to, as children of view1.
Basically my main questions are:
What does invoke actually do? I only have this running to try to see if its working because onPropertyChanged methods I always use run the Invoke command like so. I'm actually not sure where I'm going with this.
How does the handler work?
How do the event args get called out so that I can use them and pass them as objects to other methods?
Thank you for your time. And Thank you twice for any and all pointers and advice you may give me.
Try to use preview mouse wheel event

BIRT - Dynamically replace Label content

I know one can dynamically change the content of a Label by using an Event Handler, and overriding for example the onRender method, for example:
#Override
public void onRender(ILabelInstance label, IReportContext reportContext)
throws ScriptException {
label.setText("My text!!");
}
But it doesn't seem to work if the label has its Localization TextKey set.
Does anyone already tried to implement it?
Ok ... found a workaround, just remove the Text Key before setting your own text:
#Override
public void onRender(ILabelInstance label, IReportContext reportContext)
throws ScriptException {
label.setTextKey("");
label.setText("My text!!");
}

how to take property value using droptarget?

I am creating a plugin and i need to know the value of porosity of reservoir. If these properties exist somewhere it would be much easier if I could just access them.
So how can we take these value using "drop target button" ?
You must subscribe to the DropTarget.DragDrop event. The following callback method shows you how to get the object dropped on the DropTarget button.
void DropTarget_DragDrop(object sender, DragEventArgs e)
{
Property property = e.Data.GetData(typeof(object)) as Property;
if (property == null)
return;
// Do something with property, like show it in a
// PresentationBox or store it for use later.
}

Flow of initializing objects in XAML?

I'm not sure but from my hours of debugging, this should be the best description of my problem I can give.
I'm creating a WinRT app, there are two pages- Main Page and Details Page. Inside Main Page constructor, I have initialized a listbox. On click of any of the element of listbox, user is taken to the Details page.
I'm just learning all this and design may not be best but here is what I did.
I took a static variable in MainPage.cs, and set it to point to the element which is clicked by the user. Now in the constructor of the Details page, I used this static variable to set the datacontext of Details Page itself.
What flow I'm expecting is:-
MainPage is created first. Listbox is setup.
User will click on any of the element of listbox. Itemclick event handler runs. It will set the static variable (of Mainpage.cs) to hold the infomation which item is clicked and navigate user to the Details page.
In Details page constructor, I have set the datacontext to point to some information based on the value of static variable mentioned in the previous step.
It works for most of the times, but once in like every 5 times, The Details page constructor throws an exception stating the static variable is not initialized yet. Why is Details page's constructor running when I'm starting the app? and why only sometimes? Do I need to set DataContext of Details Page in some other method instead of constructor?
The code is somewhat complex and too much in terms of domain of the problem so I'm avoiding posting it. But if I'm failing to explain the problem please tell, I'll post it keeping it as related as I can.
CODE:-
This is the method called when an item in listbox is clicked--will take user to the Details page.
private void overviewlistbox_Tapped_1(object sender, TappedRoutedEventArgs e)
{
MatchOverview selectedmatch = (sender as ListBox).SelectedItem as MatchOverview;
matchFullDetails = new ObservableCollection<Match>();
foreach (Match m in UpdateController.matchList)
{
if (m.matchDescription == selectedmatch.matchDesc)
{
matchFullDetails.Add(m);
break;
}
}
if(!(matchFullDetails.Count == 0))
this.Frame.Navigate(typeof(Details));
}
This is the constructor for Main Page:-
public static ObservableCollection<Match> matchFullDetails;
public MainPage()
{
matchFullDetails = new ObservableCollection<Match>();
this.InitializeComponent();
UpdateController update = new UpdateController(); // Creating new object will update the overview_list of UpdateController(static list).
overviewlistbox.ItemsSource = UpdateController.overview_list;
}
And this is the code for constructor of details page, where the exception occurs:-
public static ObservableCollection<Match> matchdetails = new ObservableCollection<Match>();
DispatcherTimer dtm_detailspage = null;
public Details()
{
this.InitializeComponent();
matchdetails = MainPage.matchFullDetails; // matchdetails.Last<>() is take because we only need item which is added latest to the collection.
if (matchdetails.Last<Match>().type == "TEST") // Exception is thrown here--Initialization
// error. When I check MainPage.matchFullDetails,
// no data is shown which means its not yet
// initialized. Also the exception is thrown either at
// the start of the app, or when details page is visited. That too once in 4-5 times, not always.
{
matchdetails.Add(matchdetails.First<Match>() as TestMatch);
}
if (matchdetails.Last<Match>().type == "ODI")
{
matchdetails.Add(matchdetails.Last<Match>() as ODIMatch);
}
if (matchdetails.Last<Match>().type == "T20")
{
matchdetails.Add(matchdetails.Last<Match>() as T20Match);
}
}
Exception Screenshot:-
Call Stack data on bug encounter:-
[Cricket Expert.exe!Cricket_Expert.Details.Details() Line 33 + 0x5 bytes
[External Code]
Cricket Expert.exe!Cricket_Expert.Common.SuspensionManager.RestoreFrameNavigationState(Windows.UI.Xaml.Controls.Frame frame) Line 236 + 0x5 bytes
Cricket Expert.exe!Cricket_Expert.Common.SuspensionManager.RestoreAsyn() Line 124 0x8 bytes
Cricket Expert.exe!Cricket_Expert.App.OnLaunched(Windows.ApplicationModel.Activation.LaunchActivatedEventArgs args) Line 74 + 0x5 bytes
[External Code]
MAJOR UPDATE:
I finally found the flaw. If the Details page is still active, and the app is restarted, the problem occurs.
Is there a solution to this problem??
You can pass information on what needs to be displayed on the Details page through the Navigate call and set the DataContext in OnNavigatedTo override to avoid using static variables. Pages don't get created unless you do it specifically e.g. by navigating to one. They might not be recreated if a page has NavigationCacheMode changed from the default (Disabled) so instances of the page can be reused during navigation calls. Ultimately it's hard to say what's wrong but it seems like something in your code and we couldn't help you if you don't share a sample that reproduces the problem.
*EDIT
One way to debug Details being created before MainPage would be to add this code at the beginning of the Details constructor:
if (MainPage.matchFullDetails == null)
{
System.Diagnostics.Debugger.Break();
}
Then look at the Call Stack panel in Visual Studio to see how it gets constructed.
One way to see if matchFullDetails is ever set to null is to search for its assignment (put a cursor on matchFullDetails in Visual Studio code editor and hit Shift+F12).
Another way would be to make matchFullDetails into a property and test it like this:
private static ObservableCollection<Match> _matchFullDetails;
public static ObservableCollection<Match> matchFullDetails
{
get
{
return _matchFullDetails;
}
set
{
if (value == null)
{
System.Diagnostics.Debugger.Break();
}
_matchFullDetails = value;
}
}
*EDIT 2
You can initialize your static property in a static constructor like this:
public static ObservableCollection<Match> matchFullDetails;
static MainPage()
{
matchFullDetails = new ObservableCollection<Match>();
}
public MainPage()
{
this.InitializeComponent();
UpdateController update = new UpdateController(); // Creating new object will update the overview_list of UpdateController(static list).
overviewlistbox.ItemsSource = UpdateController.overview_list;
}
this will prevent the null reference exception but won't fix your problem overall. When your app gets suspended and resumed - you have to restore the full state and it seems like your matchFullDetails collection would need to be serialized and saved to disk when your app gets suspended. Alternatively you might simply ignore the suspension manager call in App.xaml.cs and always start on home page, though that's not a very good experience and I am not sure if it satisfies app certification.

Passing class objects as arguments in Windows 8 App and receive them on click event

The objects passed as arguments are only received an Navigation event. I want to receive them on Click Event,what should I use instead of Parameter??
void App1::MainPage::btuN_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
Variables^ data = (Variables^)e->OriginalSource;
if (data->sNotf!=nullptr)
Frame->Navigate(TypeName(BlankPage3::typeid), data);
}
I used OriginalSource, but it didn't work. Would any one help me? Thanks in Adv
OriginalSource property contains a reference to the object that raised the event. It has nothing to do with navigation parameters.
I'm not exactly sure which parameters you'd like to access in your button click event. The ones passed to your page in its navigation event? In this case you should handle said navigation event, retrieve the parameters there and store them into a private field of your page. In click event you can then read them back from the private field and pass them forward.
On a related note: passing non-basic types as navigation parameters is discouraged. If you need to do that, it's a better idea to just pass the object ids and read their values inside the page from a common repository.
When you navigate to your page, if the parameters from your navigation event are important, you should store them within your page object so it can be accessed later.
//MainPage needs to have a private Variables^ named Info
void MainPage::OnNavigatedTo(NavigationEventArgs^ e)
{
if(e->Parameter)
this->Info = dynamic_cast<Variables^>(e->Parameter);
}
And then access that variable from within your click handler:
void MainPage::btuN_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
if(this->Info)
if (this->Info->sNotf!=nullptr)
Frame->Navigate(TypeName(BlankPage3::typeid), Info);
}