当我试图学习数据绑定时,我发现其中一个快速启动示例无效。你能告诉我它是错还是我错了?
该示例使用CollectionView Source和ObservableCollection类将数据动态绑定到UI元素。我使用了listpicker而不是组合框。然而,当列表选择器中的选择发生变化时,我发现文本块没有改变。 我是否必须实施更改的INotifyProperty?以下是我的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
答案 0 :(得分:1)
当您像这样修改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>
您需要将listpicker的所选项目绑定到文本块,以便在更改选择时更新文本块。不知道是否有更好的方法来做到这一点。无论如何,这解决了这个问题。
Alfah