我正在开发Windows Phone应用程序。我将List绑定到内容控件元素。
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Button Width="100" Margin="163.558,67.567,192.441,453.612" Content="Click" Command="{Binding ClickCommand}"/>
<ContentControl Content="{Binding Strings , Converter={StaticResource Converter},ConverterParameter=0,Mode=TwoWay,UpdateSourceTrigger=Default}"/>
</Grid>
在转换器中,我返回指定参数的字符串。 我的主视图模型如下
private List<string> strings;
public List<string> Strings
{
get
{
return strings;
}
set
{
strings = value;
RaisePropertyChanged("Strings");
}
}
/// <summary>
/// Initializes a new instance of the MainViewModel class.
/// </summary>
public MainViewModel()
{
Strings = new List<string>();
}
private ICommand clickCommand;
public ICommand ClickCommand
{
get
{
clickCommand = new RelayCommand(Click);
return clickCommand;
}
}
private void Click()
{
for (int i = 0; i < 10; i++)
{
string abc = "This is string" + i.ToString();
Strings.Add(abc);
}
}
我希望内容控件显示'This is string 0',但它显示无字符串(当列表为空时,我从转换器返回此信息)。当我在启动时填充列表时,这个问题不会出现,即在视图模型的构造函数中将项添加到列表中。为什么会这样?
如果我绑定元素而不是列表( {Binding Strings [0]} ),它工作正常。
答案 0 :(得分:1)
您需要使用ObservableCollection<T>
代替List<T>
才能使视图检测添加和删除列表项
答案 1 :(得分:0)
当您从列表中添加或删除项时,ObservableCollection会触发CollectionChanged事件。 列表不会触发事件。
您的视图(XAML)永远不会被授予更改,这就是您必须使用ObservableCollection的原因。正如thumbmunkeys所说。