首页 文章

WPF MVVM绑定到UserControl的DependencyProperty不起作用

提问于
浏览
3

我试图坚持MVVM方法来构建我的WPF应用程序,并遇到一个奇怪的绑定问题,感觉我错过了什么 .

我有一个用户控件(PluginsTreeView),它有一个ViewModel(PluginsViewModel)驱动它 . PluginsTreeView公开了一个类型为String(DocumentPath)的公共DependencyProperty . 我的MainWindow在XAML中设置了这个属性,但它似乎没有进入我的UserControl . 我正在寻找一些关于为什么这不起作用的指示 .

PluginsTreeView.xaml.cs

public partial class PluginsTreeView: UserControl
{
    public PluginsTreeView()
    {
        InitializeComponent();
        ViewModel = new ViewModels.PluginsViewModel();
        this.DataContext = ViewModel;
    }

    public static readonly DependencyProperty DocumentPathProperty =
        DependencyProperty.Register("DocumentPath", typeof(string), typeof(PluginsTreeView), new FrameworkPropertyMetadata(""));


    public string DocumentPath
    {
        get { return (string)GetValue(DocumentPathProperty); }
        set 
        {
            //*** This doesn't hit when value set from xaml, works fine when set from code behind
            MessageBox.Show("DocumentPath"); 
            SetValue(DocumentPathProperty, value); 
            ViewModel.SetDocumentPath(value);
        }
    }
    ....
 }

MainWindow.xaml

我的PluginsTreeView永远不会获得值'测试路径',我不知道为什么 . 我觉得我在这里缺少一些基本的东西 .

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:Views="clr-namespace:Mediafour.Machine.EditorWPF.Views" x:Class="Mediafour.Machine.EditorWPF.MainWindow"
    xmlns:uc="clr-namespace:Mediafour.Machine.EditorWPF.Views"
    Title="MainWindow" Height="350" Width="600">
  <Grid>
    <uc:PluginsTreeView x:Name="atv" DocumentPath="from xaml" />
  </Grid>
</Window>

但是,当我从MainWindow的代码隐藏中设置DependencyProperty时,它似乎确实正确设置了值 . 我试图弄清楚这里的区别以及代码隐藏方法的工作原理以及在xaml中设置属性的原因 .

MainWindow.xaml.cs

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        MainWindowViewModel ViewModel = new MainWindowViewModel();
        this.DataContext = ViewModel;

        atv.DocumentPath = "from code behind";  //THIS WORKS!
     }
     ....
 }

使用Snoop,我看到XAML“来自xaml”的值确实使其成为属性,但我在PluginsTreeView中的Set方法仍然没有被击中 . 除非从MainWindow代码隐藏设置了值,否则我在那里作为调试工具的消息框不会弹出 .

1 回答

  • 2

    显然,您不应该向这些属性设置器添加任何逻辑,因为只有在从代码设置属性时才会调用它们 . 如果从XAML设置属性,则直接调用SetValue()方法 . 我最终注册了一个回调方法,现在一切都很好用了:

    public static readonly DependencyProperty DocumentPathProperty = DependencyProperty.Register("DocumentPath", typeof(string), typeof(PluginsTreeView), new FrameworkPropertyMetadata("initial value", OnValueChanged));
    

相关问题