Reputation: 4527
I have a simple Silverlight TextBox that receives text via a barcode scanner. It basically functions like a paste. Anyway, I would like my TextBox, when it notices a change in its contents, to run LoadScannedResults()
in my ViewModel. By default, when I do a TwoWay Binding, the ScanDocumentNumber
in my ViewModel is triggered when I click away from my page. I can get the desired effect if I put in tbDocumentNumber_TextChanged()
in my codebehind but then I hit my ViewModel twice - once on TextChanged and then again when I click away from the page. I would like it to only occur on TextChanged. Thank you for your help!
This is my Home.xaml
<TextBox Name="tbDocumentNumber" Margin="3" VerticalAlignment="Center" Text="{Binding ScanDocumentNumber, Mode=TwoWay}" Width="150" />
Here is my Home.xaml.cs
public Home()
{
m_DataContext = HomeViewModel.Current;
this.DataContext = m_DataContext;
InitializeComponent();
tbDocumentNumber.TextChanged += new TextChangedEventHandler(tbDocumentNumber_TextChanged);
}
private void tbDocumentNumber_TextChanged(object sender, TextChangedEventArgs e)
{
object focusObj = FocusManager.GetFocusedElement();
if (focusObj != null && focusObj is TextBox)
{
var binding = (focusObj as TextBox).GetBindingExpression(TextBox.TextProperty);
binding.UpdateSource();
tbDocumentNumber.SelectAll();
}
}
This is my HomeViewModel.cs
private string m_ScanDocumentNumber;
public string ScanDocumentNumber
{
get { return m_ScanDocumentNumber; }
set
{
if (m_ScanDocumentNumber == null || !m_ScanDocumentNumber.Equals(value))
{
m_ScanDocumentNumber = value.Trim();
RaisePropertyChanged("ScanDocumentNumber");
}
if (m_ScanDocumentNumber != null && m_ScanDocumentNumber != "")
{
LoadScannedResults();
}
}
}
Upvotes: 1
Views: 1454
Reputation: 1497
I am not sure but UpdateSourceTrigger might help in this case.
The TextBox.Text property has a default UpdateSourceTrigger value of LostFocus. This means if an application has a TextBox with a data-bound TextBox.Text property, the text you type into the TextBox does not update the source until the TextBox loses focus (for instance, when you click away from the TextBox).
If you want the source to get updated as you are typing, set the UpdateSourceTrigger of the binding to PropertyChanged. In the following example, the Text properties of both the TextBox and the TextBlock are bound to the same source property. The UpdateSourceTrigger property of the TextBox binding is set to PropertyChanged.
<TextBox Name="itemNameTextBox"
Text="{Binding Path=ItemName,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
Upvotes: 1