简体   繁体   中英

WPF FolderBrowserDialog using Model-View-ViewModel (MVVM) in c#

I have to get FolderBrowserDialog once I click the browse button,but I should achieve that by using MVVM.

Explanation:

  1. Once I get the FolderBrowserDialog Box, I should able to select the folder in which I'm wishing to save my files.

  2. Then after selecting the folder,it should show me the selected folderpath along with the foldername in the Textbox beside my browse button.

    How can I achieve this....

You need to learn about binding.

In this simple example i added a button that is bind to a Command - that replaces the code behind event.I used also in a Nuget that extant the ICommand and implement it ( along with a lot of other functionality ) - The name of the Nuget is Prism6.MEF.

Here is the example :

Xaml:

    <Grid>
    <StackPanel>
        <TextBlock Text="{Binding BindableTextProperty}" />
        <Button Content ="Do Action" Command="{Binding DoAction}" Height="50"/>
    </StackPanel>

</Grid>

Code Behind :

    /// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new MainWindowVM();
    }
}

View Model :

   class MainWindowVM : BindableBase
{
    private string m_bindableTextProperty;


    public MainWindowVM() 
    {
        DoAction = new DelegateCommand(ExecuteDoAction,CanExecuteDoAction); 
    }


    public string BindableTextProperty
    {
        get { return m_bindableTextProperty; }
        set { SetProperty(ref m_bindableTextProperty , value); }
    }

    public DelegateCommand DoAction
    {
        get;
        private set;
    }

    private bool CanExecuteDoAction()
    {
        return true;
    }

    private void ExecuteDoAction() 
    { 
      // Do something
      // You could enter the Folder selection code here 
        BindableTextProperty = "Done"; 
    }
}

As i explained at the begin with to understand why it works you have to understand the Binding in WPF and especially the INotifyPropertyChange - for the Data on the TextBlock

Hope it helped :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM