C# WPF에서 Microsoft.Win32
namespace의 OpenFileDialog
class를 활용하여 파일 불러오기를 구현하였습니다.
저는 UserControl
과 ViewModel
을 연결해서 사용하였습니다.
TextBox와 Button을 포함하는 간단한 UI를 정의합니다. TextBox는 파일명을 표시하며, Button은 파일 열기 대화상자를 엽니다.
<UserControl x:Class="[컨트롤러 경로]"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="200" Width="300">
<StackPanel Orientation="Horizontal">
<TextBox Text="{Binding SelectedBackupFile, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
Width="200" Height="30" Margin="0 5 15 0" IsReadOnly="True"/>
<Button Command="{Binding OpenFileCommand}"
Content="Open File"/>
</StackPanel>
</UserControl>
Control
클래스의 생성자에서 DataContext
를 ViewModel
로 설정하여 View
와 ViewModel
을 연결합니다.
using System.Windows.Controls;
namespace [컨트롤러 경로]
{
public partial class [~Control] : UserControl
{
public [~Control]()
{
InitializeComponent();
DataContext = new [~Control]ViewModel();
}
}
}
INotifyPropertyChanged
인터페이스를 구현하여 데이터 바인딩
을 지원합니다.OpenFileCommand
를 RelayCommand
로 초기화하고, OpenFile 메서드
를 실행합니다.OpenFileDialog
를 열고 파일을 선택하면, 선택한 파일의 이름을 SelectedBackupFile
속성에 설정합니다.using Microsoft.Win32;
using System.ComponentModel;
using System.IO;
using System.Windows.Input;
namespace [뷰모델 경로]
{
public partial class [컨트롤러뷰모델 명] : INotifyPropertyChanged
{
private string _selectedBackupFile;
public ICommand OpenFileCommand { get; set; }
public InfoControlViewModel()
{
OpenFileCommand = new RelayCommand(OpenFile);
}
public string SelectedBackupFile
{
get => _selectedBackupFile;
set
{
_selectedBackupFile = value;
OnPropertyChanged(nameof(SelectedBackupFile));
}
}
private void OpenFile()
{
// file dialog box를 열 경로 구성
var dialog = new OpenFileDialog();
// MyDocuments 폴더 경로 가져오기
string backupDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
// "backup" 폴더 경로 설정
string backupFolderPath = Path.Combine(backupDirectory, "backup");
// 초기 경로 및 파일 필터 설정
dialog.InitialDirectory = backupFolderPath;
dialog.DefaultExt = ".db";
dialog.Filter = "Data Base File(.db)|*.db";
// 파일 선택 대화상자 열기
bool? result = dialog.ShowDialog();
if (result == true)
{
// 파일 이름을 SelectedBackupFile 속성에 설정
SelectedBackupFile = Path.GetFileName(dialog.FileName);
}
}
// INotifyPropertyChanged 인터페이스 구현
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
ICommand 인터페이스
를 구현하여 명령을 정의합니다. RelayCommand
는 명령 실행
과 조건
을 간단히 정의할 수 있도록 도와줍니다.
ICommand
와 RelayCommand
에 대해서는 추후에 다룰 예정입니다.
using System;
using System.Windows.Input;
namespace [네임스페이스명]
{
public class RelayCommand : ICommand
{
private readonly Action _execute;
private readonly Func<bool> _canExecute;
public RelayCommand(Action execute, Func<bool> canExecute = null)
{
_execute = execute;
_canExecute = canExecute;
}
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return _canExecute == null || _canExecute();
}
public void Execute(object parameter)
{
_execute();
}
public void RaiseCanExecuteChanged()
{
CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}
}
}
파일 선택 버튼을 클릭하면
OpenFileDialog가 보이게 되고
파일 하나를 선택하여 열면 파일 이름이 TextBox에 보이게 됩니다.
참고
1)
https://learn.microsoft.com/ko-kr/dotnet/desktop/wpf/windows/how-to-open-common-system-dialog-box?view=netdesktop-8.0
2)
https://rhkdrmfh.tistory.com/119