我的ItemsControl的ItemsTemplate绑定不起作用。我查看了一些类似的Stack Overflow问题,但是我无法找出绑定的问题所在。请问有谁能告诉我我的绑定有什么错误吗?
以下是我的MainWindow的ViewModel的摘录;
以下是我的MainWindow的ViewModel的摘录;
private ObservableCollection<uint> words;
private uint word;
private int numberOfWords;
public ObservableCollection<uint> Words
{
get
{
return this.words;
}
set
{
this.words = value;
this.NotifyPropertyChanged(m => m.Words);
}
}
public uint Word
{
get
{
return this.word;
}
set
{
this.word = value;
this.NotifyPropertyChanged(m => m.Word);
}
}
public int NumberOfWords
{
get
{
return this.numberOfWords;
}
set
{
this.numberOfWords = value;
this.NotifyPropertyChanged(m => m.NumberOfWords);
this.Words.Clear();
for (uint x = 0; x < value; x++)
{
this.Words.Add(this.Word);
}
}
}
我在一个用户控件中有以下的ItemsControl。MainWindow将其DataContext设置为ViewModel,而ItemsControl使用该ViewModel。ItemsSource绑定可以工作,并且我可以得到所指定的文本框数量,但是当我在TextBox中输入值时,绑定不起作用。
<ItemsControl Grid.Row="0" Grid.Column="1" Grid.RowSpan="8" ItemsSource="{Binding Words}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBox Text="{Binding Word}" Width="125" Height="25" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
我看到一个帖子讨论了如何使用下面这种绑定方式,但是显然我不理解FindAncestor,所以我不知道是否走在正确的道路上。
Text="{Binding Path=Word, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}}"
Word
属性看起来像是被选中的项目。你为什么想要将每个TextBox.Text
绑定到同一个属性上?你是不是想要使用<TextBox Text="{Binding}" Width="125" Height="25" />
?这会将TextBox
绑定到每个项目上。 - dkozlWord
,而是绑定到每个项目。每个列表只有一个Word
属性,但你有多个TextBox
,不过我忽略了它是uint
,@Will 是正确的。如果你更改TextBox
,它不会更新集合中的元素。 - dkozl