简体   繁体   English

绑定ObservableCollection <string> 到ListView

[英]Binding an ObservableCollection<string> to a ListView

This should be really easy, I just want to update the listview when the user adds something in the textbox to my observable collection. 这应该非常简单,我只想在用户将文本框中的内容添加到我的可观察集合时更新列表视图。

I don't understand why I can't get this working: 我不明白为什么我不能这样做:

XAML XAML

<Window x:Class="MyStuff.WPF.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Height="486" Width="540" WindowStyle="SingleBorderWindow" ResizeMode="NoResize" >
    <Grid>
        <Menu IsMainMenu="True" VerticalAlignment="Top" HorizontalAlignment="Stretch" FlowDirection="LeftToRight">
            <MenuItem Header="File" >
                <MenuItem Header="Open File..">
                </MenuItem>
                <MenuItem Header="Exit">
                </MenuItem>
            </MenuItem>               
        </Menu>
        <TextBox Height="36" HorizontalAlignment="Left" Margin="12,27,0,0" Name="textBoxSearchTerm" VerticalAlignment="Top" Width="414" FontSize="24" MaxLength="80" AcceptsReturn="False" Background="#FFFFFFE8" Text="asdfasdf" FontWeight="Bold" FontFamily="Calibri" FontStretch="Normal" />
        <Button Content="Add" Height="36" HorizontalAlignment="Left" Margin="435,27,0,0" VerticalAlignment="Top" Width="68" FontSize="20" FontWeight="Normal" FontFamily="Calibri" Click="AddSearchTerm_Click" />

        <ListView Height="338" HorizontalAlignment="Left" Margin="12,97,0,0" Name="listView1" VerticalAlignment="Top" Width="261" ItemsSource="{Binding SearchTerms}">
        <ListView.View>
            <GridView>
                <GridViewColumn Width="120" Header="Search Term" DisplayMemberBinding="{Binding}" />
            </GridView>
        </ListView.View>
    </ListView>

    </Grid>
</Window>

Code Behind 代码背后

public partial class MainWindow : Window
{
    public ObservableCollection<string> searchItems = new ObservableCollection<string>();

    public MainWindow()
    {
        InitializeComponent();
    }

    // DEFINE A PROPERTY..
    public ObservableCollection<string> SearchItems
    {
        get { return searchItems; }
    }

    private void AddSearchTerm_Click(object sender, RoutedEventArgs e)
    {
        searchItems.Add(textBoxSearchTerm.Text);
    }
}

How do I reference each item in SearchTerms Here? 如何在SearchTerms中引用每个项目? I can do DisplayMemberPath="{Binding SomeProperty}" But what if I just want the actual object, like a string? 我可以做DisplayMemberPath =“{Binding SomeProperty}”但是如果我只想要实际的对象,比如字符串呢?

To bind to the item itself, just use {Binding} . 要绑定到项目本身,只需使用{Binding}

For details, and as a resource, refer to the WPF Binding CheatSheet - this is the first listed binding option. 有关详细信息以及作为资源,请参阅WPF Binding CheatSheet - 这是第一个列出的绑定选项。

To me it seems that the problem is that you're binding to your class field . 对我来说,问题似乎是你绑定到你的类字段 Define it like a property , instead, and it should work. 相反,它定义为属性 ,它应该工作。

EDIT 编辑

I noticed that you don't assign a DataContext of you window, which leads to NO binding. 我注意到你没有为你的窗口分配一个DataContext ,这导致没有绑定。

1) Move the collection to separate class (some DataLayer class) 1)将集合移动到单独的类(某些DataLayer类)

2) Assign to Window's DataContext property an instance of that class. 2)为Window的DataContext属性分配该类的实例。 In this case you binding in list view, has to look something like this: 在这种情况下,您在列表视图中绑定,必须看起来像这样:

<ListView ... ItemsSource="{Binding Path=SearchTerms}">

After inside your back code use exactly the same instance of the class which was assigned to Window's DataContext property to Add/Remove elements from collection. 在你的后面代码内部使用与分配给Window的DataContext属性的类完全相同的实例来添加/删除集合中的元素。

Hope this helps. 希望这可以帮助。

Tigrans answer is correct with regards to setting the datacontext. 关于设置datacontext,Tigrans的回答是正确的。 This is required to do databinding. 这是进行数据绑定所必需的。 There are a number of ways this can be accomplished but the easiest way would be to set the datacontext to your viewmodel (SearchItems). 有许多方法可以实现,但最简单的方法是将datacontext设置为viewmodel(SearchItems)。

public MainWindow()
{
    InitializeComponent();
    this.DataContext = SearchItems;
}

Then your binding would look like <ListView ... ItemSource={Binding}> Also you have {Binding SearchTerm} a couple times but i do not see a property that it would be binding to (maybe a typo). 然后你的绑定看起来像<ListView ... ItemSource={Binding}>你也有{Binding SearchTerm}几次,但我没有看到它将绑定的属性(可能是一个错字)。

Another option for binding the DataContext is to set it to the control itself: 绑定DataContext的另一个选项是将其设置为控件本身:

this.DataContext = this;

This will change your binding expressions to {Binding Path=SearchItems} as this will tell the binding engine to look for the SearchItems property on the current datacontext. 这会将绑定表达式更改为{Binding Path=SearchItems}因为这将告诉绑定引擎在当前datacontext上查找SearchItems属性。

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM