WPF ComboBox selectedValue绑定失败

时间:2015-07-28 12:01:58

标签: wpf xaml combobox

我有var fontStyle = ''; $.ajax({ url : "/chrysofin/fonts/getFonts", success : function(response) { $.each(response, function(index, item ) { var fontName = item.name; var eotFile = item.eotPath; var ttfFile = item.ttfPath; fontStyle += "@font-face {\n" + "\tfont-family: \ "+ fontName+"\;\n" + "\tsrc: url('../invitations/fonts/"+ eotFile +"');\n" + "\tsrc: url('../invitations/fonts/"+ ttfFile +"') format('truetype');\n" + "}\n" ; }); alert(fontStyle); /*CKEDITOR.config.customConfig = function(config) { config.contentsCss = fontStyle; };*/ // CKEDITOR.addCss(fontStyle); $.each(response, function(index, item ) { var fontName = item.name; CKEDITOR.config.font_names = fontName +'/'+fontName + ';' + CKEDITOR.config.font_names; }); }, error : function() { displayError("Error while getting fonts."); }, }); // CKEDITOR.config.contentsCss ='../assets/invitations/fonts/fonts.css'; CKEDITOR.config.font_names = 'Windsong/windsong;' + CKEDITOR.config.font_names; ObservableCollection<Employee>...ObservableCollection<Departments>定义为

Enployee

public class Employee { [Key] public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public DateTime Birthday { get; set; } public int DepId { get; set; } [ForeignKey("DepId")] public virtual Departments Departments { get; set; } } 定义为

Department

在数据库中我有

enter image description here

看起来最后一个ComboBox无法找到属于相应员工的DepId !!任何想法的人?

public class Departments
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual IEnumerable<Employee> Employees { get; set; } 
}

看起来最后一个ComboBox无法找到属于相应员工的DepId !!任何想法的人?

enter image description here

更新:我的viewModel

    <DataGrid  Name="DataGrid1" Grid.Row="3" Margin="10,0,10,10"
               RenderOptions.ClearTypeHint="Enabled"
               TextOptions.TextFormattingMode="Display"
               CanUserAddRows="False"
               CanUserDeleteRows="False"
               SelectionUnit="FullRow" 
               AutoGenerateColumns="false"
               SelectedItem="{Binding CurrentSelectedEmployee, Mode=TwoWay}"
               ItemsSource="{Binding Employees, Mode=TwoWay}">
        <DataGrid.Columns>
            <!--Column 1: Employee Id-->
            <DataGridTextColumn Header="Emplyee Id" Binding="{Binding Id}"/>

            <!--Column 2: First Name-->
            <DataGridTextColumn Header="First Name" Binding="{Binding FirstName}"/>

            <!--Column 3: Last Name-->
            <DataGridTextColumn Header="Last Name" Binding="{Binding LastName}"/>

            <!--Column 4: Birth Day-->
            <DataGridTemplateColumn Header="Birth Day" >
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <DatePicker SelectedDate="{Binding Birthday}"  BorderThickness="0" />
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>

            <!--Column 5: Department Id-->
            <DataGridTemplateColumn Header="Department" >
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <ComboBox ItemsSource="{Binding Departments}"
                                  DisplayMemberPath="Name" SelectedValuePath="Id" SelectedValue="{Binding DepId}" />
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>

        </DataGrid.Columns>
    </DataGrid>

3 个答案:

答案 0 :(得分:1)

现在我看到了问题。当您使用ItemsSource时,ComboBox的每个项都获得与Department实体的绑定,而不是Employee。 Department实体是否有DepId属性?可能不是,这就是问题所在。如果您需要参考员工,您需要这样做。

{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type DataGrid}}, Path=DepId}

Employee.Departments是什么?你确定它已经初始化了吗?

这对我有用:

{
    public partial class MainWindow : Window
    {
        public ObservableCollection<Employee> Employees { get; set; }

        public MainWindow()
        {
            InitializeComponent();
            Department dept1 = new Department() { Id = 1, Name = "aaa" };
            Department dept2 = new Department() { Id = 2, Name = "bbb" };
            Department dept3 = new Department() { Id = 3, Name = "ccc" };

            ObservableCollection<Department> depts = new ObservableCollection<Department>();
            depts.Add(dept1);
            depts.Add(dept2);
            depts.Add(dept3);

            this.Employees = new ObservableCollection<Employee>();
            this.Employees.Add(new Employee() { Id = 1, Birthday = DateTime.Now, FirstName = "aaa", LastName = " aaaa", DepId = 1, Departments = depts });
            this.Employees.Add(new Employee() { Id = 2, Birthday = DateTime.Now, FirstName = "aaa", LastName = " bbbb", DepId = 2, Departments = depts });
            this.Employees.Add(new Employee() { Id = 3, Birthday = DateTime.Now, FirstName = "aaa", LastName = " cccc", DepId = 3, Departments = depts });
            this.Employees.Add(new Employee() { Id = 4, Birthday = DateTime.Now, FirstName = "aaa", LastName = " dddd", DepId = 2, Departments = depts });

            this.DataContext = this;
        }
    }
}

