【发布时间】:2011-10-19 11:02:57
【问题描述】:
我正在尝试创建一个图例控件,它是一组数据绑定的堆栈面板,并且在使数据绑定正常工作时遇到了重大问题。经过多次搜索后,我能够绑定到在我的数据模板中定义的标准控件上工作。但是,当我使用 exactly 相同的绑定来设置自定义控件上的值时,我的依赖属性不会被设置。这是相关的 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>
// 测试项目
<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#)?
-
好吧,您已经展示了几乎可以工作的代码,但没有展示应该工作的代码,但不是
ItemLabel属性的实现。 -
有趣的是,如果我放了一个无效的绑定,PXLegendItem 上的ItemLabel 被设置为一个空字符串,但如果我放了有效的绑定,它根本就没有设置。
-
我已使用显示不良行为的用户控件更新了示例 - 谢谢
标签: silverlight data-binding binding