正在学习wpf,我新建了一个自定义控件,其中包含了一个treeview控件
下面是部分代码:
namespace MyTree
{
/// <summary>
/// Interaction logic for NewTree.xaml
/// </summary>
public partial class NewTree : UserControl
{
public System.Collections.IEnumerable ItemsSource
{
get { return treeView1.ItemsSource; }
set { treeView1.ItemsSource = value; }
}
public NewTree()
{
InitializeComponent();
}
}
}
然后我使用这个控件,想对其中的treeview控件进行绑定,下面是绑定代码:
<Window x:Class="MyTree.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MyTree"
xmlns:system="clr-namespace:System;assembly=mscorlib"
Title="MainWindow" Height="300" Width="541" xmlns:my="clr-namespace:MyTree">
<Grid>
<Grid.Resources>
<ObjectDataProvider x:Key="name" ObjectType="{x:Type local:BindDataAccess}" MethodName="FindTables">
<ObjectDataProvider.ConstructorParameters>
<system:String>Provider=SQLOLEDB.1;Data Source=WP-PC;Initial Catalog=DataBaseGateTest;User ID=sa;Password=111</system:String>
</ObjectDataProvider.ConstructorParameters>
</ObjectDataProvider>
<DataTemplate x:Key="tables">
<TextBlock Text="{Binding Path=Code}"></TextBlock>
</DataTemplate></Grid.Resources>
<!--这是一个普通的treeview控件,下面的方法可以实现绑定-->
<TreeView ItemsSource="{Binding Source={StaticResource name}}" ItemTemplate="{StaticResource tables}" Height="214" HorizontalAlignment="Left" Margin="284,24,0,0" Name="treeView1" VerticalAlignment="Top" Width="197" />
<!--这是我新建的自定义控件,下面的方法绑定失败-->
<my:NewTree ItemsSource="{Binding Source={StaticResource name}}" HorizontalAlignment="Left" Margin="49,24,0,0" x:Name="newTree1" VerticalAlignment="Top" Height="214" Width="84" />
</Grid>
</Window>
在自定义控件NewTree的{Binding Source={StaticResource name}}处提示A 'Binding' cannot be set on the 'ItemsSource' property of type NewTree,a 'Binding' can only be set on a DependencyProperty of a DependencyObject.
于是我修改了代码,代码如下:
namespace MyTree
{
/// <summary>
/// Interaction logic for NewTree.xaml
/// </summary>
public partial class NewTree : UserControl
{
public System.Collections.IEnumerable ItemsSource
{
get { return (System.Collections.IEnumerable)GetValue(NewTreeItemsSource); }
set { SetValue(NewTreeItemsSource, value); }
}
public static DependencyProperty NewTreeItemsSource;
public NewTree()
{
InitializeComponent();
NewTreeItemsSource = DependencyProperty.Register("ItemsSource", typeof(System.Collections.IEnumerable), typeof(NewTree), new FrameworkPropertyMetadata(treeView1.ItemsSource, FrameworkPropertyMetadataOptions.AffectsRender));
}
}
}
但是仍然还是这个问题,请高手指点