Silverlight Textbox Binding TextChanged Event
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();
}
}
}
No comments:
Post a Comment