将参数传递给wpf中的对象数据提供程序

时间:2017-03-12 15:42:51

标签: wpf

我将int值传递给我的dataprovider类但是我遇到错误,无法弄清楚是什么问题。

错误说:严重性代码描述项目文件行列源 错误MarkupExtension表达式的结束'}'后不允许使用文本''。第13行位置33. ObjectDataProvider D:\ Learing \ WpfApplication1 \ ObjectDataProvider \ MainWindow.xaml 13 33 Build

代码如下。 的 window.xaml

<Window x:Class="ObjectDataProviderExer.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:src="clr-namespace:ObjectDataProviderExer"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <ObjectDataProvider x:Key="Provider" ObjectType="{x:Type src:Student}"
                MethodName="GetStudents">
            <ObjectDataProvider.MethodParameters>
                <sys:Int32>20</sys:Int32>
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>
    </Window.Resources>
    <Grid>
        <DataGrid x:Name="MyGrid" ItemsSource="{Binding Source={StaticResource Provider}}"></DataGrid>
    </Grid>
</Window>

Student.cs

using System.Collections.ObjectModel;
using System.Linq;

namespace ObjectDataProviderExer
{
    public class Student
    {
        private ObservableCollection<Student> _studentsList;

        private int _age;

        public int Age
        {
            get { return _age; }
            set { _age = value; }
        }

        private string _name;

        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        public Student()
        {
            _studentsList = new ObservableCollection<Student>();
        }

        public ObservableCollection<Student> GetStudents(int age)
        {
            CreateStudentCollection();
            return (ObservableCollection<Student>)_studentsList.Where(x => x.Age == age);
        }

        private void CreateStudentCollection()
        {
            _studentsList.Add(new Student() { _age = 10, _name = "Arun" });
            _studentsList.Add(new Student() { _age = 20, _name = "Avinash" });
            _studentsList.Add(new Student() { _age = 14, _name = "Avith" });
            _studentsList.Add(new Student() { _age = 20, _name = "Baskar" });
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您的问题无法重现。您确定已发布正确的XAML标记吗?

无论如何,您的GetStudents方法会抛出异常,因为您试图将IEnumerble<Student>强制转换为ObservableCollection<Student>。这不会起作用,但你可以创建一个新的ObservableCollection<Student>并返回这个:

public ObservableCollection<Student> GetStudents(int age)
{
    CreateStudentCollection();
    return new ObservableCollection<Student>(_studentsList.Where(x => x.Age == age));
}

如果你复制XAML标记,你已经发布到一个新窗口并使用上面的修改运行代码,它应该可以正常工作。