将ViewModel绑定到Listview的问题

时间:2013-08-18 23:08:00

标签: c# wpf mvvm wpf-controls

我的观点模型

public class ExchangeViewModel : ViewModelBase
{
    ObservableCollection<string> _repo = new ObservableCollection<string>()
    {
        "CME",
        "CFE",
        "LIFFE"
    };

    #region Properties

    public ObservableCollection<string> Exchanges
    {
        get
        {
            return _repo;
        }
    }

    #endregion // Properties

    #region Constructors
    public ExchangeViewModel() { }



    #endregion // Constructors

}

我的观点

<Window x:Class="ListviewTest.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>
    <ListView 
            Grid.Row="0" 
            Grid.Column="0"
            SelectionMode="Single"
            DataContext="{Binding}"
            >
        <ListView.View>
            <GridView>
                <GridViewColumn
                        DisplayMemberBinding="{Binding Exchanges}"
                        Header = "Exchange"
                        >
                </GridViewColumn>
            </GridView>
        </ListView.View>
    </ListView>

</Grid>

我在app.xaml.cs中将它们绑定在一起

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);

        MainWindow window = new MainWindow();

        // Create the ViewModel to which 
        // the main window binds.
        //string path = "Data/customers.xml";
        ExchangeViewModel viewModel = new ExchangeViewModel();



        // Allow all controls in the window to 
        // bind to the ViewModel by setting the 
        // DataContext, which propagates down 
        // the element tree.
        window.DataContext = viewModel;

        window.Show();
    }
}

但是当我运行应用程序时,我的listview为空。我的绑定交换属性甚至没有得到调用,这表明我的绑定没有正确完成。

1 个答案:

答案 0 :(得分:0)

您必须为ListView指定ItemsSource。试试这个:

<ListView ItemsSource="{Binding Exchanges}"
        Grid.Row="0" 
        Grid.Column="0"
        SelectionMode="Single" >
        <ListView.View>
            <GridView>
                <GridViewColumn
                    DisplayMemberBinding="{Binding}"
                    Header = "Exchange">
                </GridViewColumn>
            </GridView>
        </ListView.View>
    </ListView>
相关问题