Silverlight 4.0数据绑定到依赖项属性

时间:2011-03-15 07:13:12

标签: data-binding silverlight-4.0

我很难在一个嵌套在另一个使用控件中的用户控件上启动绑定。 这是我的层次结构:

  • 导航页面
    • 用户控制A(AthleteMaxGrid)
      • 用户控制B(PagingControl)

我正在使用MVVM设计模型和MVVMLight工具包来实现这些控件。 情况如下: 两个用户控件都具有在XAML中附加到它们的相应ViewModel。 运动员的视图模型MaxGrid有一个Observable Collection(AthleteMaxes)属性暴露,我想绑定到PagingControl。此属性也绑定到AthleteMaxGrid控件的数据视图中,因此它知道它正确填充。

以下是代码:

AthleteMaxGrid XAML:

     <UserControl ...
         DataContext="{Binding AthleteMaxGrid, Source={StaticResource Locator}}">
     ....
     <StackPanel Orientation="Horizontal">
        ...
        <my:PagingControl Jake="{Binding AthleteMaxes}" />
    </StackPanel>
    <telerik:RadGridView x:Name="rgvMaxes" IsScrolling="False" 
        ItemsSource="{Binding AthleteMaxes}" AutoGenerateColumns="False" 
        IsBusy="{Binding IsBusy}" >...

这是来自AthleteMaxGrid ViewModel的片段:

public const string AllMaxesPropertyName = "AthleteMaxes";

private ObservableCollection<AthleteMaxTableItem> _allMaxes = new ObservableCollection<AthleteMaxTableItem>();

    /// <summary>
    /// Gets the AthleteMaxes property.
    /// </summary>
    public ObservableCollection<AthleteMaxTableItem> AthleteMaxes
    {
        get
        {
            return _allMaxes;
        }

        set
        {
            if (_allMaxes == value)
            {
                return;
            }

            _allMaxes = value;

            // Update bindings, no broadcast
            RaisePropertyChanged("AthleteMaxes");
        }
    }

这是来自PagingControl的XAML:

<UserControl  ...
          x:Name="rootElement"
         DataContext="{Binding PagingControlVM, Source={StaticResource Locator}}">
 ...
</UserControl>

我在后面的PagingControl代码中创建了Dependency属性,如下所示:

    public const string JakePropertyName = "Jake";

    public object Jake
    {
        get
        {
            return (object)GetValue(JakeProperty);
        }
        set
        {
            SetValue(JakeProperty, value);
        }
    }

    public static readonly DependencyProperty JakeProperty = DependencyProperty.Register(
        JakePropertyName,
        typeof(object),
        typeof(PagingControl),
        new PropertyMetadata(null,
            new PropertyChangedCallback(onJakeChanged)));


    private static void onJakeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        MessageBox.Show(d.GetType().ToString());
    }

此时我只是试图让我的Callback函数命中(onJakeChanged)所以我知道数据正确进入,我可以进入下一个绑定我的控件的阶段,但它没有被击中。 / p>

如果我将AthleteMaxGrid上的XAML中的Jake属性设置为像“test”这样简单的东西,那么回调就会被正确击中。这似乎是viewModel属性绑定的问题。

有什么想法吗?

提前致谢! 尼克

1 个答案:

答案 0 :(得分:0)

这个很容易回答。这一行:

<my:PagingControl Jake="{Binding AthleteMaxes}" />

将Jake绑定到DataContext的AthleteMaxes。但是,当您创建UserControl时,您将DataContext设置为其他内容!

<UserControl x:Name="rootElement" DataContext="{Binding PagingControlVM, Source=StaticResource Locator}}">

所以现在Jake绑定到PagingControlVM.AthleteMaxes ......它不存在:)