0

Sry fot the title, if you have a better please edit.

I have a working code if I use a object create in wpf in resources like this:

<local:PersonView x:Key="Persons"/>

But I want to use a object created in mainwindow, here is the working code:

    <Grid>
        <Grid.Resources>
            <local:PersonView x:Key="Persons"/>
            <CollectionViewSource x:Key="ViewPersons" Source="{Binding Source={StaticResource Persons}, Path=Persons}">
                <CollectionViewSource.GroupDescriptions>
                    <PropertyGroupDescription PropertyName="Name"/>
                </CollectionViewSource.GroupDescriptions>
            </CollectionViewSource>
        </Grid.Resources>
        <ListView ItemsSource="{Binding Source={StaticResource ViewPersons}}">
            <ListView.View>
                <GridView>
                    <GridViewColumn Width="100" Header="Name" DisplayMemberBinding="{Binding Name}"/>
                </GridView>
            </ListView.View>
        </ListView>
    </Grid>

The classes I use:

    public class Person
    {
        public string Name { get; set; }
    }

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

        public PersonView()
        {
            Persons = new ObservableCollection<Person>();
            Persons.Add(new Person() { Name = "Luis" });
            Persons.Add(new Person() { Name = "Gusth" });
        }
    }

This code work, but I want to bind the CollectionViewSource to object created in mainwindow:

    public partial class MainWindow : Window
    {
        public PersonView BindThis { get; set; }

        public MainWindow()
        {
            InitializeComponent();

            BindThis = new PersonView();
        }
    }

I try this but dont work:

<CollectionViewSource x:Key="ViewPersons" Source="{Binding RelativeSource={RelativeSource AncestorType=Window}, Path=BindThis}">
                <CollectionViewSource.GroupDescriptions>
                    <PropertyGroupDescription PropertyName="Name"/>
                </CollectionViewSource.GroupDescriptions>
            </CollectionViewSource>
4

1 回答 1

1

抱歉,我花了很长时间试图解决这个问题。但现在我让它工作了。这个绑定的东西还是让我很困惑。希望它可以帮助某人。

修复:

public class PersonView : ObservableCollection<Person>
{
    public PersonView()
    {
        Add(new Person() { Name = "Luis" });
        Add(new Person() { Name = "Gusth" });
    }
}
于 2012-08-15T23:39:08.167 回答