WPF:ICommand,在文本框中打开一个txt文件

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

我在这里有一个小问题,我必须用基本的WPF记事本类的东西打开(读取)文本文件,但必须与ICommand接口有关。问题是,当我选择要打开的txt文件时,什么都没有发生,我只是看到一个空的记事本。有什么解决办法吗?这是代码:

    public class OpenCommand : ICommand
{

    public bool CanExecute(object parameter)
    {
        return true;
    }

    public event EventHandler CanExecuteChanged;


    public void Execute(object parameter)
    {
        OpenFileDialog op = new OpenFileDialog();

        op.Filter = "textfile|*.txt";
        op.DefaultExt = "txt";
        if(op.ShowDialog() == true)
        {

            File.ReadAllText(op.FileName);

        }

    }
}

也许此时我不是真的不知道bindig。

                <MenuItem Header="File" >
                <MenuItem Header="New"/>
                <MenuItem Header="Open..." Command="{Binding MyOpenCommand}" CommandParameter="{Binding ElementName=textbox2, Path=Text}"/>
                <MenuItem Header="Save..." Command="{Binding MySaveCommand}" CommandParameter="{Binding ElementName=textbox2, Path=Text}"/>
                <Separator/>
                <MenuItem Header="Exit..." Command="{Binding MyExitCommand}"/>

            </MenuItem>

有绑定,我想在“ textbox2”中查看文件

<TextBox x:Name="textbox2" DockPanel.Dock="Left" 
             Grid.IsSharedSizeScope="True"
             AcceptsReturn="True"/> 
wpf xaml binding icommand
1个回答
0
投票

您必须将TextBox绑定到文本文件的内容。

下面的示例使用可重用的RelayCommand,它接受委托。这使得将结果传递到绑定源更加优雅。

ViewModel.cs

public class ViewModel : INotifyPropertyChanged
{
  public ICommand OpenCommand => new RelayCommand(ExecuteOpemFile);
  public ICommand ExitCommand => new RelayCommand(param => Application.Current.MainWindow.Close());

  private string textFileContent;   
  public string TextFileContent
  {
    get => this.textFileContent;
    set 
    { 
      this.textFileContent= value; 
      OnPropertyChanged();
    }
  }

  public ExecuteOpemFile(object commandParameter)
  {
    OpenFileDialog op = new OpenFileDialog();
    op.Filter = "textfile|*.txt";
    op.DefaultExt = "txt";

    if(op.ShowDialog() == true)
    {
      this.TextFileContent = File.ReadAllText(op.FileName);
    }
  }

  public event PropertyChangedEventHandler PropertyChanged;
  protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
  {
    this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
  }
}

RelayCommand.csMicrosoft Docs: Relaying Command Logic复制的实现。

public class RelayCommand : ICommand
{
  #region Fields

  readonly Action<object> _execute;
  readonly Predicate<object> _canExecute;

  #endregion // Fields 

  #region Constructors

  public RelayCommand(Action<object> execute) : this(execute, null)
  {
  }

  public RelayCommand(Action<object> execute, Predicate<object> canExecute)
  {
    if (execute == null)
      throw new ArgumentNullException("execute");
    _execute = execute;
    _canExecute = canExecute;
  }

  #endregion // Constructors 

  #region ICommand Members

  [DebuggerStepThrough]
  public bool CanExecute(object parameter)
  {
    return _canExecute == null ? true : _canExecute(parameter);
  }

  public event EventHandler CanExecuteChanged
  {
    add { CommandManager.RequerySuggested += value; }
    remove { CommandManager.RequerySuggested -= value; }
  }

  public void Execute(object parameter)
  {
    _execute(parameter);
  }

  #endregion // ICommand Members 
}

MainWindow.xaml

<Window>
  <Window.DataContext>
    <ViewModel />
  </Window.DataContext>

  <StackPanel>
    <Menu>
      <MenuItem Command="{Binding OpenCommand}" />
      <MenuItem Command="{Binding ExitCommand}" />
    </Menu>

    <TextBox Text="{Binding TextFileContent}" />
</Window>
© www.soinside.com 2019 - 2024. All rights reserved.