In my sample application, I just added a RichTextBox , and Button , Button bound to Command "SuperScriptText", which is called when the button is pressed, and CommandParameter , which is bound to RichTextBox and passed as a parameter to the "SuperScriptText" Command
MainWindow.xaml
<Grid> <StackPanel Orientation="Horizontal"> <RichTextBox Name="rtb" Height="100" Width="300" HorizontalAlignment="Left" VerticalAlignment="Top" ></RichTextBox> <Button Command="{Binding SuperScriptText}" CommandParameter="{Binding ElementName=rtb}" Height="25" Width="100" HorizontalAlignment="Left" VerticalAlignment="Top" Content="SuperScript"/> </StackPanel> </Grid>
In ViemModel, an important part of public ICommand SuperScriptText { get; set; } public ICommand SuperScriptText { get; set; } public ICommand SuperScriptText { get; set; } , which is initialized using the DelegateCommand<FrameworkElement> , now here the FrameworkElement allows the View to pass the RichTextBox as a CommandParameter
MainWindowViewModel.cs
public class MainWindowViewModel : BindableBase { public MainWindowViewModel() { this.SuperScriptText = new DelegateCommand<FrameworkElement>(SuperScriptTextCommandHandler); } private void SuperScriptTextCommandHandler(FrameworkElement obj) { var rtb = obj as RichTextBox; if (rtb != null) { var currentAlignment = rtb.Selection.GetPropertyValue(Inline.BaselineAlignmentProperty); BaselineAlignment newAlignment = ((BaselineAlignment)currentAlignment == BaselineAlignment.Superscript) ? BaselineAlignment.Baseline : BaselineAlignment.Superscript; rtb.Selection.ApplyPropertyValue(Inline.BaselineAlignmentProperty, newAlignment); } } public ICommand SuperScriptText { get; set; } }
And here is the most important part providing the DataContext for MainWindow
MainWindow.xaml.cs
public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); this.DataContext = new MainWindowViewModel(); } }
source share