简体   繁体   English

WPF网格中包含多个列的ItemSource绑定

[英]ItemSource Binding in WPF grid that contains multiple columns

I am learning WPF following the MVVM pattern, I have come across an issue in XAML where I am binding the ItemSource for a grid I have. 我正在按照MVVM模式学习WPF,我在XAML中遇到了一个问题,其中我将ItemSource绑定到我拥有的网格中。 Currently I am binding each column to a Public Property that exists in my Model which works fine. 目前,我将每列绑定到模型中存在的公共属性,该公共属性可以正常工作。

The issue I am having is that I do not know what to bind the Grids ItemSource too, as previously I have bound this to a Property, but when doing this is will only display the data for that one Property, is there a way I can bind this so I can display data for both columns. 我遇到的问题是我也不知道该如何绑定Grids ItemSource,因为以前我已将其绑定到Property,但是这样做时将仅显示该Property的数据,有没有办法绑定此,以便我可以显示两个列的数据。 Thanks, 谢谢,

MainWindow.Xaml MainWindow.Xaml

    <ListView Name="UserGrid" Grid.Row="1" Margin="4,178,12,13"  ItemsSource="{Binding ClientRatesPreAwr}"  >
        <ListView.View>
            <GridView x:Name="grdTest">
                <GridViewColumn Header="PreAWR" DisplayMemberBinding="{Binding ClientRatesPreAwr}"  Width="50"/>
                <GridViewColumn Header="PostAWR" DisplayMemberBinding="{Binding ClientRatesPostAwr}"  Width="50"/>
            </GridView>
        </ListView.View>
    </ListView>

Model: 模型:

public string ClientRatesPreAwr
    {
        get { return _ClientRatePreAWR; }
        set
        {
            _ClientRatePreAWR = value;
            OnPropertyChanged("ClientRatesPreAWR");
        }
    }

    public string ClientRatesPostAwr
    {
        get { return _ClientRatePostAWR; }
        set
        {
            _ClientRatePostAWR = value;
            OnPropertyChanged("ClientRatesPostAwr");
        }
    }

ListView ItemSource应该绑定到模型/视图模型中的(ClientRates?)项目的集合,而不是单个属性。

You have to bind ListView to an ObservableCollection<T> like following example 您必须将ListView绑定到ObservableCollection<T>如以下示例所示

<ListView Name="Items" ItemsSource={Binding Items}>
    <ListView.View>
        <GridView>
            <GridViewColumn Width="200" Header="First name" DisplayMemberBinding="{Binding FirstName}"></GridViewColumn>
            <GridViewColumn Width="200" Header="Last name" DisplayMemberBinding="{Binding LastName}"></GridViewColumn>
        </GridView>
    </ListView.View>
</ListView>

private ObservableCollection<Contact> items;
public ObservableCollection<Contact> Items
{
    get { return items; }
    set
    {
        if (value != items)
        {
            items = value;
            NotifyOfPropertyChange(() => Items);
        }
    }
}

Moreover I suggest to use Caliburn.Micro MVVM framework. 此外,我建议使用Caliburn.Micro MVVM框架。 It is easy to use and comfortable. 它易于使用且舒适。 Here is a basic example for applying Caliburn.Micro 这是应用Caliburn.Micro 的基本示例

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

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