无法从另一个控件使用自定义(MVVM)控件

时间:2019-05-09 07:48:56

标签: c# wpf mvvm

我尝试实现具有wpf控件(使用MVVM实现)可重复使用的其他控件/窗口(使用MVVM)。

  

我现在的观点是:我想具有该控件的值以绑定到我的外部窗口中。

我已经创建了一个示例应用程序,应该对其进行演示(目录选择器视图):

  1. 我有一个小控件,其中包含一个TextBox和一个Button。该按钮将打开目录选择器,并将所选路径设置为TextBox。

  2. 我有一个窗口。该窗口具有两个元素。 1.的控件和一个按钮。

  3. 第2步中的按钮现在可以生成一些文本并将其保存到所选路径位置的文件中。

问题是:我必须怎么做才能在自定义控件中具有可绑定的属性,以便可以在窗口中像这样使用

<Window x:Class="WpfApp9.MainWindow" 
    ...
    >    
    <StackPanel Orientation="Vertical">

        <local:FilePathView Margin="10"
                            CurrentPath="{Binding ChosenDirectory, Mode=TwoWay}"  />

        <Button Height="30" Margin="10"
                Command="{Binding SaveTextToDir}"/>
</StackPanel>

FilePathView的属性“ CurrentPath”目前是DependencyProperty。 我只是不知道如何解决这个问题。一方面,我有绑定到属性的TextBox。同时,我需要这个DependencyProperty。

我当前的“解决方案”如下所示:FilePathView的ViewModel具有将自己的当前路径设置为View的DependencyProperty的功能。但是,此值不会转发到我的Window中的绑定属性。而且我不知道它可以通过哪种机制起作用。


要完成操作,请在此处找到其他文件

FilePathView:

<UserControl x:Class="WpfApp9.FilePathView"
         ...>
 <StackPanel Orientation="Horizontal">
    <TextBox Text="{Binding CurrentPath}" Width="200" Height="30"  />
    <Button  Command="{Binding SelectPathCommand}" Width="30" Height="30" />
</StackPanel>

FilePathViewModel:

    public class FilePathViewModel : NotificytionObject
    {
        FilePathView _view;
        public FilePathViewModel(FilePathView view)
        {
            this._view = view;
            SelectPathCommand = new Command(ExecuteSelectPathCommand);
        }

        public string CurrentPath
        {
            get { return _view.CurrentPath; }
            set
            {
                _view.CurrentPath = value;
                Notify();
            }
        }

        public Command SelectPathCommand { get; }
        void ExecuteSelectPathCommand()
        {
            CurrentPath = @"C:\JustExample\";
        }
    }

0 个答案:

没有答案
相关问题