数据绑定-如何将用户控件绑定到应用程序视图模型



我在WP7应用程序中使用标准的数据透视模板。

我用一些额外的属性定义了MainViewModel类:

public class MainViewModel : INotifyPropertyChanged
{
    ...
    private MyClass selectedKey_m;
    public MyClass SelectedKey
    {
        get
        {
            ...
        }
        set
        {
            if (value != this.selectedKey_m)
            {
                this.selectedKey_m = value;
                NotifyPropertyChanged("SelectedKey");
            }
        }
    }
}

App类有一个视图模型实例:

private static MainViewModel viewModel = null;
public static MainViewModel ViewModel
{
    get
    {
        // Delay creation of the view model until necessary
        if (viewModel == null)
            viewModel = new MainViewModel();
        return viewModel;
    }
}

My MainPage.xaml.cs设置DataContext:

DataContext = App.ViewModel;

从这里开始,我可以在ListBoxes上设置双向绑定,我知道它是有效的,因为如果我在视图模型中的SelectedKey属性上设置断点,我可以看到setter被调用。

我的问题是,我有自己的用户控件,它有一个可绑定的属性,绑定到视图模型的SelectedKey属性,但当视图模型更新时,我的用户控件中的属性永远不会被设置,我不知道为什么。

这是我的用户控件:

public partial class MyUserControl : UserControl
{
    public static readonly DependencyProperty SelectedKeyProperty = DependencyProperty.Register(
        "SelectedKey", typeof(MyClass), typeof(MyUserControl), new PropertyMetadata(null));
    public MyClass SelectedKey
    {
        get { return (MyClass)this.GetValue(SelectedKeyProperty); }
        set { this.SetValue(SelectedKeyProperty, value); }
    }    
}

这是我主页中的xaml:

<local:MyUserControl x:Name="myUC" SelectedKey="{Binding Path=SelectedKey}">

我希望当视图模型的SelectedKey属性发生更改时,会调用用户控件的SelectedKey属性的setter,但事实并非如此。

我还尝试在xaml:中设置我的用户控件的数据上下文

DataContext="{Binding Path=App.ViewModel}"

调试器没有进入setter,不知道为什么。

尝试添加属性值更改时调用的回调:

public static readonly DependencyProperty SelectedKeyProperty = DependencyProperty.Register(
        "SelectedKey", typeof(MyClass), typeof(MyUserControl), new PropertyMetadata(MyPropertyChanged));
private static void MyPropertyChanged( object sender, DependencyPropertyChangedEventArgs args)
{
}

已解决。我不得不按照ptauzen的建议添加静态方法,但也从我的xaml:中删除了DataContext绑定语句

DataContext="{Binding Path=App.ViewModel}"

因为MainPage在构造函数中设置了数据上下文,所以因为我的用户控件是主页面的子控件,所以它继承了数据上下文。我所需要的只是确保我的用户控件属性的绑定已经设置好:

SelectedKey="{Binding SelectedKey}"

最新更新