在WPF中,如何实现文件上传控件(文本框和浏览文件的按钮)?

Rel*_*ity 5 wpf file-upload mvvm

我有一个WPF,MVVM应用程序.

我需要与asp.net中的"文件上传"控件相同的功能.

有人能告诉我如何实现它吗?

 <StackPanel Orientation="Horizontal">
                <TextBox Width="150"></TextBox>
                <Button Width="50" Content="Browse"></Button>
</StackPanel>
Run Code Online (Sandbox Code Playgroud)

我有这个xaml ...但是当你点击按钮时如何拥有"浏览窗口"?

Job*_*Joy 9

您可以使用OpenFileDialog类来获取文件选择对话框

OpenFileDialog fileDialog= new OpenFileDialog(); 
fileDialog.DefaultExt = ".txt"; // Required file extension 
fileDialog.Filter = "Text documents (.txt)|*.txt"; // Optional file extensions

fileDialog.ShowDialog(); 
Run Code Online (Sandbox Code Playgroud)

阅读内容:您将从OpenFileDialog获取文件名并使用它来对其执行IO操作.

 if(fileDialog.ShowDialog() == DialogResult.OK)
  {
     System.IO.StreamReader sr = new 
     System.IO.StreamReader(fileDialog.FileName);
     MessageBox.Show(sr.ReadToEnd());
     sr.Close();
  }
Run Code Online (Sandbox Code Playgroud)

  • `DialogResult.OK`不存在,但我使用`bool?res = fileDialog.ShowDialog(); if(res.HasValue && res.Value){...}` (4认同)