【问题标题】:GridView databinding issueGridView 数据绑定问题
【发布时间】:2013-12-27 01:28:31
【问题描述】:

GridView 数据绑定有问题。

我在 ViewModelGV.cs 文件中创建了一个视图模型。

class ViewModelGV
{

    public ObservableCollection<Person> Persons{ get; set; }          

    public ViewModelGV()
    {
        Persons = new ObservableCollection<Person>();
        Person person1 = new Person();
        person1.Name = "John";
        Persons.Add(person1);

        Person person2 = new Person();
        person2.Name = "Jack";
        Persons.Add(person2);

        Person person3 = new Person();
        person3.Name = "Stephen";
        Persons.Add(person3);
    }
}

还有另一类具有简单 Name 属性的人。

class Person
{
    private String _Name;

    public String Name
    {
        get { return _Name; }
        set { _Name = value; }
    } 
}

然后在我的 XAML 文件中,我将 DataContext 指向我的 ViewModelGV(我添加了一些问号来标记代码中的重要点)。

<Page.DataContext>
    <ViewModels:ViewModelGV/>
</Page.DataContext>

并添加了 CollectionViewSource

<Page.Resources>
    <CollectionViewSource x:Name="Src" IsSourceGrouped="False" ItemsPath="?" Source="{Binding Persons}" />
</Page.Resources>

我不知道如何指向特定的项目名称值,它可能与 ItemsPath 属性有关。

然后在我的 GridView 中,我想创建一个 StackPanel,下面有 Rectangle 和 TextBlock。

<Grid x:Name="LayoutGrid" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <GridView ItemsSource="{Binding Source={StaticResource Src}}">
        <GridView.GroupStyle>
            <GroupStyle>
                <GroupStyle.Panel>
                    <ItemsPanelTemplate>
                        <StackPanel>
                            <Rectangle Fill="Red" Width="100" Height="100" />
                            <TextBlock Text="{Binding ? Name ? }" FontSize="40" />
                        </StackPanel>
                    </ItemsPanelTemplate>
                </GroupStyle.Panel>
            </GroupStyle>
        </GridView.GroupStyle>
    </GridView>   
    <TextBlock Text="{Binding Persons.Count}" Margin="0,200,0,0"></TextBlock>
</Grid>

这是显示正确计数但不正确的模板和人员数据的结果

【问题讨论】:

    标签: c# xaml data-binding windows-8


    【解决方案1】:

    我最近做了类似的事情并让它工作。尝试将您的 xaml 更改为以下内容

    <GridView ItemsSource="{Binding Path=Persons, Mode=TwoWay}">
    

    <TextBlock Text="{Binding Name}" FontSize="40"/>
    

    我没有使用集合视图源,只是直接绑定到我的视图模型中的可观察集合。希望这会有所帮助。

    【讨论】:

      【解决方案2】:

      你试过了吗:

      <TextBlock Text="{Binding Person.Name}" FontSize="40" />
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-03-12
        • 1970-01-01
        • 1970-01-01
        • 2013-10-11
        • 1970-01-01
        • 2017-07-20
        相关资源
        最近更新 更多