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

8
我有一个WPF,MVVM应用程序。
我需要与asp.net中的“文件上传”控件相同的功能。
有人可以告诉我如何实现吗?
 <StackPanel Orientation="Horizontal">
                <TextBox Width="150"></TextBox>
                <Button Width="50" Content="Browse"></Button>
</StackPanel>

我有这个 XAML 代码……但是当你点击按钮时如何得到“浏览窗口”?

2个回答

14

你可以使用 OpenFileDialog 类来获取一个文件选择对话框。

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

fileDialog.ShowDialog(); 

要阅读内容:您将从OpenFileDialog中获取文件名,并使用其执行哪些IO操作。

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

6
DialogResult.OK并不存在,但我可以通过bool? res = fileDialog.ShowDialog(); if(res.HasValue && res.Value) { ... }来实现相同的功能。 - wormsparty
1
请注意,如果您正在使用 System.Windows.Forms,则存在 DialogResult.OK,您可以使用它,但由于这是 WPF,因此通常会使用 Microsoft.Win32。 - Casey Sebben

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

在您的视图模型中声明一个命令,并像我在按钮内部所做的那样在视图中绑定它。现在,一旦用户点击按钮,您将在代码中获得控制权。在该代码中创建一个窗口并启动它。一旦用户关闭窗口,读取内容并进行您想要的任何操作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接