本文介绍了数据表中的组合框绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实际上正在创建一个WPF DataGrid自定义控件。
想要这个combobos应该显示在组合框中的性别,当我将组合框保持在datatemplate之外时,它是什么东西,但是在datatemplate里面是不起作用的。请帮助我?

 < UserControl x:Class =Custom_DataGrid.Grid3.Grid3
xmlns =http ://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x =http://schemas.microsoft.com/winfx/2006/xaml
xmlns:mc = http://schemas.openxmlformats.org/markup-compatibility/2006
xmlns:d =http://schemas.microsoft.com/expression/blend/2008
mc:Ignorable = dxmlns:sdk =http://schemas.microsoft.com/wpf/2008/toolkit
d:DesignHeight =300d:DesignWidth =300>
< UserControl.Resources>

< DataTemplate x:Key =dueDateCellTemplate>
< TextBlock Text ={Binding DOB}Margin =5,4,5,4/>
< / DataTemplate>
< DataTemplate x:Key =dueDateCellEditingTemplate>
< DatePicker SelectedDate ={Binding DOB,Mode = TwoWay}/>
< / DataTemplate>

< DataTemplate x:Key =GenderCellTemplate>
< TextBlock Text ={Binding GENDER.Gender}Margin =5,4,5,4/>
< / DataTemplate>
< DataTemplate x:Key =genderCellEditingTemplate>
<! - < ComboBox ItemsSource ={Binding Genders}SelectedItem ={Binding Genders}SelectedValue ={Binding Path = GENDER,ElementName = Id}DisplayMemberPath =IdSelectedValuePath =性别>< / ComboBox> - >
< ComboBox x:Name =c1ItemsSource ={Binding Genders}DisplayMemberPath =IdHeight =50Width =100>< / ComboBox>
<! - < TextBlock Text ={Binding Genders.Gender}Foreground =Khaki>< / TextBlock> - >
< / DataTemplate>

< /UserControl.Resources>
< Grid>
< DataGrid x:Name =datagrid3AutoGeneratingColumn =datagrid3_AutoGeneratingColumnItemsSource ={Binding Employees}Foreground =SteelBlue>< / DataGrid>

< / Grid>
< / UserControl>





  public enum指定
{
销售,开发,人力资源,BackOffice
}

public class Sex
{
private string id;
私人字符串gen;

public string Id
{
get
{
return id;
}
set
{
id = value;
}
}

public string Gender
{
get
{
return gen;
}
set
{
gen = value;
}
}

}

public class DataSource
{
ObservableCollection< Employee> empList = new ObservableCollection< Employee>();
列表<性别> genders = new List< Sex>();



public DataSource()
{

empList.Add(new Employee(){ID = 1,NAME =Neeraj ,DOB = Convert.ToDateTime(12/03/1986),EMAIL [email protected],GENDER = new Sex(){Id =M,Gender =Male},PHONE = 9999999999,ACTIVE = false,DESIGNATION = Designation.Development});
empList.Add(new Employee(){ID = 2,NAME =Mayank,DOB = Convert.ToDateTime(01/01/1986),EMAIL [email protected],GENDER = new Sex(){Id =M,Gender =Male},PHONE =9999999999,ACTIVE = true,DESIGNATION = Designation.BackOffice});
empList.Add(new Employee(){ID = 1,NAME =Neeraj,DOB = Convert.ToDateTime(12/03/1986),EMAIL [email protected],GENDER = new Sex(){Id =M,Gender =Male},PHONE =9999999999,ACTIVE = false,DESIGNATION = Designation.Development});
empList.Add(new Employee(){ID = 2,NAME =Mayank,DOB = Convert.ToDateTime(01/01/1986),EMAIL [email protected],GENDER = new Sex(){Id =M,Gender =Male},PHONE =9999999999,ACTIVE = true,DESIGNATION = Designation.BackOffice});
empList.Add(new Employee(){ID = 1,NAME =Neeraj,DOB = Convert.ToDateTime(12/03/1986),EMAIL [email protected],GENDER = new Sex(){Id =M,Gender =Male},PHONE =9999999999,ACTIVE = false,DESIGNATION = Designation.Development});
empList.Add(new Employee(){ID = 2,NAME =Mayank,DOB = Convert.ToDateTime(01/01/1986),EMAIL [email protected],GENDER = new Sex(){Id =M,Gender =Male},PHONE =9999999999,ACTIVE = true,DESIGNATION = Designation.BackOffice});

genders.Add(new Sex(){Id =M,Gender =Male});
genders.Add(new Sex(){Id =F,Gender =Female});


}




public ObservableCollection< Employee>员工
{
get
{
return empList;
}
set
{
empList = value;
}
}

public List< Sex>性别
{
get
{
return genders;
}
set
{
genders = value;
}
}


}

