【发布时间】:2011-02-16 01:37:49
【问题描述】:
我有一个名为 GoalProgressControl 的自定义用户控件。另一个用户控件包含 GoalProgressControl,并通过 XAML 中的数据绑定设置其 GoalName 属性。但是,永远不会设置 GoalName 属性。当我在调试模式下检查它时,GoalName 在控件的生命周期内保持“null”。
如何设置 GoalName 属性?是不是我做错了什么?
我正在使用 .NET Framework 4 和 Silverlight 4。我对 XAML 和 Silverlight 比较陌生,因此我们将不胜感激。
我试图将 GoalProgressControl.GoalName 更改为 POCO 属性,但这会导致 Silverlight 错误,我的阅读使我相信数据绑定属性应该是 DependencyProperty 类型。我还简化了我的代码,只关注 GoalName 属性(代码如下),但没有成功。
这是 GoalProgressControl.xaml:
<UserControl x:Class="GoalView.GoalProgressControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
Height="100">
<Border Margin="5" Padding="5" BorderBrush="#999" BorderThickness="1">
<TextBlock Text="{Binding GoalName}"/>
</Border>
</UserControl>
GoalProgressControl.xaml.cs:
public partial class GoalProgressControl : UserControl, INotifyPropertyChanged
{
public GoalProgressControl()
{
InitializeComponent();
}
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public static DependencyProperty GoalNameProperty = DependencyProperty.Register("GoalName", typeof(string), typeof(GoalProgressControl), null);
public string GoalName
{
get
{
return (String)GetValue(GoalProgressControl.GoalNameProperty);
}
set
{
base.SetValue(GoalProgressControl.GoalNameProperty, value);
NotifyPropertyChanged("GoalName");
}
}
}
我已将 GoalProgressControl 放在另一个页面上:
<Grid Grid.Row="1" Grid.Column="1" Grid.ColumnSpan="2" Margin="5" Background="#eee" Height="200">
<Border BorderBrush="#999" BorderThickness="1" Background="White">
<StackPanel>
<hgc:SectionTitleBar x:Name="ttlGoals" Title="Personal Goals" ImageSource="../Images/check.png" Uri="/Pages/GoalPage.xaml" MoreVisibility="Visible" />
<ItemsControl ItemsSource="{Binding Path=GoalItems}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<!--TextBlock Text="{Binding Path=[Name]}"/-->
<goal:GoalProgressControl GoalName="{Binding Path=[Name]}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</Border>
</Grid>
请注意上面注释掉的“TextBlock”项。如果我在 TextBlock 中注释并注释掉 GoalProgressControl,则绑定工作正常并且 TextBlock 正确显示 GoalName。此外,如果我将上面的“GoalName”属性替换为一个简单的文本字符串(例如“hello world”),则控件会正确呈现,并且在呈现时会在控件上显示“hello world”。
【问题讨论】:
标签: silverlight data-binding xaml user-controls silverlight-4.0