How to emulate a console in WPF?

后端 未结 3 2085
北海茫月
北海茫月 2020-12-29 09:29

I\'d like some tips-in-the-right-direction or even ready solutions to this problem and I\'m pretty stuck (I\'m just beginner/intermediate):

I\'m trying to implement

3条回答
  •  执笔经年
    2020-12-29 10:27

    Given that you want to emulate a console, I'd do it like this. Note that you'd have to handle the commands and outputting the results yourself.

    page.xaml

    
        
            
                
                    
                        
                            
                                
                            
                        
                    
                    
                
            
        
    
    

    page.xaml.cs

    public partial class MainWindow : Window
    {
        ConsoleContent dc = new ConsoleContent();
    
        public MainWindow()
        {
            InitializeComponent();
            DataContext = dc;
            Loaded += MainWindow_Loaded;
        }
    
        void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            InputBlock.KeyDown += InputBlock_KeyDown;
            InputBlock.Focus();
        }
    
        void InputBlock_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                dc.ConsoleInput = InputBlock.Text;
                dc.RunCommand();
                InputBlock.Focus();
                Scroller.ScrollToBottom();
            }
        }
    }
    
    public class ConsoleContent : INotifyPropertyChanged
    {
        string consoleInput = string.Empty;
        ObservableCollection consoleOutput = new ObservableCollection() { "Console Emulation Sample..." };
    
        public string ConsoleInput
        {
            get
            {
                return consoleInput;
            }
            set
            {
                consoleInput = value;
                OnPropertyChanged("ConsoleInput");
            }
        }
    
        public ObservableCollection ConsoleOutput
        {
            get
            {
                return consoleOutput;
            }
            set
            {
                consoleOutput = value;
                OnPropertyChanged("ConsoleOutput");
            }
        }
    
        public void RunCommand()
        {
            ConsoleOutput.Add(ConsoleInput);
            // do your stuff here.
            ConsoleInput = String.Empty;
        }
    
    
        public event PropertyChangedEventHandler PropertyChanged;
        void OnPropertyChanged(string propertyName)
        {
            if (null != PropertyChanged)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    

提交回复
热议问题