我在Windows 8.1应用程序中使用C#/ XAML以及MVVM-Light-Toolkit进行了简单的数据绑定,但它不起作用。我想显示一个列表,列出从早上6点到第二天6点的时间。以下是相关代码:
public class DayViewViewModel : ViewModelBase
{
private ObservableCollection<DateTime> _TimesList = null;
/// <summary>
/// Sets and gets the TimesList property.
/// Changes to that property's value raise the PropertyChanged event.
/// </summary>
public ObservableCollection<DateTime> TimesList
{
get
{
return _TimesList;
}
set
{
if (_TimesList == value)
{
return;
}
RaisePropertyChanging(TimesListPropertyName);
_TimesList = value;
RaisePropertyChanged(TimesListPropertyName);
}
}
public void CreateTimes()
{
TimesList = new ObservableCollection<DateTime>();
for (int i = 0; i < 24; i++)
{
TimesList.Add(DateTime.MinValue.AddHours(6 + i));
}
}
}
现在XAML编辑中的绑定:现在显示完整的层次结构:
<ListView>
<ListView.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.7*"/>
<ColumnDefinition Width="2*"/>
</Grid.ColumnDefinitions>
<ListView Grid.Column="0"
ItemsSource="{Binding Day.TimesList, Mode=TwoWay, Source={StaticResource Locator}}"
ItemTemplate="{Binding Source={StaticResource DayCalendarTimesItemTemplate}}">
</ListView>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
模板:
<DataTemplate x:Key="DayCalendarTimesItemTemplate">
<Grid Height="80">
<TextBox Text="{Binding Date}"/>
</Grid>
</DataTemplate>
嗯,我想我绑定到TextBox中的错误对象?我对这个问题感到非常沮丧 - 我无法弄清楚这里有什么问题。
编辑:有关定位器的信息:
定位器是MVVM-Light Toolkit提供的标准定位器:
这是具有该ViewModel注册的类:
public class ViewModelLocator
{
/// <summary>
/// Initializes a new instance of the ViewModelLocator class.
/// </summary>
public ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
SimpleIoc.Default.Register<DayViewViewModel>();
}
public DayViewViewModel Day
{
get
{
return ServiceLocator.Current.GetInstance<DayViewViewModel>();
}
}
}
定位器在App.xaml中实例化:
<Application.Resources>
<ResourceDictionary>
<vm:ViewModelLocator x:Key="Locator"/>
[...]
</ResourceDictionary>
</Application.Resources>
非常感谢你的帮助!
FunkyPeanut
答案 0 :(得分:0)
我已经解决了这个问题。
我上面发布的ListView是在DataTemplate中。我有点忘了提供这些信息。一旦我从模板中删除它,绑定工作正常。