Наши проекты:
Журнал · Discuz!ML · Wiki · DRKB · Помощь проекту |
||
ПРАВИЛА | FAQ | Помощь | Поиск | Участники | Календарь | Избранное | RSS |
[3.16.15.149] |
|
Сообщ.
#1
,
|
|
|
Хотелось бы поднять заезженную тему, но ни куда без нее, каждый пилит свой велосипед , подключает WinForms кто то пишет свою библиотеку , кто то просто добавляет дополнительное окно и организует свой выбор и вывод строки ,
вообщем пособирав там сям начал с этого Прикреплённый файлpr77.png (33,63 Кбайт, скачиваний: 575) |
Сообщ.
#2
,
|
|
|
Вот такой простенький код
using System.Collections.ObjectModel; using System.IO; using System.Windows; using System.Windows.Controls; namespace WpfApp1 { public partial class MainWindow : Window { ObservableCollection<DiR> dDiRs = null; public MainWindow() { InitializeComponent(); foreach (DriveInfo drive in DriveInfo.GetDrives()) { TreeViewItem item = new TreeViewItem(); item.Tag = drive; item.Header = drive.ToString(); item.Items.Add("*"); treeView1.Items.Add(item); } } private void treeView1_Expanded(object sender, RoutedEventArgs e) // обработчик события раскрытие пункта (кликнули по узлу) { TreeViewItem item = (TreeViewItem)e.OriginalSource; item.Items.Clear(); DirectoryInfo dir; if (item.Tag is DriveInfo) { DriveInfo drive = (DriveInfo)item.Tag; dir = drive.RootDirectory; } else dir = (DirectoryInfo)item.Tag; try { foreach (DirectoryInfo subDir in dir.GetDirectories()) { TreeViewItem newItem = new TreeViewItem(); newItem.Tag = subDir; newItem.Header = subDir.ToString(); newItem.Items.Add("*"); item.Items.Add(newItem); } } catch { } } private void butUpd_Click(object sender, RoutedEventArgs e) // кн. Обновить { string pathDir = txtBox1.Text.ToString(); // указываем какой каталог показать DirectoryInfo dir = new DirectoryInfo(pathDir);//получаем атрибуты указанного каталога if (dDiRs == null)// если наша коллекция пусто { dDiRs = new ObservableCollection<DiR>(); listBox1.ItemsSource = dDiRs; } foreach (var dD in dir.GetDirectories())// перебираем дочерние папки { dDiRs.Add( // добавляем в коллекцию по одной записи new DiR() { PathDir = dir.FullName, NameDir = dD.Name } ); } } private void butClose_Click(object sender, RoutedEventArgs e) // кн. Закрыть { Close(); // закрыть окно } private void but2_Click(object sender, RoutedEventArgs e) // кн. Открыть { } } public class DiR { public string PathDir { get; set; } public string NameDir { get; set; } } } XAML <ListBox x:Name="listBox1" ItemsSource="{Binding dDiRs}" Margin="0,103,30,74" HorizontalAlignment="Right" Width="369"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal"> <Image Width="32" Height="32" Source="folder_256.png" SnapsToDevicePixels="True"></Image> <Label Content="{Binding NameDir}"/> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> |
Сообщ.
#3
,
|
|
|
<Button Content="Прикрепить" Height="23" HorizontalAlignment="Left" Command="{Binding SetOpenDialogCommand}" Grid.Row="0" Grid.Column ="1" Name="button1" VerticalAlignment="Top" Width="75" /> private Command setopendialogcommand; public ICommand SetOpenDialogCommand { get { if (setopendialogcommand == null) { setopendialogcommand = new Command(arg => SetOpenDialog()); } return setopendialogcommand; } } public void SetOpenDialog() { Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog(); ClassSettings open_options = ReferenceObj.deserialize(); dlg.Multiselect = true; if (open_options.ras==".cws") dlg.Filter = "ptsl files (*.cws)|*.cws| autocad fles (*.dwg)| *.dwg| image files (*.tif)|*.tif| pdf files (*.pdf)|*.pdf| jpg files (*.jpg)|*.jpg"; else dlg.Filter = "autocad fles (*.dwg)|*.dwg|ptsl files (*.cws)|*.cws| image files (*.tif)|*.tif| pdf files (*.pdf)|*.pdf| jpg files (*.jpg)|*.jpg"; if (dlg.ShowDialog() == true) { File_Dialog = dlg.FileName; AddDrwName = System.IO.Path.GetFileNameWithoutExtension(dlg.FileName); listadd = new ObservableCollection<AddViewModel> (dlg.FileNames.Select(x => new AddViewModel(x)).ToList()); NotifyPropertyChanged(()=>this.listadd); } } |
Сообщ.
#4
,
|
|
|
Koss что то не получается запустить этот кусок , это диалог выбора файла ??? я правильно понял ??? с WinForms ???
|
Сообщ.
#5
,
|
|
|
Цитата Koss @ <Button Content="Прикрепить" Height="23" HorizontalAlignment="Left" Command="{Binding SetOpenDialogCommand}" Grid.Row="0" Grid.Column ="1" Name="button1" VerticalAlignment="Top" Width="75" /> это точно с винформс |
Сообщ.
#6
,
|
|
|
XAML кусок это я понял что с WPF, но OpenFileDialog вот про это спрашиваю
Добавлено это я понял что подключаем using System.Windows.Forms; Добавлено вот на просторах интернета нашел вот такой класс [Spoiler] public class FileFolderDialog : CommonDialog { private OpenFileDialog dialog = new OpenFileDialog(); public OpenFileDialog Dialog { get { return dialog; } set { dialog = value; } } public new DialogResult ShowDialog() { return this.ShowDialog(null); } public new DialogResult ShowDialog(IWin32Window owner) { // Set validate names to false otherwise windows will not let you select "Folder Selection." dialog.ValidateNames = false; dialog.CheckFileExists = false; dialog.CheckPathExists = true; try { // Set initial directory (used when dialog.FileName is set from outside) if (dialog.FileName != null && dialog.FileName != "") { if (Directory.Exists(dialog.FileName)) dialog.InitialDirectory = dialog.FileName; else dialog.InitialDirectory = System.IO.Path.GetDirectoryName(dialog.FileName); } } catch (Exception ex) { // Do nothing } // Always default to Folder Selection. dialog.FileName = "Зайдите в папку которую хотите выбрать, но не выделяя другие."; if (owner == null) return dialog.ShowDialog(); else return dialog.ShowDialog(owner); } /// <summary> // Helper property. Parses FilePath into either folder path (if Folder Selection. is set) // or returns file path /// </summary> public string SelectedPath { get { try { if (dialog.FileName != null && (dialog.FileName.EndsWith("Folder Selection.") || !File.Exists(dialog.FileName)) && !Directory.Exists(dialog.FileName)) { return System.IO.Path.GetDirectoryName(dialog.FileName); } else { return dialog.FileName; } } catch (Exception ex) { return dialog.FileName; } } set { if (value != null && value != "") { dialog.FileName = value; } } } /// <summary> /// When multiple files are selected returns them as semi-colon seprated string /// </summary> public string SelectedPaths { get { if (dialog.FileNames != null && dialog.FileNames.Length > 1) { StringBuilder sb = new StringBuilder(); foreach (string fileName in dialog.FileNames) { try { if (File.Exists(fileName)) sb.Append(fileName + ";"); } catch (Exception ex) { // Go to next } } return sb.ToString(); } else { return null; } } } public override void Reset() { dialog.Reset(); } protected override bool RunDialog(IntPtr hwndOwner) { return true; } } |
Сообщ.
#7
,
|
|
|
Цитата kms @ OpenFileDialog Microsoft.Win32.OpenFileDialog |
Сообщ.
#8
,
|
|
|
на WPF работает , отлично , удобно , но !!!! при первом запуске надо понять и привыкнуть к тому что выбор папки происходит не той которая выделенная а в той которой находишься в момент выбора ,
|
Сообщ.
#9
,
|
|
|
не тот код. У меня файлы выбирает.
|
Сообщ.
#10
,
|
|
|
да я понял , это я тебе про тот класс который выше написан в сообщ.#6
Добавлено вот нашел , https://www.codeproject.com/Articles/118612...-Folder-Browser это по моему одно из более менее удобных решений, но опять же большущий минус то что надо подключать WinForms , а в этом еще и Microsoft.Practices.Prism.dll |