To access the text from your view model, you'll want to use data binding. Here's how to set it up:
1. Update your XAML
Add a Text binding to your TextBox:
<TextBox Grid.Column="0"
x:Name="ChatInput"
Text="{Binding ChatInputText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
Margin="0,0,5,0"
VerticalContentAlignment="Center"
Padding="5"
Background="{StaticResource SurfaceContainerLowBrush}"
Style="{StaticResource TextBoxBase}"
Foreground="{StaticResource OnSurfaceBrush}"
BorderBrush="{StaticResource OnSurfaceVariantBrush}"
BorderThickness="1" />
2. Add a property to your view model
public class YourViewModel : INotifyPropertyChanged
{
private string _chatInputText = string.Empty;
public string ChatInputText
{
get => _chatInputText;
set
{
if (_chatInputText != value)
{
_chatInputText = value;
OnPropertyChanged();
}
}
}
public event PropertyChangedEventHandler? PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
Don't forget to add using System.ComponentModel; and using System.Runtime.CompilerServices; at the top of your view model file.
Key points:
Mode=TwoWay ensures changes flow both ways between the TextBox and view model
UpdateSourceTrigger=PropertyChanged updates the view model property as the user types (instead of waiting for focus to leave the TextBox)
- The
INotifyPropertyChanged implementation allows the UI to update when you programmatically change ChatInputText in your view model
Now you can access and modify the text through the ChatInputText property in your view model.