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

时间:2014-11-04 18:56:03

标签: c# wpf xaml binding dependency-properties

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

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

重点是在后面的代码中使用DependencyProperties和Binding。

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

Bind Dependency Property in codebehind WPF

How to: Create a Binding in Code

Bind Dependency Property, defined in Code-Behind, through Xaml to a Property in the DataContext of a UserControl

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

示例应该非常简单。

MainWindow.xaml

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

MainWindow.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方法的情况下,注册事件会更好吗?我发现自定义命令绑定的使用有点乏味。

1 个答案:

答案 0 :(得分:2)

首先,您可以完全使用没有MVVM的绑定。我不推荐它,因为当您使用MVVM时代码更清晰,但可以完成。您需要做的就是将这一行放在构造函数中:

this.DataContext = this;

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

现在,您的代码在DependencyProperty课程中有一个MainWindow不要那样做。它完全没有用处。 DP就在那里,所以控件可以给它们绑定。 MainWindow没有父母;因此DP无用。

您需要做的就是设置常规属性:

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

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

回答您的Command问题。是的,如果您反对使用命令,只需注册事件即可。但是,Command是一种非常好的方法,可以在不破坏MVVM的情况下将用户点击进入视图模型。语法不是 坏。如果您仍在使用“以视图模式查看”的方法,Command并不会为您带来太多收获。