I am struggling to find a good solution to a nagging problem we are experiencing. We have a multiline textbox in a WPF app using MvvmLight to implement the MVVM design pattern. The textbox is bound to a property in the viewmodel via a two-way binding. Both the end user and the viewmodel can update the bound property. Whenever the viewmodel updates the bound property, the NotifyPropertyChanged event is raised (via the MvvmLight Set() method.) When this happens, the textbox is properly updated but the caret moves to the front of the text. We have a method in the viewmodel that invokes an event that has an eventhandler in the codebehind. The eventhandler moves the caret to the end of the text. The problem is, there are many places throughout the code that we have to remember to execute that method. It seems to me there ought to be a way to have the view automatically move the caret to the end every time the NotifyPropertyChanged event is raised. I found one 12 year old example that does what I want here. But I've run into a conflict. Our view defines the DataContext thusly:
<UserControl x:Class="CaptionNet.Wpf.Captioning.CaptioningView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:CaptionNet.Wpf.Captioning"
d:DataContext="{Binding CaptioningViewModel, Source={StaticResource Locator}}"
DataContext="{Binding CaptioningViewModel, Source={StaticResource Locator}}"
xmlns:dp="clr-namespace:CaptionNet.Wpf.DependencyProperties"
xmlns:cmd="http://www.galasoft.ch/mvvmlight"
xmlns:interactivity="http://schemas.microsoft.com/expression/2010/interactivity"
mc:Ignorable="d"
d:DesignHeight="500" d:DesignWidth="500"
AutomationProperties.AutomationId="CaptioningPane">
The sample code defines the DataContext this way:
<UserControl.DataContext>
<local:CaptioningViewModel CaptionsChanged="ScrollToEnd" />
</UserControl.DataContext>
The CaptionsChanged event is defined in the CaptioningViewModel. The ScrollToEnd is the eventhandler defined in the backend.
I can only define the DataContext one way. Either the original way or the example's way but not both. If I use the original way, I can't figure out how to subscribe the ScrollToEnd eventhandler to the CaptionsChanged event. If I use the example's way, I can't figure out how to bind the datacontext to the CaptioningViewModel. I've searched all day and have been unable to figure this out. Your help would be greatly appreciated.
Add a binding on TextBox.CaretIndex.