如何将我的列表框绑定到自己的部分类?

时间:2015-01-21 14:20:50

标签: c# wpf xaml data-binding

我遇到一个小问题,假设我有以下 MainWindow.xaml

<Window x:Class="DragDrop.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <ListBox Name="ListBoxLeft"  />
        <ListBox Name="ListBoxRight"  Grid.Column="1" />
    </Grid>
</Window>

现在我只想将<ListBox Name="ListBoxLeft" />绑定到我的属性public List<User> UserListLeft;。我怎样才能做到这一点?我应该如何指定DataContext?

所有属性都只是在 MainWindow.xaml.cs 中列出。

注意:我不使用MVVM模型。

由于

1 个答案:

答案 0 :(得分:2)

在MainWindow.xaml.cs的构造函数中添加:

DataContext=this;

然后在您的MainWindow.xaml中添加:

 <ListBox Name="ListBoxRight"  Grid.Column="1" ItemSource={Binding UserListLeft} />

请将您的UserListLeft设为ObservableCollection,而不是List。能够通知视图的任何更改。