如何在不使用MVVM的情况下绑定DependencyProperty

本文关键字:情况下 绑定 DependencyProperty MVVM | 更新日期: 2023-09-27 18:29:01

好吧,我正在做一个小项目,我发现没有必要实现一个完整的MVVM。

我试图在代码背后绑定一些属性,但无法使其工作。

重点是在代码隐藏中使用DependencyProperties和Binding。

我试着在SO:中关注这些链接和问题

代码绑定WPF 中的绑定依赖属性

如何:在代码中创建绑定

通过Xaml将Code Behind中定义的依赖项属性绑定到UserControl 的DataContext中的属性

但它们与MVVM有关,或者至少我不能在我的情况下调整代码。

这个例子应该很简单。

主窗口.xaml

<Label Name="_lblCurrentPath"
        Style="{StaticResource CustomPathLabel}"
        ToolTip="{Binding CurrentPath}"
        Content="{Binding CurrentPath, Mode=TwoWay,
                     UpdateSourceTrigger=PropertyChanged}"/>

主窗口.xaml.cs

public MainWindow()
{
    InitializeComponent();
    SetBindings();
}
#region Properties
public static readonly DependencyProperty CurrentPathProperty =
    DependencyProperty.Register("CurrentPath", typeof(String), typeof(MainWindow), new PropertyMetadata(String.Empty, OnCurrentPathChanged));

public string CurrentPath
{
    get { return (String)GetValue(CurrentPathProperty); }
    set { SetValue(CurrentPathProperty, value); }
}

#endregion
#region Bindings
private void SetBindings()
{
    // Label CurrentPath binding
    Binding _currentPath = new Binding("CurrentPath");
    _currentPath.Source = CurrentPath;
    this._lblCurrentPath.SetBinding(Label.ContentProperty, _currentPath);
}
#endregion
#region Methods
private void Refresh()
{
    MessageBox.Show("Refresh!");
}
private string Search()
{
    WinForms.FolderBrowserDialog dialog = new WinForms.FolderBrowserDialog();
    WinForms.DialogResult _dResult = dialog.ShowDialog();
    switch(_dResult)
    {
        case WinForms.DialogResult.OK:
            CurrentPath = dialog.SelectedPath;
            break;
        default:
            break;
    }
    return CurrentPath;
}
#endregion
#region Events
private static void OnCurrentPathChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    MainWindow instance = d as MainWindow;
    instance.Refresh();
}
public void OpenSearchEclipsePath(object sender, RoutedEventArgs e)
{
    CurrentPath = Search();
}
public void RefreshEclipsePath(object sender, RoutedEventArgs e)
{
    Refresh();
}

知道吗?

。如果这是一种糟糕的做法,我应该使用MVVM,当然欢迎评论。

。此外…与Command属性相关。在这种情况下,我不想使用MVVM方法,注册事件更好吗?我发现使用自定义命令绑定有点乏味。

如何在不使用MVVM的情况下绑定DependencyProperty

首先,您完全可以在没有MVVM的情况下使用绑定。我不推荐它,因为当你使用MVVM时,代码会干净得多,但它是可以做到的。你所需要做的就是在你的构造函数中放上这行:

this.DataContext = this;

现在,您的视图也是您的视图模型!就像我说的,这不是个好主意。

现在,您的代码在MainWindow类中有一个DependencyProperty不要那样做。这毫无用处。DP存在,因此控件可以为它们提供绑定。MainWindow没有父级;因此DP是无用的。

你所需要做的就是设置一个常规属性:

public string CurrentPath
{
    get { return currentPath; }
    set
    {
         currentPath = value;
         NotifyPropertyChanged();
    }
}

然后让MainWindow实现INotifyPropertyChanged(我有没有提到使用简单的视图模型更有意义?)。

回答您的Command问题。是的,如果您反对使用命令,只需注册事件即可。然而,Command是一种非常好的方法,可以在不破坏MVVM的情况下让用户点击视图模型。语法并不是那么糟糕。无论如何,如果你要采用"视图作为视图模型"的方法,Command并不会给你带来太多好处。