如何从RichTextBox WPF获取文本

问题描述 投票:0回答:1

所以我想做代码编辑器来输入代码,我使用RichTextBox,但我不知道如何从中获取文本,我想使用MVVM模式,我尝试使用事件(但我不知道它是否正确),

<RichTextBox x:Name="CodeField" AcceptsTab="True" Margin="0,51,0,22" RenderTransformOrigin="0.5,0.5" Grid.ColumnSpan="3" TextChanged="CodeField_TextChanged" >
            <RichTextBox.Resources>
                <Style TargetType="{x:Type Paragraph}">
                    <Setter Property="Margin" Value="0"/>
                </Style>
            </RichTextBox.Resources>
        </RichTextBox>
 public string GetSetCode
        {
            get { return codetext; }
            set
            {
                codetext = value;
                OnPropertyChanged(nameof(codetext));
            }
        }
private void CodeField_TextChanged(object sender, TextChangedEventArgs e)
        {
            TextRange textRange = new TextRange(
            // TextPointer to the start of content in the RichTextBox.
            CodeField.Document.ContentStart,
            // TextPointer to the end of content in the RichTextBox.
            CodeField.Document.ContentEnd
            );
            viewModel.GetSetCode= textRange.Text;
            MessageBox.Show(viewModel.codetext);
        }

MessageBox.Show(viewModel.codetext);

MessageBox 显示数据,但是当我尝试这样做时

viewModel.GetSetCode= textRange.Text;

字段代码文本 = null;

c# wpf mvvm richtextbox
1个回答
0
投票

所以答案很简单,可用的必须是静态的MainWindow.xaml.cs

 public partial class MainWindow : Window
{
    MainViewModel viewModel;
    public MainWindow()
    {
        InitializeComponent();
        viewModel = new MainViewModel();
    }

    private void CodeField_TextChanged(object sender, TextChangedEventArgs e)
    {
        
        TextRange textRange = new TextRange(
    // TextPointer to the start of content in the RichTextBox.
    CodeField.Document.ContentStart,
    // TextPointer to the end of content in the RichTextBox.
    CodeField.Document.ContentEnd
    );

        // The Text property on a TextRange object returns a string
        // representing the plain text content of the TextRange.
        viewModel.SetText = textRange.Text;

    }
}

ViewModel.cs

 class MainViewModel : INotifyPropertyChanged
{
    private static string codetext;

    
    public string GetText
    {
        get { return codetext; }
    }
    public string SetText
    {
        set { codetext = value; }
    }

    private LanguageForAPI selectedLanguage;
    public MainViewModel()
    {
        CompiledCommand = new RelayCommand(CallRequest, true);
    }
 private void CallRequest()
    {
        Request request = new Request
        (
            lang: SelectedLanguageForAPI.GetArgument,
            source: GetText,
            input: "",
            memory_limit: 262144,
            time_limit: 5,
            context: "",
            callback: ""
        );
        MessageBox.Show(GetText);
    }
 }
   
© www.soinside.com 2019 - 2024. All rights reserved.