【问题标题】:WPF: ICommand, open a txt file in textboxWPF:ICommand,在文本框中打开一个txt文件
【发布时间】:2020-08-08 05:27:51
【问题描述】:

我这里有个小问题,我必须在基本的 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);

        }

    }
}

也许绑定不是我现在真的不知道。

                <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"/> 

【问题讨论】:

  • 你没有将File.ReadAllText(op.FileName);结果赋值给任何变量

标签: wpf xaml binding icommand


【解决方案1】:

您必须将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.cs
Microsoft 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>

【讨论】:

  • 我做到了,但是当我使用 Open MenuItem 时没有任何反应,我的意思是对话框出现了,我可以选择我要打开的 txt,但是没有任何反应,它没有出现在文本框中跨度>
  • 对不起,我无法复制它。对我来说它有效。请检查您的装订是否有任何拼写错误。在调试模式下运行应用程序以查看是否遇到任何异常。确保文件不为空。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-25
  • 1970-01-01
  • 2011-12-20
  • 2017-05-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多