In silverlight 3 I am doing something like :
//currentDataForm.itemssource = currentCollisionDisplay;
//<input:AutoCompleteBox Width="74" x:Name="InvolvedCnt" Text="{Binding involvedCnt, Mode=TwoWay}"
...
for (int i = 0; i < driverNums; i++)
{
AddCollisionVehicle_Click(null, null);
}
...
private void AddCollisionVehicle_Click(object sender, RoutedEventArgs e)
{
currentCollisionDisplay.involvedCnt ++;
(df_collision.FindNameInContent("InvolvedCnt") as AutoCompleteBox).Text = currentCollisionDisplay.involvedCnt.ToString();
(df_collision.FindNameInContent("InvolvedCnt") as AutoCompleteBox).UpdateLayout();
string testString = (df_collision.FindNameInContent("InvolvedCnt") as AutoCompleteBox).Text;
}
so the initial value of the autocompletebox is "1".
if driverNums = 1 then the autocompletebox.text is 2.. which is correct
but if driverNums = 2 then the autocompletebox.text is 2.. which is wrong.
I changed the autocompletebox text field within an array, but this is not updated properly.. does anybody know how to fix this issue?
Strange thing is if i check testString variable, the value is correct..
This appears to be a known issue. See http://forums.silverlight.net/forums/p/199616/519232.aspx
A workaround that worked in my application is to clear out the Text property and then set it again using Dispatcher.BeginInvoke, i.e. something like this:
autoCompleteBox.Text = null;
Dispatcher.BeginInvoke(() =>
autoCompleteBox.Text = currentCollisionDisplay.involvedCnt.ToString());
I've only done this in one scenario so I don't know for sure if it'll work for you. My application also used bindings (I called ClearValue and then SetBinding).
You need to use the method "ValueMemberBrinding"
<toolkit:AutoCompleteBox x:Name="InvolvedCnt" ValueMemberBinding="{Binding Name}"/>
Related
I am working in Xamarin but I believe this applies to any UWP application using XAML.
First I have two ContentPages. On the first page, I want to pass some data to the second page, so I do this as part of the navigation:
async void BuyTickets(object sender, EventArgs e)
{
var ticketOrderTotal = new TicketOrder
{
OrderTotal = lblOrderAmount.Text,
OrderTotalList = ticketsPrices.Where(o => o.TicketQuantity > 0).ToList<Ticket>()
};
var paymentPage = new PaymentPage();
paymentPage.BindingContext = ticketOrderTotal;
await Navigation.PushAsync(paymentPage);
}
The above works fine in XAML. On the second page (PaymentPage), I am able to reference the BindingContext like this, for example, and the Text property is correct:
<Label x:Name="lblOrderAmount" Text="{Binding OrderTotal}" />
What I would like to do is access the "{Binding OrderTotal}" value in the C# code-behind of the second page. I found a way to do this, too, but it just does not seem optimal. This is the kludge I have in place:
<Label x:Name="lblOrderAmount" Text="{Binding OrderTotal}" BindingContextChanged="GetChargeAmount" />
And this is the code-behind for the label:
public static string m_charge_amount = "";
...
private void GetChargeAmount(object sender, EventArgs e)
{
var lbl = ((Label)sender);
m_charge_amount = lbl.Text;
}
So my question is this: is there a better way to do this? It is particularly hard to research as XAML seems to be rooted in WPF, Silverlight, Xamarin, Windows 8, and now Windows 10 (UWP). It is all over the place. I am constantly fighting with the framework to do things that I think should be quite easy to do....like this. Please help but do be nice.
Thank you.
EDIT:
Per #Jason's comment, you can pass an object to the page constructor, and that will work. This is what the re-worked function looks like now:
async void BuyTickets(object sender, EventArgs e)
{
var ticketOrderTotal = new TicketOrder
{
OrderTotal = lblOrderAmount.Text,
OrderTotalList = ticketsPrices.Where(o => o.TicketQuantity > 0).ToList<Ticket>()
};
var paymentPage = new PaymentPage(ticketOrderTotal);
paymentPage.BindingContext = ticketOrderTotal;
await Navigation.PushAsync(paymentPage);
}
And then the result from debugging:
instead of having PageA set PageB's BindingContext, instead pass the ticketOrderTotal object as a parameter on PageB's constructor. Then PageB can set it's own BindingContext as well as keep a local reference to the ticketOrderTotal object.
I see here lot of similar question, but I still not find answer that help me in situation.
I have two frame(lets say FrameChild), one is "in" another(practically FrameChild is in this frame, lets say FrameMain).
When I insert all parameters in FrameChild and tap on button witch is on bottom of FrameMain I call method that return string...
Now when i get string i need to change textbox text in FrameChild
I have tray many way.
First idea was something like:
FrameChild frm = new FrameChild;
frm.textbox.text = "somestring";
But nothing happen.
Than i thing use some property.
in FrameChield:
public string setTicNo
{
set
{
textBox.Text = value;
}
}
in FrameMain:
FrameChild frm = new FrameChild;
frm.setTicNo = "somestring";
When i debbuging I get value, but textbox still is empty...
On the end I try to bind textbox text on setTicNo;
public string setTicNo
{
get
{
return setTicNo;
}
set
{
setTicNo = value;
}
}
Xaml:
Text = {Binding setTicNo, Mode=TwoWay,UpdateSourceTrigger=Explicit}
(here i try use more bindings, but every time i get infinite loop.
Please help , I not have more ideas..
Thanx
Did you try building a single view model and bind it to both frames, if it was passed by ref which is the default it will change the value once you do.
A side note implement a INOTIFYPROPERTYCGANGED in the View model
Hope you can help me whit this :)
I WANT TO: give the following values to four different radio buttons: 30, 50, 100 and 200 (doesn't really matter what the values is for now). Right now I need to go into the code and change the number my self. I want these radio buttons to do the job when checked.
I will paste the code here. Can you please be very spesific when explaining this to me (if you can and bother to do so).
Thank you!
//Method for establishing connection to database.
// Sette parameter for limit
public static MongoDatabase GetDatabase(string searchText)
{
/* try
{*/
TweetOC.Clear();
MongoServerSettings settings = new MongoServerSettings();
settings.Server = new MongoServerAddress("xxxx", xxxx);
MongoServer server = new MongoServer(settings);
MongoDatabase database = server.GetDatabase("tweet_database");
var collection = database.GetCollection<Tweets>("docs");
System.Console.WriteLine("5");
var query = Query.And(Query.Matches("text", searchText),
Query.NE("geo_enabled", false));
System.Console.WriteLine("6");
//var match = Query.ElemMatch("text", query);
var cursor = collection.Find(query);
cursor.SetLimit(30);
System.Console.WriteLine("7");
//Puts the result from the last query into a list.
var resultList = cursor.ToList();
//Iterates over the previous mentioned list and inserts the content into the ObservableCollcetion created earlier.
foreach (var item in resultList)
TweetOC.Add(item);
System.Console.WriteLine(TweetOC.Count);
return database;
}
I HAVE TO CHANGE CURSOR.LIMIT(manually) ALL THE TIME. I WANT THIS NUMBER TO CHANGE AUTOMATICALLY WHEN A RADIO BUTTON IS CHECKED.
THE METHOD AND XAML WILL FOLLOW:
// I want this to be if radiobutton is 20, then this should be sent to cursor.set limit. I cannot make another string in database.cs without getting an error.
/* Private void RadioButton_Checked(object sender, RoutedEventArgs e)
{
var radioButton = sender as RadioButton;
if (radioButton == 20)
return;
int intIndex = Convert.ToInt32(radioButton.Content.ToString(Cursor.SetLimit));
}
* Remember Checked="RadioButton_Checked" in the XAML if you want to try
*/
XAML for one of the four buttons:
<RadioButton Content="RadioButton" Grid.Column="2" HorizontalAlignment="Left"
Margin="20,116,0,0" Grid.Row="2" VerticalAlignment="Top"/>
HOW SHOULD THIS ACTUALLY LOOK TO GET IT WORKING? PLEASE EDIT THE CODE (if you bother) SO I CAN SEE AND UNDERSTAND THIS.
THANKS AGAIN!
To do this in an MVVM friendly way, bind the IsChecked property like this:
IsChecked="{Binding Path=CursorLimit, Converter={StaticResource ParamToIntConverter}, ConverterParameter=10}"
Set the parameter to the correct value for the given radio button, of course. If you are not familiar with converters, you need a line in your resources like (assuming you have the local xmlns set up to point to the converter namespace):
<local:ParamToIntConverter x:Key="ParamToIntConverter"/>
Then your converter looks like:
public class ParamToIntConverter : IValueConverter
{
public object Convert (...)
{
return value.Equals(int.Parse((string)parameter));
}
public object ConvertBack(...)
{
if ((bool)value)
return int.Parse((string)parameter);
else
return Binding.DoNothing;
}
}
Your xmal code:
<RadioButton Content="RadioButton" Grid.Column="2" HorizontalAlignment="Left"
Margin="20,116,0,0" Grid.Row="2" VerticalAlignment="Top" Checked="RadioButton_Checked" />
Your *.cs code:
private void RadioButton_Checked(object sender, RoutedEventArgs e)
{
// ... do what you need for this button
}
Use different Checked="[insert_method_name]" template with equal method names in your *.cs file and do what you need in each method.
Also you can try to make it as in this http://www.dotnetperls.com/radiobutton-wpf example.
EDIT - Sorry folks, i guess i wanted to "obscure" my work code too much... i don't know why it got so many downvotes but anyway. see below for update/edit with actual code.
I am trying to insert a piece of text into an existing section of a line (<data) which resides at the beginning of a line in my RichTextBox control. However, whenever i do that in the following manner:
private void AddSelectedIntellisense(object sender, EventArgs e)
{
ToolStripItem x = sender as ToolStripItem;
int cursorpos = this.txt_Body.SelectionStart;
string final = this.txt_Body.Text.Insert(cursorpos, x.Text);
//final var at breakpoint is equal to "<data log=\"Original\""
//then i assign it/that to the RTB.Text
this.txt_Body.Text = final;
//when checked with breakpoint, this.txt_Body.Text is equal to
//"log=\"\"<data log=\"Original\""
this.txt_Body.SelectionStart = cursorpos + x.Text.Length;
}
I am thinking that it is the < character that is causing issues when i assign the string to the .Text property (because if i replace the < with a [ in my logic, no problems), but i don't know how to fix it... if you could help me i would really appreciate it.
I also checked all of the indexes manually and they all lign up perfectly... so i don't know why the RTB.Text value is different than the string but if someone knows please tell me.
Cheers!
You are first setting:
txt = this.RTB1.Text.Substring(starts, length);
Then on the next line you are replacing the value of txt:
txt = this.RTB1.Text.Insert(index,"log='test'></data>");
You are probably looking to concatenate the strings:
string txt = this.RTB1.Text.Substring(starts, length);
txt += this.RTB1.Text.Insert(index,"log='test'></data>");
this.RTB1.Text = txt;
Ok folks... i suppose i'll give it to Aaron, since it's like somewhat related and nobody else answered.
The answer was:
I am using the RTB.On_TextChanged event to fire off the intellisense based on a condition. However, because i am also setting text the RTB.Text value within the Intellisense, the condition became true twice and added the specific text twice. So i setup a flag when i add intellisense text and check it in the on_textchanged event.
Cheers and sorry for the confusion.
In my VS 2012 WPF project, I have a customized textbox class called TextBoxDX that adds an AutoSelect feature. No problem. I have another class based on TextBoxDX called IntBox which only allows integers. That's where our story begins. Both classes are used in binding situations like so:
<local:TextBoxDX Grid.Row="0" Grid.Column="1" x:Name="txtBox_singlesName" Width="320" HorizontalAlignment="left" Text="{Binding SelectedItem.name, ElementName=listBoxSingles, Mode=OneWay}"/>
<local:IntBox x:Name="intBox_heightin" Width="60" AllowZeroValue="True" MaxLength="2" Text="{Binding SelectedItem.heightin, ElementName=listBoxSingles, Mode=OneWay}" MinVal="0" MaxVal="11"/>
Pretty sure most of that is irrelevant except for the binding. Both work fine in that they change their text corresponding to ListBox selections. But in the IntBox class, I had to add code for allowing only integers. In order to do that, I tapped into the TextChanged event in my IntBox class. The end result is this:
using System;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace Herculese
{
public class IntBox : TextBoxDX
{
//INIT PROPERTIES
private int _MaxVal = 0;
private int _MinVal = 0;
private bool _AllowZeroValue = false;
//INIT STRING TO KEEP TRACK OF TEXT BEFORE CHANGES
private string originalText;
public IntBox()
{
//ADD TO TEXTCHANGED HANDLER
TextChanged += new TextChangedEventHandler(My_OnTextChanged);
//STORE ORIGINAL TEXT
originalText = this.Text;
}
//EVENT HANDLER WHEN TEXT IS CHANGED
private void My_OnTextChanged(object sender, EventArgs e)
{
//IF THERE IS TEXT IN THE BOX,
MessageBox.Show("yee");
if (this.Text.Length > 0)
{
//REMOVE SPACES AND LEADING ZEROS FROM STRING
if (!_AllowZeroValue)
this.Text = this.Text.TrimStart('0');
this.Text = Regex.Replace(this.Text, #"\s+", "");
//IF VALUE ISN'T NUMERICAL OR NOTHING IS LEFT AFTER REMOVING ZEROS AND SPACES, CHANGE TEXT BACK TO ORIGINAL
Regex regex = new Regex("[^0-9]+");
if (regex.IsMatch(this.Text) || this.Text.Length < 1)
{
this.Text = originalText;
System.Media.SystemSounds.Beep.Play();
}
//IF VALUE IS NUMERICAL,
else
{
//MAKE SURE VALUE IS WITHIN ACCEPTED RANGE. IF NOT, CHANGE IT TO HIGHEST/LOWEST AVAILABLE RESPECTIVELY
int intText;
intText = Convert.ToInt32(this.Text);
if (intText > _MaxVal)
{
this.Text = _MaxVal.ToString();
System.Media.SystemSounds.Beep.Play();
}
else if (intText < _MinVal)
{
this.Text = _MinVal.ToString();
System.Media.SystemSounds.Beep.Play();
}
//SUCCESS! UPDATE ORIGINAL TEXT WITH NEW VALID VALUE.
else originalText = this.Text;
}
}
}
//PROVIDE GET/SET PROPERTIES
public int MaxVal
{
get { return _MaxVal; }
set { _MaxVal = value; }
}
public int MinVal
{
get { return _MinVal; }
set { _MinVal = value; }
}
public bool AllowZeroValue
{
get { return _AllowZeroValue; }
set { _AllowZeroValue = value; }
}
}
}
As you can see, I had a great time in the TextChanged of my IntBox. Wild parties, you name it. Suddenly I realized that binding for IntBox wasn't working anymore. I could manually change the text just fine. It only accepted integers and worked like a charm. But changing the ListBox selection no longer updated the text. If I removed the code in My_OnTextChanged, the binding worked again. I figured my code was causing the problem. So I came back today with a fresh head and realized something weird.
If I remove the code in My_OnTextChanged and replace it with a MessageBox, the binding works and the message box appears. Makes perfect sense and furthers the idea that my code is causing the issue. Now for the weirdness: if I put the code back into the event after the MessageBox code, binding is broken again and the MessageBox never shows meaning the event never fires. All I can say to that is... HUUUUH?! I've recreated this several times just to be sure I'm not crazy. The only other thing I could think of is a conflict with the TextBoxDX that it inherits from so I made it inherit directly from TextBox and got the same results... Anybody got a clue on this one?
You are assigning a new value to Text which is removing the original binding as you have replaced it with a new string.
Instead of using this.Text = "Somthing" try using base.SetCurrentValue(TextProperty, value);
Example:
//IF VALUE ISN'T NUMERICAL OR NOTHING IS LEFT AFTER REMOVING ZEROS AND SPACES, CHANGE TEXT BACK TO ORIGINAL
Regex regex = new Regex("[^0-9]+");
if (regex.IsMatch(this.Text) || this.Text.Length < 1)
{
// this.Text = originalText;
base.SetCurrentValue(TextProperty, originalText);
System.Media.SystemSounds.Beep.Play();
}
SetCurrentValue Sets the value of a dependency property without changing its value source.