[英]Binding to a TextBox inside an ItemsControl ItemTemplate
我的ItemsControl ItemsTemplate上的綁定不起作用。 我已經經歷了其他一些類似的堆棧溢出問題,但無法確定綁定問題。 有人可以告訴我我的約束力在做什么嗎?
從我的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設置為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}}}"
您不能綁定到集合中的元素,然后更改元素本身-您只能通過綁定來更改此元素的屬性 。 換句話說,給定以下集合
[ “一二三” ]
通過諸如
<TextBox Text="{Binding Words[0]} /> <!-- the word "one" is displayed in the tb -->
如果將“一個”更改為“ derp”,則不會將集合更改為
[“ derp”,“兩個”,“三個”]
要將其應用於您的示例,您需要將集合綁定到ItemsControl,然后在模板中綁定到集合內的每個實例並更改該實例的屬性 。
首先,創建您的模型。 這將保存您的數據,並且是您在UI中綁定的數據。
public sealed class Word
{
public uint Value {get;set;}
}
接下來,在您的視圖模型上公開這些集合。
public sealed class ViewModel
{
//create and fill in ctor
public ObservableCollection<Word> WordsYo {get;private set;}
}
接下來,將ItemsControl的ItemsSource綁定到此屬性,並將模板中的元素綁定到Word的屬性:
<!-- Window.DataContext is set to an instance of ViewModel -->
<ItemsControl ItemsSource="{Binding WordsYo}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBox Text="{Binding Value}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
貴族。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.