一切都发生在Windows Phone 7.1开发环境中。
在我的MainPage.xaml中,我有ListBox:
<ListBox x:Name="LottoListBox" ItemsSource="{Binding lottoResults}">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<local:LottoResults Date="{Binding Date}" Results="{Binding Results}" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
如您所见,作为ItemSource,我设置了“lottoResults”集合。
public ObservableCollection<Lotto> lottoResults { get; set; }
“乐透”课程:
public DateTime Date
{
get { return _date; }
set
{
_date = value;
NotifyPropertyChanged("Date");
}
}
private DateTime _date;
public Structures.DoubleResult[] Results
{
get { return _results; }
set
{
_results = value;
NotifyPropertyChanged("Results");
}
}
private Structures.DoubleResult[] _results;
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyName = "")
{
if(PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
DoubleResult结构包含两个字段 - int和bool,但它现在并不重要,因为我没有设置任何绑定到“Results”字段。
让我们看一下我的usercontrol“LottoResults”:
public DateTime Date
{
get { return (DateTime)GetValue(DateProperty); }
set { SetValue(DateProperty, value); }
}
public static readonly DependencyProperty DateProperty =
DependencyProperty.Register("Date", typeof(DateTime), typeof(LottoResults), new PropertyMetadata(new DateTime(), dateChanged));
public static void dateChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
LottoResults control = d as LottoResults;
MessageBox.Show("DateChanged!");
// some magical, irrelevant voodoo which only I can understand. ;-)
}
现在是一些XAML,我绑定了“Date”字段。
<TextBlock Grid.ColumnSpan="6" Foreground="Black" FontSize="34" FontWeight="Bold" Text="{Binding Date, StringFormat='{}{0:yyyy.MM.dd}'}" />
令人惊讶的是,惊喜 - 绑定不起作用!好吧,在usercontrol中它确实如此。在DependencyProperty作为默认值我设置“new DateTime()”,这是0001.01.01,正好在TextBlock中显示。
在我的lottoResults集合中(ListBox的ItemsSource)我有3个项目(没有一个项目的日期为“0001.01.01”)。 ListBox显示3个项目,但显示的日期始终为0001.01.01。更重要的是,“dateChanged()”方法永远不会被执行(我没有得到MessageBox,也没有在断点处停止),所以我猜“Date”字段永远不会从绑定中获得新值。
但有趣的是,如果我将TextBlock的代码从usercontrol复制到MainPage.xaml(现在它直接从“lottoResults”集合中获取值),绑定确实有效!
<ListBox x:Name="LottoListBox" ItemsSource="{Binding lottoResults}">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<TextBlock Foreground="Black" FontSize="34" FontWeight="Bold" Text="{Binding Date, StringFormat='{}{0:yyyy.MM.dd}'}" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
那么,为什么呢?我处于死胡同。我花了半天的时间才弄明白没有结果。
答案 0 :(得分:0)
Lotto类需要implement INotifyPropertyChanged这将导致在Lotto对象属性更改时发出UI / View信号。
如果结果集合发生更改(添加,删除了项目),则还需要使用ObservableCollection而不是数组。