绑定到ItemsControl ItemTemplate内的TextBox

时间:2014-11-18 15:42:01

标签: c# wpf mvvm

我的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设置为ViewConode使用的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}}}"

1 个答案:

答案 0 :(得分:3)

您无法绑定到集合中的元素,然后更改元素本身 - 您只能通过绑定更改此元素的属性。换句话说,给出以下集合

  

[“one”,“two”,“three”]

通过诸如

之类的绑定
<TextBox Text="{Binding Words[0]} /> <!-- the word "one" is displayed in the tb -->

如果您将“one”更改为“derp”,则不会将集合更改为

  

[“derp”,“two”,“three”]

要将此应用于您的示例,您可能希望将集合绑定到ItemsControl,然后在模板中绑定到集合中的每个实例,并更改此实例的属性

首先,创建您的模型。它保存您的数据,并且是您在UI中绑定的内容。

public sealed class Word 
{ 
    public uint Value {get;set;}
}

接下来,在View Model上公开这些集合。

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>

Aristocrats。

相关问题