[英]Usercontrol in ListBox, binding in usercontrol doesn't work
一切都在Windows Phone 7.1 Dev環境中發生。
在我的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; }
“ Lotto”類:
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”字段設置任何綁定。
讓我們看一下我的用戶控件“ 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,我在其中綁定了“日期”字段。
<TextBlock Grid.ColumnSpan="6" Foreground="Black" FontSize="34" FontWeight="Bold" Text="{Binding Date, StringFormat='{}{0:yyyy.MM.dd}'}" />
和驚喜,驚喜 - 約束力不工作! 好吧,在用戶控制中確實如此。 在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>
那為什么呢? 我快要死了 我花了半天時間才解決這個問題,但沒有結果。
Lotto類需要實現INotifyPropertyChanged,這將導致在Lotto對象屬性更改時向UI / View發出信號。
如果Results集合發生變化(添加,刪除了項目),則也需要在其中使用ObservableCollection而不是數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.