开发者

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

开发者 https://www.devze.com 2023-02-07 23:02 出处:网络
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 ?

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>
</StackPan开发者_StackOverflow中文版el>

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


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();
}


<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.

0

精彩评论

暂无评论...
验证码 换一张
取 消