繁体   English   中英

在C#中使用Model-View-ViewModel(MVVM)的WPF FolderBrowserDialog

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

单击浏览按钮后,我必须获取FolderBrowserDialog,但应该使用MVVM来实现。

说明:

  1. 收到FolderBrowserDialog Box后,我应该能够选择要保存文件的文件夹。

  2. 然后,在选择文件夹之后,它应该在我的浏览按钮旁边的文本框中显示所选的文件夹路径以及文件夹名称。

    我该如何实现呢?

您需要了解绑定。

在这个简单的示例中,我添加了一个绑定到Command的按钮-替换了event背后的代码。我还使用了现存ICommand并实现它的Nuget(以及许多其他功能)-Nuget的名称是Prism6.MEF。

这是示例:

XAML:

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

</Grid>

背后的代码:

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

查看模型:

   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"; 
    }
}

正如我在开始时解释的那样,要了解它为什么起作用,您必须了解WPF中的绑定,尤其是INotifyPropertyChange-对于TextBlock上的数据

希望它有帮助:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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