2

我无法绑定到我ObservableCollection<T>的列表框中。

我正在使用 MVVM,WPF。

页面的绑定有效。我的理解是,Grid(未在代码中显示)绑定到 my DataContext,即我的 ViewModel。因此,我ListBox可以通过Itemssource. 我的 Folders 对象非常简单,字面意思是

private ObservableCollection<Folders> _folders;
public ObservableCollection<Folders> Folders 
{
get { return _folders; }
set
  {
      if (value == _folders)
      return;

      _folders = value;
      OnPropertyChanged("Folders");
   }
}

我的文件夹模型是

public class Folders
{
    public string SourceFolder { get; set; }
    public string DestinationFolder { get; set; }
}

最后,我的 XAML

    <ListBox Grid.RowSpan="2" ItemsSource="{Binding Folders, UpdateSourceTrigger=PropertyChanged}" Grid.Row="1" SelectedItem="{Binding SelectedFolderItem}" IsSynchronizedWithCurrentItem="True">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal" DataContext="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}, AncestorLevel=1}, Path=DataContext}">
                    <StackPanel>
                        <TextBlock Text="{Binding SourceFolder}" />
                        <TextBlock Text="{Binding DestinationFolder}" />
                        <Button Content="Edit" Command="{Binding EditCommand}" CommandParameter="{Binding SelectedListItem}"/>
                    </StackPanel>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

按钮绑定/执行,但 2 个文本块没有。我也试过

 <TextBlock Text="{Binding Folders.SourceFolder}" />
 <TextBlock Text="{Binding Folders.DestinationFolder}" />

但这是同一个问题。内容不显示(不绑定),因为如果我在 ViewModel 上添加手表,我可以看到值是它们应该的样子。

如果有帮助,如果我将代码更新为

 <TextBlock Text="{Binding SelectedFolderItem.SourceFolder}" />
 <TextBlock Text="{Binding SelectedFolderItem.DestinationFolder}" />

然后它可以工作,尽管这不是我们所希望的(它只是循环正确的次数,但只针对 1 个项目!)。

有人能指出我正确的方向吗?

4

1 回答 1

3

您正在设置不同的 DataContext。你不需要那个,否则你会破坏项目模板的目的。

<StackPanel Orientation="Horizontal">
    <StackPanel>
        <TextBlock Text="{Binding SourceFolder}" />
        <TextBlock Text="{Binding DestinationFolder}" />
        <Button Content="Edit"
                Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}, Path=DataContext.EditCommand}"
                CommandParameter="{Binding}"/>
    </StackPanel>
</StackPanel>

当然,如果您希望按钮也能正常工作,您只需将当前拥有的相对源移动到按钮的绑定即可。

于 2013-06-12T14:44:42.577 回答