我试图创建一个图例控件,它是一组数据绑定的数据绑定集合,并且在获取数据绑定的工作时遇到了重大问题。经过多次搜索后,我可以绑定到我的数据模板中定义的标准控件上。但是,当我使用刚好相同的绑定来设置我的自定义控件的值时,我的依赖项属性不会被设置。下面是相关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>
// TestItem
<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>
TestItem代码背后
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值。
我认为这是一个相当“实用”的实现,所以我很惊讶它不能正常工作,并且任何帮助都会受到赞赏!
你可以发布你的代码PXLegendItem(包括XAML和C#)吗? – CodeNaked
那么你已经显示了很多可用的代码,并没有显示应该工作的代码,但不是'ItemLabel'属性的实现。 – AnthonyWJones
有趣的是,如果我把一个无效的绑定,PXLegendItem ItemLabel设置为一个空字符串,但如果我把有效绑定,它根本没有设置。 –