依赖属性传播失败

时间:2014-09-29 14:35:08

标签: c# wpf xaml treeview dependency-properties

我创建了一个名为ObjectExplorer的UserControl:

public partial class ObjectExplorer : UserControl
{
    public static readonly DependencyProperty ItemsProperty = DependencyProperty.Register("Items", typeof(List<Node>), typeof(ObjectExplorer), new PropertyMetadata(new List<Node>(), ItemsSet));
    public List<Node> Items
    {
        get { return (List<Node>)GetValue(ItemsProperty); }
        set { SetValue(ItemsProperty, value); }
    }
}

在控件的XAML中它有:

<TreeView Name="treeView" ItemsSource="{Binding Items}" Padding="0,5,0,0" Grid.Row="1">
    <TreeView.ItemTemplate>
        <HierarchicalDataTemplate ItemsSource="{Binding Nodes}">
            <StackPanel Orientation="Horizontal" Margin="4,3" ContextMenu="{Binding Converter={StaticResource NodeTypeToContextMenuConverter}}">
                <Image Source="{Binding Converter={StaticResource StringToImageConverter}}" />
                <TextBlock Text="{Binding Title}" Padding="4,0,0,0" />
            </StackPanel>
        </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>
</TreeView>

所以我们可以看到,TreeView绑定到Items DP。现在我在我的MainWindow.xaml中使用它,如下所示:

<fe:ObjectExplorer x:Name="objExplorer" Items="{Binding DatabaseObjects}" />

所以控件的这个“实例”,它的Items绑定到MainWindow上的DP:

public partial class MainWindow : Window
{
    public static readonly DependencyProperty DatabaseObjectsProperty = DependencyProperty.Register("DatabaseObjects", typeof(List<Node>), typeof(MainWindow), new PropertyMetadata(new List<Node>(), DatabaseObjectsPropertySet));
    public List<Node> DatabaseObjects
    {
        get { return (List<Node>)GetValue(DatabaseObjectsProperty); }
        set { SetValue(DatabaseObjectsProperty, value); }
    }
}

在MainWindow.cs上的方法内部我正在做:

List<Node> nodes = new List<Node>();
nodes.add(....);
DatabaseObjects = nodes;

会发生什么:

MainWindow上的DP触发其设置回调正常。

未发生的事情:

不会调用ObjectExplorer上的DP,并且TreeView中不显示任何内容。我通过在mainwindow中命名自定义控件(objExplorer)的实例来工作,然后每当DatabaseObjects的回调触发时手动设置其Items ...

private static void DatabaseObjectsPropertySet(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    ((MainWindow)d).objExplorer.Items = (List<Node>)e.NewValue;
}

我想知道......为什么?

编辑:

MainWindow的DataContext在XAML DataContext="{Binding RelativeSource={RelativeSource Self}}

中设置

我期待:

Code in MainWindow -> MainWindow.DatabaseObjects DP ||breaks|| ---(binding)--> objExplorer.Items ---> UC.Items ---(Internal Binding)--> TreeView.ItemSource

0 个答案:

没有答案