Skip to content

Instantly share code, notes, and snippets.

@odugen
Created January 13, 2015 08:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save odugen/ae2d790cea26f01ea0e7 to your computer and use it in GitHub Desktop.
Save odugen/ae2d790cea26f01ea0e7 to your computer and use it in GitHub Desktop.
WPF MVVM Folder dialog
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Interactivity;
using Button = System.Windows.Controls.Button;
namespace FolderDialog
{
public class FolderDialogBehavior : Behavior<Button>
{
public string SetterName { get; set; }
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.Click += OnClick;
}
protected override void OnDetaching()
{
AssociatedObject.Click -= OnClick;
}
private void OnClick(object sender, RoutedEventArgs e)
{
var dialog = new FolderBrowserDialog();
var result = dialog.ShowDialog();
if (result == DialogResult.OK && AssociatedObject.DataContext != null)
{
var propertyInfo = AssociatedObject.DataContext.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public)
.Where(p => p.CanRead && p.CanWrite)
.First(p => p.Name.Equals(SetterName));
propertyInfo.SetValue(AssociatedObject.DataContext, dialog.SelectedPath, null);
}
}
}
}
using System.ComponentModel;
namespace FolderDialog
{
public class MainViewModel: INotifyPropertyChanged
{
private string _folderName;
public string FolderName
{
get { return _folderName; }
set
{
_folderName = value;
OnPropertyChanged("FolderName");
}
}
#region Implementation of INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
}
protected virtual void OnPropertyChanged(PropertyChangedEventArgs args)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, args);
}
#endregion
}
}
<Window x:Class="FolderDialog.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:FolderDialog="clr-namespace:FolderDialog"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
Title="MainWindow" Height="350" Width="525"
>
<Window.DataContext>
<FolderDialog:MainViewModel></FolderDialog:MainViewModel>
</Window.DataContext>
<Grid>
<StackPanel>
<TextBlock Text="{Binding FolderName}"/>
<Button Content="Select Folder">
<i:Interaction.Behaviors>
<FolderDialog:FolderDialogBehavior SetterName="FolderName"/>
</i:Interaction.Behaviors>
</Button>
</StackPanel>
</Grid>
</Window>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment