代码之家  ›  专栏  ›  技术社区  ›  Joel

Silverlight:奇怪的数据绑定问题

  •  2
  • Joel  · 技术社区  · 16 年前

    我用的是 Visifire 我创建了一个正确绑定到依赖属性的图表。效果很好。我决定将图表制作成一个用户控件,因为我将在另一个项目中使用它,并且使用相同的设置。现在我的数据绑定不起作用,除非我把它绑定到代码后面而不是XAML中。

    以下是我所拥有的:

    <UserControl ... x:Name="root">
     ...
         <chart:DataSeries ... DataSource="{Binding ElementName=root, Path=Results}">
     ...
    </UserControl>
    

    public MyList Results
    {
        get { return (MyList)GetValue(ResultsProperty); }
        set { SetValue(ResultsProperty, value); }
    }
    
        // Using a DependencyProperty as the backing store for Results.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ResultsProperty =
            DependencyProperty.Register("Results", typeof(MyList), typeof(MyChart), new PropertyMetadata(null));
    
    
    public GoogleChart()
    {
        Loaded += delegate
        {
        //  theChart.Series[0].DataSource = Results;
        };
        Results = new GoogleResults();
        InitializeComponent();
    }
    

    如果我取消对行的注释 theChart.Series[0].DataSource = Results; 它工作得很好。但是如果我把那行留下注释(就像我把图表移到UserControl之前那样),它就不会绑定(顺便说一句: theChart x:name 图表父级的。所以第一个要素, .Series[0] ,参考图表)。

    谢谢

    1 回复  |  直到 16 年前
        1
  •  2
  •   AnthonyWJones    16 年前

    ElementName=Root

    通常有一个名为“LayoutRoot”的根元素(通常是网格)。因此,不用依赖可以更改的UserControl名称,而是使用“LayoutRoot”,按照惯例,它是UserControl的内容元素。像这样:-

    <chart:DataSeries ... DataSource="{Binding ElementName=LayoutRoot, Path=Parent.Results}">
    

    注意,属性路径现在以 Parent 把你带到 UserControl 不需要知道用户控件的名字。