xaml.cs文件的编码

  using System; 
使用System.Collections.Generic;
使用System.Linq;
使用System.Text;
使用System.Windows;
使用System.Windows.Controls;
使用System.Windows.Data;
使用System.Windows.Documents;
使用System.Windows.Input;
使用System.Windows.Media;
使用System.Windows.Media.Imaging;
使用System.Windows.Navigation;
使用System.Windows.Shapes;




命名空间Custom_DataGrid.Grid3
{
///< summary>
/// Grid3.xaml的交互逻辑
///< / summary>
public partial class Grid3:UserControl
{
public Grid3()
{
InitializeComponent();
this.DataContext = new DataSource();
}

private void datagrid3_AutoGeneratingColumn(object sender,DataGridAutoGeneratingColumnEventArgs e)
{
if(e.PropertyName.ToLower()。ToString()。Equals(id ))
{
e.Column.Header =Employee Id;
}
else if(e.PropertyName.ToLower()。Equals(name))
{
e.Column.Header =Employee Name;
}
else if(e.PropertyName.ToLower()。Equals(dob))
{
e.Column.Header =Employee DOB;
if(e.PropertyType == typeof(DateTime))
{
DataGridTemplateColumn templateColumn = new DataGridTemplateColumn();
templateColumn.Header =Employee DOB;
templateColumn.CellTemplate =(DataTemplate)资源[dueDateCellTemplate];
templateColumn.CellEditingTemplate =(DataTemplate)资源[dueDateCellEditingTemplate];
templateColumn.SortMemberPath =DueDate;
e.Column = templateColumn;
}
}
else if(e.PropertyName.ToLower()。Equals(phone))
{
e.Column.Header =员工电话;
e.Cancel = true;
}
else if(e.PropertyName.ToLower()。Equals(email))
{
e.Column.Header =Employee Email;
}
else if(e.PropertyName.ToLower()。Equals(gender))
{
e.Column.Header =Employee Gender;
DataGridTemplateColumn templateColumn = new DataGridTemplateColumn();
templateColumn.Header =员工性别;
templateColumn.CellTemplate =(DataTemplate)资源[genderCellTemplate];
templateColumn.CellEditingTemplate =(DataTemplate)资源[genderCellEditingTemplate];
e.Column = templateColumn;
}
else if(e.PropertyName.ToLower()。Equals(active))
{
e.Column.Header =Employee Active / InActive;
}
else if(e.PropertyName.ToLower()。Equals(names))
{
e.Column.Header =Employee Nameation;
}
}



}
}

所以我试图在celleditingtemplate中使用combobxo创建模板列,每一件事情都可以正常工作,但是在datatemplate里面是不行的。
请帮我吗检查我已经评论的文本框工作正常...

解决方案

如果您在DataTemplate内,DataContext将作为被模板化的对象。所以你的绑定,相对于DataContext,如果只有一个绑定路径被指定将找不到ItemsSource。



