WP7中数据绑定快速入门示例的问题
本文关键字:问题 数据绑定 WP7 | 更新日期: 2023-09-27 18:11:00
当我尝试学习数据绑定时,我发现其中一个快速入门示例不起作用。你能告诉我是错了还是我弄错了吗?
http://create.msdn.com/en-US/education/quickstarts/Data_Binding_to_Controls DisplayingItemsWithDataTemplate
示例使用collectionviewsource和ObservableCollection类来动态地将数据绑定到UI元素。我使用了一个列表选择器而不是一个组合框。然而,我发现文本块不会随着列表选择器中的选择改变而改变。我是否必须实现INotifyProperty Changed?以下是我的c#代码
namespace binding3
{
public partial class MainPage : PhoneApplicationPage
{
public ObservableCollection<Recording> MyMusic = new ObservableCollection<Recording>();
// Constructor
public MainPage()
{
InitializeComponent();
MyMusic.Add(new Recording("Chris Sells", "Chris Sells Live", new DateTime(2008, 2, 5)));
MyMusic.Add(new Recording("Luka Abrus", "The Road to Redmond", new DateTime(2007, 4, 3)));
MyMusic.Add(new Recording("Jim Hance", "Best of Jim Hance", new DateTime(2007, 3, 6)));
//listPicker1.DataContext = MyMusic;
//RecordingDetails.DataContext = new CollectionViewSource { Source = MyMusic };
LayoutRoot.DataContext = new CollectionViewSource { Source = MyMusic };
}
public class Recording
{
public Recording() { }
public Recording(string artistName, string cdName, DateTime release)
{
Artist = artistName;
Name = cdName;
ReleaseDate = release;
}
public string Artist { get; set; }
public string Name { get; set; }
public DateTime ReleaseDate { get; set; }
public override string ToString()
{
return Name + " by " + Artist + ", Released: " + ReleaseDate.ToShortDateString();
}
}
这是xaml设计
<!--ContentPanel - place additional content here-->
<StackPanel x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<toolkit:ListPicker Height="150" HorizontalAlignment="Left" Margin="5" x:Name="listPicker1"
VerticalAlignment="Top" Width="400" ItemsSource="{Binding}" FontSize="18">
<toolkit:ListPicker.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Margin="2">
<TextBlock Text="Artist:" Margin="2"/>
<TextBlock Text="{Binding Artist}" Margin="2"/>
<TextBlock Text="CD:" Margin="10,2,0,2"/>
<TextBlock Text="{Binding Name}" Margin="2"/>
</StackPanel>
</DataTemplate>
</toolkit:ListPicker.ItemTemplate>
</toolkit:ListPicker>
<StackPanel x:Name="RecordingDetails">
<TextBlock Text="{Binding Artist}" Margin="5,0,0,0"/>
<TextBlock Text="{Binding Name}" Margin="5,0,0,0"/>
<TextBlock Text="{Binding ReleaseDate}" Margin="5,0,0,0"/>
</StackPanel>
</StackPanel>
谢谢你,
Alfah
当您像这样修改xaml时,代码可以工作
<StackPanel x:Name="RecordingDetails">
<TextBlock Text="{Binding SelectedItem.Artist, ElementName= listPicker1}" Margin="5,0,0,0"/>
<TextBlock Text="{Binding SelectedItem.Name, ElementName= listPicker1}" Margin="5,0,0,0"/>
<TextBlock Text="{Binding SelectedItem.ReleaseDate,ElementName= listPicker1}" Margin="5,0,0,0"/>
</StackPanel>
您需要将列表选择器的选定项绑定到文本块,以便在选择更改时更新文本块。我不知道是否有更好的方法。无论如何,这解决了问题。
Alfah