C
C#2mo ago
stigzler

✅ Force Binding update in ViewModel where UpdateSourceTrigger==LostFocus

Hi folks - sorry to keep posting, but WPF is proving a difficult mare to break in.... I have a text editor control whose text is bound to a ViewModel Property and UpdateSourceTrigger set to LostFocus It's not possible to set it to PropertyChanged because it compares the text against a default text set which can be really long. If set to PropertyChanged, it introduces too much lag. Relevant code: View:
<syncfusion:EditControl x:Name="CodeEC" Grid.Row="4"
Text="{Binding SelectedGistFileViewModel.Content, Mode=TwoWay, UpdateSourceTrigger=LostFocus}
</syncfusion:EditControl>
<syncfusion:EditControl x:Name="CodeEC" Grid.Row="4"
Text="{Binding SelectedGistFileViewModel.Content, Mode=TwoWay, UpdateSourceTrigger=LostFocus}
</syncfusion:EditControl>
ViewModel:
public GistFileViewModel SelectedGistFileViewModel { get => selectedGistFileViewModel; set => SetProperty(ref selectedGistFileViewModel, value); }
public GistFileViewModel SelectedGistFileViewModel { get => selectedGistFileViewModel; set => SetProperty(ref selectedGistFileViewModel, value); }
GistFileViewModel :
public string Content {
get { return content; }
set
{
if (value != ReferenceGistFile.Content) HasChanges = true;
else HasChanges = false;

SetProperty(ref content, value);
ParentGistViewModel.HasChanges = ParentGistViewModel.GistHasChanges();
}
}
public string Content {
get { return content; }
set
{
if (value != ReferenceGistFile.Content) HasChanges = true;
else HasChanges = false;

SetProperty(ref content, value);
ParentGistViewModel.HasChanges = ParentGistViewModel.GistHasChanges();
}
}
The issue is, I have a manual Save button. If I click this, the text control does not seem to loose focus and thus the bound property does not get updated. I'm trying to avoid View code behind as much as possible. The Save button click calls a Command in the ViewModel. How can I go about manually updating either the Property, or forcing the text control to lose focus? Tried a few bit scraped from the interweb, but no joy.
1 Reply
stigzler
stigzler2mo ago
Caved in and did it in the code behind:
private void SaveBT_Click(object sender, RoutedEventArgs e)
{
BindingExpression expr = CodeEC.GetBindingExpression(EditControl.TextProperty);
expr.UpdateSource();
}
private void SaveBT_Click(object sender, RoutedEventArgs e)
{
BindingExpression expr = CodeEC.GetBindingExpression(EditControl.TextProperty);
expr.UpdateSource();
}
Unless anyone can tell me how to do it properly (if 'properly' even is doing eveything in the ViewModel?)