我正在尝试创建一个图例控件,这是一个堆栈面板的数据绑定集,并且我在获得数据绑定工作方面存在重大问题。经过多次搜索后,我能够使绑定在数据模板中定义的标准控件上工作。然而,当我使用完全相同的绑定来设置自定义控件上的值时,我的依赖属性没有被设置。以下是相关的XAML
编辑我改变了我的复杂的自定义项目与一个简单的用户控制,只是有一个按钮-同样的效果-感谢帮助
<StackPanel x:Name="LayoutRoot" Background="Transparent">
<TextBlock Text="Legend:" />
<ItemsControl x:Name="tStack" ItemsSource="{Binding LegendItems}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Vertical"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Button Content="{Binding ItemLabel}" />
<pxsc:TestItem ItemLabel="{Binding ItemLabel}" />
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<!-- <pxsc:PXLegendItem ItemColor="Green" ItemLabel="TextLabel"/> -->
</StackPanel>
//testtem
<UserControl x:Class="SilverlightControls.TestItem"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400"
DataContext="{Binding RelativeSource={RelativeSource Self}}" >
<Grid x:Name="LayoutRoot" Background="White">
<Button Content="{Binding ItemLabel}" />
</Grid>
</UserControl>
测试代码 public partial class TestItem : UserControl
{
public TestItem()
{
InitializeComponent();
}
#region ItemLabel
public static readonly DependencyProperty ItemLabelProperty =
DependencyProperty.Register("ItemLabel", typeof(string), typeof(TestItem),
new PropertyMetadata(new PropertyChangedCallback(OnItemLabelPropertyChanged)));
public string ItemLabel
{
get { return (string)GetValue(ItemLabelProperty); }
set { SetValue(ItemLabelProperty, value); }
}
private static void OnItemLabelPropertyChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
}
public static void SetItemLabel(DependencyObject obj, string val)
{
obj.SetValue(ItemLabelProperty, val);
}
public static double GetItemLabel(DependencyObject obj)
{
return (double)obj.GetValue(ItemLabelProperty);
}
#endregion
}
在我的示例代码中,我用3个对象填充LegendItems。ItemsControl创建了三个正确标记的按钮和三个未设置任何标签的legenditem控件。
如果取消最后一行的注释,则可以看到附加控件正确地接受TextLabel值。
我认为这是一个相当"按书"的实现,所以我很惊讶,它没有工作,任何帮助是非常感激的!
作为暗算,您没有将ItemLabel
实现为依赖属性,或者如果您没有正确实现它。如果是后者,那么用相关代码编辑你的问题。
编辑
由于您的控件将自己分配给DataContext
,任何来自其祖先的现有DataContext
将被忽略。删除对DataContext
的分配。将内部的xaml更改为:-
<Grid x:Name="LayoutRoot" Background="White">
<Button Content="{Binding Parent.ItemLabel, ElementName=LayoutRoot}" />
</Grid>
这应该能让它工作。顺便说一句,你真的需要GetItemLabel
和SetItemLabel
静态方法吗?这些通常包含在附加属性中,而不是标准的依赖属性。