通常你可以使用一个 RelativeSource -binding以找到仍然具有可以找到ItemsSource的DataContext的控件。 (请参阅RV1987的答案;我以为没有更早的工作,因为如果你有一个 DataGridComboBoxColumn 相同的RelativeSource-ItemsSource绑定将不工作,这是因为它自己的列是抽象的,并不会出现在树中,而不像模板创建的控件



由于UserControl的DataContext应该是您正在寻找的,您可以命名您的UserControl(例如, control ),并按以下方式绑定:

  ItemsSource ={Binding Source = {x:Reference control},Path = DataContext.Genders}

(请注意,是相当新的,它不存在于.NET 3.5中,使用 ElementName = control 而不是工作)


Hi i am actually creating a WPF DataGrid Custom Control.What is want this combobos should show the genders in the combobox and what is heppening when i am keeping the combobox outside the datatemplate its working but inside the datatemplate it is not working. Please help me ?

<UserControl x:Class="Custom_DataGrid.Grid3.Grid3"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d" xmlns:sdk="http://schemas.microsoft.com/wpf/2008/toolkit"
             d:DesignHeight="300" d:DesignWidth="300" >
    <UserControl.Resources>

        <DataTemplate x:Key="dueDateCellTemplate">
            <TextBlock Text="{Binding DOB}" Margin="5,4,5,4"/>
        </DataTemplate>
        <DataTemplate x:Key="dueDateCellEditingTemplate">
            <DatePicker SelectedDate="{Binding DOB, Mode=TwoWay}"/>
        </DataTemplate>

        <DataTemplate x:Key="genderCellTemplate">
            <TextBlock Text="{Binding GENDER.Gender}" Margin="5,4,5,4"/>
        </DataTemplate>
        <DataTemplate x:Key="genderCellEditingTemplate">
            <!--<ComboBox ItemsSource="{Binding Genders}" SelectedItem="{Binding Genders}" SelectedValue="{Binding Path=GENDER, ElementName=Id}" DisplayMemberPath="Id" SelectedValuePath="Gender"></ComboBox>-->
            <ComboBox x:Name="c1" ItemsSource="{Binding Genders}" DisplayMemberPath="Id"  Height="50" Width="100"></ComboBox>
            <!--<TextBlock Text="{Binding Genders.Gender}" Foreground="Khaki"></TextBlock>-->
        </DataTemplate>

    </UserControl.Resources>
    <Grid>
        <DataGrid x:Name="datagrid3" AutoGeneratingColumn="datagrid3_AutoGeneratingColumn" ItemsSource="{Binding Employees}" Foreground="SteelBlue"></DataGrid>

    </Grid>
</UserControl>
public enum Designation
    {
        Sales, Development, HR, BackOffice
    }

public class Sex
    {
        private string id;
        private string gen;

        public string Id
        {
            get
            {
                return id;
            }
            set
            {
                id = value;
            }
        }

        public string Gender
        {
            get
            {
                return gen;
            }
            set
            {
                gen = value;
            }
        }

    }

public class DataSource
    {
        ObservableCollection<Employee> empList = new ObservableCollection<Employee>();
        List<Sex> genders = new List<Sex>();



        public DataSource()
        {

            empList.Add(new Employee() { ID = 1, NAME = "Neeraj", DOB = Convert.ToDateTime("12/03/1986"), EMAIL = "[email protected]", GENDER = new Sex() { Id = "M", Gender = "Male" }, PHONE = "9999999999", ACTIVE = false, DESIGNATION = Designation.Development });
            empList.Add(new Employee() { ID = 2, NAME = "Mayank", DOB = Convert.ToDateTime("01/01/1986"), EMAIL = "[email protected]", GENDER = new Sex() { Id = "M", Gender = "Male" }, PHONE = "9999999999", ACTIVE = true, DESIGNATION = Designation.BackOffice });
            empList.Add(new Employee() { ID = 1, NAME = "Neeraj", DOB = Convert.ToDateTime("12/03/1986"), EMAIL = "[email protected]", GENDER = new Sex() { Id = "M", Gender = "Male" }, PHONE = "9999999999", ACTIVE = false, DESIGNATION = Designation.Development });
            empList.Add(new Employee() { ID = 2, NAME = "Mayank", DOB = Convert.ToDateTime("01/01/1986"), EMAIL = "[email protected]", GENDER = new Sex() { Id = "M", Gender = "Male" }, PHONE = "9999999999", ACTIVE = true, DESIGNATION = Designation.BackOffice });
            empList.Add(new Employee() { ID = 1, NAME = "Neeraj", DOB = Convert.ToDateTime("12/03/1986"), EMAIL = "[email protected]", GENDER = new Sex() { Id = "M", Gender = "Male" }, PHONE = "9999999999", ACTIVE = false, DESIGNATION = Designation.Development });
            empList.Add(new Employee() { ID = 2, NAME = "Mayank", DOB = Convert.ToDateTime("01/01/1986"), EMAIL = "[email protected]", GENDER = new Sex() { Id = "M", Gender = "Male" }, PHONE = "9999999999", ACTIVE = true, DESIGNATION = Designation.BackOffice });

            genders.Add(new Sex() { Id = "M", Gender = "Male" });
            genders.Add(new Sex() { Id = "F", Gender = "Female" });


        }




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

        public List<Sex> Genders
        {
            get
            {
                return genders;
            }
            set
            {
                genders = value;
            }
        }


    }

coding of xaml.cs file

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;




namespace Custom_DataGrid.Grid3
{
    /// <summary>
    /// Interaction logic for Grid3.xaml
    /// </summary>
    public partial class Grid3 : UserControl
    {
        public Grid3()
        {
            InitializeComponent();
            this.DataContext = new DataSource();
        }

        private void datagrid3_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
        {
            if (e.PropertyName.ToLower().ToString().Equals("id"))
            {
                e.Column.Header = "Employee Id";
            }
            else if (e.PropertyName.ToLower().Equals("name"))
            {
                e.Column.Header = "Employee Name";
            }
            else if (e.PropertyName.ToLower().Equals("dob"))
            {
                e.Column.Header = "Employee DOB";
                if (e.PropertyType == typeof(DateTime))
                {
                    DataGridTemplateColumn templateColumn = new DataGridTemplateColumn();
                    templateColumn.Header = "Employee DOB";
                    templateColumn.CellTemplate = (DataTemplate)Resources["dueDateCellTemplate"];
                    templateColumn.CellEditingTemplate = (DataTemplate)Resources["dueDateCellEditingTemplate"];
                    templateColumn.SortMemberPath = "DueDate";
                    e.Column = templateColumn;
                }
            }
            else if (e.PropertyName.ToLower().Equals("phone"))
            {
                e.Column.Header = "Employee Phone";
                e.Cancel = true;
            }
            else if (e.PropertyName.ToLower().Equals("email"))
            {
                e.Column.Header = "Employee Email";
            }
            else if (e.PropertyName.ToLower().Equals("gender"))
            {
                e.Column.Header = "Employee Gender";
                DataGridTemplateColumn templateColumn = new DataGridTemplateColumn();
                templateColumn.Header = "Employee Gender";
                templateColumn.CellTemplate = (DataTemplate)Resources["genderCellTemplate"];
                templateColumn.CellEditingTemplate = (DataTemplate)Resources["genderCellEditingTemplate"];
                e.Column = templateColumn;
            }
            else if (e.PropertyName.ToLower().Equals("active"))
            {
                e.Column.Header = "Employee Active/InActive";
            }
            else if (e.PropertyName.ToLower().Equals("designation"))
            {
                e.Column.Header = "Employee Designation";
            }
        }



    }
}

So i am trying to create template column with the combobxo in the celleditingtemplate every things is working fine but inside datatemplate it is not working.Please help me? Check in the text box which i have commented it is working fine...

解决方案

If you are inside a DataTemplate the DataContext will be the object that is being templated. So your binding, which is relative to the DataContext if only a binding path is specified will not find the ItemsSource.

Normally you can use a RelativeSource-binding to find the control which still has the DataContext in which your ItemsSource can be found. (See RV1987's answer; i thought it did not work earlier because if you have a DataGridComboBoxColumn the very same RelativeSource-ItemsSource-binding will not work, that is because a column on its own is abstract and does not appear in the trees unlike the control that is created by a template)

Since the DataContext of the UserControl should be what you are looking for you can name your UserControl (control for example) and bind like this:

ItemsSource="{Binding Source={x:Reference control}, Path=DataContext.Genders}"

(Note that x:Reference is quite new, it does not exist in .NET 3.5, using ElementName=control instead will not work)

这篇关于数据表中的组合框绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 20:54