我有ItemsControl,它使用模板绑定数据。
<ItemsControl ItemsSource="{Binding MyCollection}" x:Name="MyCollectionControl" ItemTemplate="{DynamicResource MyCollectionTemplate}" /> MyCollection是NameValueCollection类型,下面的绑定不起作用。它正在填充正确的对数,但TextBlock没有得到有界值。
模板
<DataTemplate x:Key="MyCollectionTemplate">
<Grid>
<TextBlock Text="{Binding Path=Value, Mode=OneWay}"/>
<TextBox Name="CValue"/>
</Grid>
</DataTemplate> mainWindow
string[] dataCollection=new string[5];
....
....
Student studentObject=new Student("1",dataCollection);
this.dataContext = studentObject; 学生班
public class Student
{
public string Id;
public NameValueCollection MyCollection {get; set;}
public Student(string id, params string[] additionalInfo)
{
Id = id;
if (additionalInfo != null)
{
MyCollection=new NameValueCollection();
foreach (string s in MyCollection)
{
string[] tokens = s.Split('|');
if (tokens.Length == 2)
MyCollection.Add(tokens[0], tokens[1]);
}
}
}
}当绑定NameValueCollection时,我做的错误是什么?
请给我建议。
发布于 2013-02-26 04:14:35
好的,有几件事情,其中一件您可能想要更改一下您的DataTemplate,因为您正在将文本框直接覆盖在文本块上,为了测试,我刚刚将它更改为堆栈面板:
<StackPanel>
<TextBlock Text="{Binding}"/>
<TextBox Name="CValue"/>
</StackPanel>还请注意,我更改为简单的Text="{Binding}",因为NameValueCollection中的项只是字符串,没有值属性。
也不确定这是否只是另一个错误,但以下是:
foreach (string s in MyCollection)
{
string[] tokens = s.Split('|');
if (tokens.Length == 2)
MyCollection.Add(tokens[0], tokens[1]);
}应该说:
foreach (string s in additionalInfo)
{
string[] tokens = s.Split('|');
if (tokens.Length == 2)
MyCollection.Add(tokens[0], tokens[1]);
}否则,您只是在对一个空集合进行迭代。
https://stackoverflow.com/questions/15081097
复制相似问题