In WPF, how to implement a file upload control (textbox and a button to browse file)?

我的未来我决定 提交于 2020-12-03 04:26:11

问题


I have a WPF,MVVM application.

I need the functionality same as "File Upload" control in asp.net.

Can somebody tell me how to implement that ?

 <StackPanel Orientation="Horizontal">
                <TextBox Width="150"></TextBox>
                <Button Width="50" Content="Browse"></Button>
</StackPanel>

I have this xaml...but how to have that "browse window" when you click button ?


回答1:


You can use OpenFileDialog class to get a file choose dialog

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

fileDialog.ShowDialog(); 

To read the content : You will get the filename from the OpenFileDialog and use that to do what IO operation on it.

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



回答2:


<StackPanel Orientation="Horizontal">
     <TextBox Width="150"></TextBox>
     <Button Width="50" Content="Browse" Command="{Binding Path=CommandInViewModel}"></Button>
</StackPanel>

Declare a command in your view model and bind it in the view as I have done inside button. Now you will get control in the code once user will click the button. In that code create a window and launch it. Once user will close the window, read the contents and do whatever you want.



来源:https://stackoverflow.com/questions/4876833/in-wpf-how-to-implement-a-file-upload-control-textbox-and-a-button-to-browse-f

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!