在一个ItemControl绑定属性doesent工作,但绑定到DataContext做
问题描述:
当我运行这段代码时,我的CustomControl中的Item对象变成了一个System.Windows.Data.Binding,其中只包含null值,但DataContext变成了MyClass对象(该项目与填充)在一个ItemControl绑定属性doesent工作,但绑定到DataContext做
<UserControl x:Name="thisControl">
<Grid x:Name="LayoutRoot">
<ItemsControl ItemsSource="{Binding ElementName=thisControl,Path=Items}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<local:UniformGrid Columns="1"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<local:CustomControl Item="{Binding}" DataContext="{Binding}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
</UserControl>
我CustomControl类
public partial class CustomControl : UserControl
{
public CustomControl()
{
InitializeComponent();
}
public object Item { get; set; }
}
是有什么我不知道的ItemsControl? 这是用Silverlight 4.0写的
在此先感谢!
答
您不需要尝试分配自定义控件DataContext。 ItemsControl会为你照顾。
此外,您的CustomControl
代码需要将Item
属性指定为DependencyProperty
以使绑定生效。绑定不适用于普通的普通属性。
例子:
public object Item
{
get { return GetValue(ItemProperty); }
set { SetValue(ItemProperty, value); }
}
public static readonly DependencyProperty ItemProperty =
DependencyProperty.Register(
"Item",
typeof(object),
typeof(CustomControl),
new PropertyMetadata(null))
(我假设RSListBoxStopItem
是一个错字,你打算推广到CustomControl
)
是的,我怎么能忘了。谢谢,它解决了我的问题。 – Simon900225 2012-01-12 15:52:08