我有一个列表选择器,我试图通过使用Mvvm方式绑定。它工作但我不明白为什么当List Picker加载一个值时,我的ViewModel中的属性填充为null。
我将该属性设置为null,我可以让它获取我的Collection中的第一个元素,但我想知道为什么没有触发绑定并且以这种方式填充值。
查看
<Grid x:Name="ContentGrid"
Grid.Row="1">
<Grid.Resources>
<DataTemplate x:Name="PickerItemTemplate">
<StackPanel Orientation="Horizontal">
<Border Background="LightGreen" Width="34" Height="34">
<TextBlock Text="{Binding Country}" FontSize="16" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Border>
<TextBlock Text="{Binding Name}" Margin="12 0 0 0"/>
</StackPanel>
</DataTemplate>
<DataTemplate x:Name="PickerFullModeItemTemplate">
<StackPanel Orientation="Horizontal" Margin="16 21 0 20" d:DataContext="{Binding Cities[0]}">
<TextBlock Text="{Binding Name}" Margin="16 0 0 0" FontSize="43" FontFamily="{StaticResource PhoneFontFamilyLight}"/>
<TextBlock Text="language: "/>
<TextBlock Text="{Binding Language}" Foreground="Green"/>
</StackPanel>
</DataTemplate>
</Grid.Resources>
<toolkit:ListPicker x:Name="listPicker" ExpansionMode="FullScreenOnly" ItemTemplate="{StaticResource PickerItemTemplate}" FullModeItemTemplate="{StaticResource PickerFullModeItemTemplate}" Header="Cities" FullModeHeader="Cities" CacheMode="BitmapCache" Height="110" Margin="12,12,12,0" VerticalAlignment="Top" ItemsSource="{Binding Cities}" SelectedItem="{Binding SelectedCity, Mode=TwoWay}"/>
</Grid>
</Grid>
查看模型
public class MainViewModel : ViewModelBase
{
public ObservableCollection<City> Cities { get; set; }
public MainViewModel()
{
if (ViewModelBase.IsInDesignModeStatic)
{
Cities = new ObservableCollection<City>
{
new City
{
Name = "Vancouver",
Language = "En",
Country = "Canada"
},
new City
{
Name = "Las Vegas",
Language = "En",
Country = "US"
}
};
}
else
{
// live data would go here but in this example, It will be more hardcoded data.
Cities = new ObservableCollection<City>
{
new City
{
Name = "Toronto",
Language = "En",
Country = "Canada"
},
new City
{
Name = "Reno",
Language = "En",
Country = "US"
}
};
}
}
/// <summary>
/// The <see cref="SelectedCity" /> property's name.
/// </summary>
public const string SelectedCityPropertyName = "SelectedCity";
private City selectedCity = null;
/// <summary>
/// Sets and gets the SelectedStore property.
/// Changes to that property's value raise the PropertyChanged event.
/// </summary>
public City SelectedCity
{
get
{
return selectedCity;
}
set
{
if (selectedCity == value)
{
return;
}
RaisePropertyChanging(SelectedCityPropertyName);
selectedCity = value;
RaisePropertyChanged(SelectedCityPropertyName);
}
}
}