public class Employee
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime Birthday { get; set; }
    public int DepId { get; set; }

    public virtual ObservableCollection<Department> Departments { get; set; }
}

public class Department
{
    public int Id { get; set; }
    public string Name { get; set; }
}

这是XAML:

<DataGrid  Name="DataGrid1" Grid.Row="3" Margin="10,0,10,10"
       RenderOptions.ClearTypeHint="Enabled"
       TextOptions.TextFormattingMode="Display"
       CanUserAddRows="False"
       CanUserDeleteRows="False"
       SelectionUnit="FullRow" 
       AutoGenerateColumns="false"
       SelectedItem="{Binding CurrentSelectedEmployee, Mode=TwoWay}"
       ItemsSource="{Binding Employees, Mode=TwoWay}">
    <DataGrid.Columns>
        <!--Column 1: Employee Id-->
        <DataGridTextColumn Header="Emplyee Id" Binding="{Binding Id}"/>

        <!--Column 2: First Name-->
        <DataGridTextColumn Header="First Name" Binding="{Binding FirstName}"/>

        <!--Column 3: Last Name-->
        <DataGridTextColumn Header="Last Name" Binding="{Binding LastName}"/>

        <!--Column 4: Birth Day-->
        <DataGridTemplateColumn Header="Birth Day" >
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <DatePicker SelectedDate="{Binding Birthday}"  BorderThickness="0" />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>

        <!--Column 5: Department Id-->
        <DataGridTemplateColumn Header="Department" >
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <ComboBox ItemsSource="{Binding Departments}"
                          DisplayMemberPath="Name" SelectedValuePath="Id" SelectedValue="{Binding DepId}" />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>

    </DataGrid.Columns>
</DataGrid>

enter image description here

答案 1 :(得分:0)

请看一下,就像那样:

  <!--Column 5: Department Id-->
                <DataGridTemplateColumn Header="Department" >
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <ComboBox ItemsSource="{Binding Departments}"
                                  DisplayMemberPath="Name" SelectedIndex="0"  SelectedValuePath="Id" SelectedValue="{Binding DepId}" />
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>

enter image description here

和代码背后:

 public partial class MainWindow : Window
    {

        private ObservableCollection<Employee> employees;
        public ObservableCollection<Employee> Employees
        {
            get { return employees; }
            set { employees = value; }
        }

        public MainWindow()
        {
            InitializeComponent();

            this.DataContext= this;

            Department dept1 = new Department() { Id = 1, Name = "aaa" };
            Department dept2 = new Department() { Id = 2, Name = "bbb" };
            Department dept3 = new Department() { Id = 3, Name = "ccc" };


            ObservableCollection<Department> depts = new ObservableCollection<Department>();
            depts.Add(dept1);
            depts.Add(dept2);
            depts.Add(dept3);



            Employees  =new ObservableCollection<Employee>();

            this.Employees.Add(new Employee() { Id = 1, Birthday = DateTime.Now, FirstName = "aaa", LastName = " aaaa", DepId = 1, Departments = depts });
            this.Employees.Add(new Employee() { Id = 2, Birthday = DateTime.Now, FirstName = "aaa", LastName = " bbbb", DepId = 2, Departments = depts });
            this.Employees.Add(new Employee() { Id = 3, Birthday = DateTime.Now, FirstName = "aaa", LastName = " cccc", DepId = 3, Departments = depts });
            this.Employees.Add(new Employee() { Id = 4, Birthday = DateTime.Now, FirstName = "aaa", LastName = " dddd", DepId = 2, Departments = depts });


        }

    }

答案 2 :(得分:0)

在DataGrid中设置ComboBox的ItemsSource的正确方法是这样的:

// simplified datacontext class
public class MainViewModel
{
    public ObservableCollection<Employee> Employees;
    public ObservableCollection<Department> Departments;
}
<DataGrid Name="DataGrid1" ItemsSource="{Binding Employees}">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Emplyee Id" Binding="{Binding Id}"/>
        <DataGridTextColumn Header="First Name" Binding="{Binding FirstName}"/>
        <DataGridTextColumn Header="Last Name" Binding="{Binding LastName}"/>

        <DataGridTemplateColumn Header="Department" >
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <!-- Note the change in the ItemsSource Binding -->
                    <ComboBox ItemsSource="{Binding ElementName=DataGrid1, Path=DataContext.Departments}"
                          DisplayMemberPath="Name" SelectedValuePath="Id" SelectedValue="{Binding DepId}" />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>

    </DataGrid.Columns>
</DataGrid>

通过在这里使用ElementName(或RelativeSource)绑定,我们只需要在主视图模型中维护整个Departments列表的一个副本,而不需要整个Departments的单独副本列出DataGrid中的每个数据项。

但无论如何,您的实际问题似乎是您将ComboBox.ItemsSource设置为Employee.Departments,其定义为

public virtual Departments Departments { get; set; }

由于这不是集合或对象列表,因此ItemsSource无法正确绑定,因此SelectedValue绑定无法按预期工作。