DataGrid中的子控件Combox之数据源绑定(WPF)

来源:互联网 发布:阿里云 云监控 编辑:程序博客网 时间:2024/03/29 17:33

看到同事有一个这样的需求,自己就写了一个小例子

如何根据DataGrid中Combox中选择的值将对应的数据显示到DataGrid中

创建了 三个数据源  

List<int> SelectionList为 Combox 数据源存放于所有数据相相关联的字段值(Selection),

tb为 DataGrid数据源存放的是与Combox相关联的数据 (Age,Name,Selection),

oldtable 用于存放所有数据(Age,Name,Selection)

前台代码:

<Window x:Class="MyTestWPF.DataGridCombox"        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"        Title="DataGridCombox" Height="276" Width="633" Loaded="Window_Loaded">    <Grid>        <DataGrid AutoGenerateColumns="False" ItemsSource="{Binding}" CanUserAddRows="False" Name="dg_Grid" AreRowDetailsFrozen="False" AllowDrop="True" Margin="23,0,23,32">            <DataGrid.Columns>                <!--依赖属性绑定数据源下拉框必须同时指定EditingElementStyle、ElemengStyle才能显示下拉框中的数据-->                <DataGridComboBoxColumn Header="ComboBox模式(修正)">                    <DataGridComboBoxColumn.EditingElementStyle>                        <Style TargetType="ComboBox">                            <Setter Property="ItemsSource" Value="{Binding Path=SelectionList,RelativeSource={RelativeSource AncestorType={x:Type Window},Mode=FindAncestor}}" />                            <Setter Property="SelectedValue" Value="{Binding Path=Value}" />                            <Setter Property="Text" Value="{Binding Selection}"/>                        </Style>                    </DataGridComboBoxColumn.EditingElementStyle>                    <DataGridComboBoxColumn.ElementStyle>                        <Style TargetType="ComboBox">                            <Setter Property="ItemsSource" Value="{Binding Path=SelectionList,RelativeSource={RelativeSource AncestorType={x:Type Window},Mode=FindAncestor}}" />                            <Setter Property="SelectedValue" Value="{Binding Path=Value}" />                        </Style>                    </DataGridComboBoxColumn.ElementStyle>                </DataGridComboBoxColumn>                <!--不使用依赖属性绑定下拉框时,数据源中必须包含该属性字段-->                <DataGridTemplateColumn Header="Template模式" x:Uid="Moshi">                    <DataGridTemplateColumn.CellTemplate>                        <DataTemplate>                            <ComboBox Tag="cbxList" x:Name="cbxList" DropDownClosed="cbxList_DropDownClosed"                                       ItemsSource="{Binding Path=SelectionList,RelativeSource={RelativeSource AncestorType={x:Type Window},Mode=FindAncestor}}"                                       Text="{Binding Selection}" />                        </DataTemplate>                    </DataGridTemplateColumn.CellTemplate>                </DataGridTemplateColumn>                <DataGridTemplateColumn Header="姓 名" Width="100">                    <DataGridTemplateColumn.CellTemplate>                        <DataTemplate>                            <TextBox Text="{Binding Name}"/>                        </DataTemplate>                    </DataGridTemplateColumn.CellTemplate>                </DataGridTemplateColumn>                <DataGridTemplateColumn Header="年 龄">                    <DataGridTemplateColumn.CellTemplate >                        <DataTemplate >                            <TextBox Text="{Binding Age}"/>                        </DataTemplate>                    </DataGridTemplateColumn.CellTemplate>                </DataGridTemplateColumn>            </DataGrid.Columns>        </DataGrid>        <ComboBox Height="23" HorizontalAlignment="Left" Margin="186,211,0,0" Name="comboBox1" VerticalAlignment="Top" Width="120" />    </Grid></Window>
后台代码: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.Shapes;using System.Data;using System.Collections;using System.Collections.ObjectModel;namespace MyTestWPF{    /// <summary>    /// DataGridCombox.xaml 的交互逻辑    /// </summary>    public partial class DataGridCombox : Window    {        DataTable tb;        DataTable newtb;        /// <summary>        /// 下拉框数据源        /// </summary>                public List<int> SelectionList        {            get { return _selectionList; }            set { _selectionList = value; }        }        private List<int> _selectionList = new List<int>();        public DataGridCombox()        {            InitializeComponent();            tb = new DataTable();            DataColumn Name = new DataColumn("Name");            DataColumn Age = new DataColumn("Age");            DataColumn Selection = new DataColumn("Selection");            tb.Columns.Add(Name);            tb.Columns.Add(Age);            tb.Columns.Add(Selection);            newtb = tb.Copy();            newtb.Clear();            banging();            check("1");            //if (SelectionList.Count > 0)            //{            //    DataGridTemplateColumn templeColumn = dg_Grid.Columns[1] as DataGridTemplateColumn;            //    if (templeColumn == null) return;            //    object item = dg_Grid.CurrentCell.Item;            //    FrameworkElement element = templeColumn.GetCellContent(dg_Grid.Items[0]);            //    ComboBox expander = templeColumn.CellTemplate.FindName("cbxList", element) as ComboBox;            //    expander.IsEnabled = false;            //}        }        private void banging()        {            //如果绑定数据不采用依赖属性绑定 采用数据模板添加 Combox 则该下拉框的数据源为Selection             for (int i = 0; i < 5; i++)            {                DataRow row = tb.NewRow();                row["Name"] = "AA" + i.ToString();                row["Age"] = i.ToString();                row["Selection"] = i.ToString();                SelectionList.Add(i);                DataRow rw = newtb.NewRow();                rw["Name"] = "AA" + i.ToString();                rw["Age"] = i.ToString();                rw["Selection"] = i.ToString();                tb.Rows.Add(row);                newtb.Rows.Add(rw);            }            //如果数据源绑定要用DataContent上下文数据绑定,则xmal界面必须指定ItemSource="{Binding}"        }        private void check(string str)        {            newtb.Clear();            DataRow[] row = tb.Select("Selection='" + str + "'");            if (row.Length > 0)            {                DataRow nrow = newtb.NewRow();                nrow["Name"] = row[0]["Name"].ToString();                nrow["Age"] = row[0]["Age"].ToString();                nrow["Selection"] = row[0]["Selection"].ToString();                newtb.Rows.Add(nrow);                dg_Grid.DataContext = newtb;            }        }        private void cbxList_DropDownClosed(object sender, EventArgs e)        {            ComboBox cbx = sender as ComboBox;            if (cbx != null)            {                if (cbx.SelectedItem != null)                {                    check(cbx.SelectedItem.ToString());                }            }        }        private void Window_Loaded(object sender, RoutedEventArgs e)        {            if (SelectionList.Count > 1)            {                //dg_Grid.IsEnabled = false;                //    DataGridTemplateColumn templeColumn = dg_Grid.Columns[1] as DataGridTemplateColumn;                //    if (templeColumn == null) return;                //    object item = dg_Grid.CurrentCell.Item;                                //    FrameworkElement element = templeColumn.GetCellContent(dg_Grid.Items[0]);                //    ComboBox expander = templeColumn.CellTemplate.FindName("cbxList", element) as ComboBox;                //    expander.IsEnabled = true;                //    expander.IsEditable = false;                //    expander.IsReadOnly = true;                //    comboBox1.IsEnabled = false;            }        }        private void cbxList_Initialized(object sender, EventArgs e)        {            if (SelectionList.Count > 0)            {                ComboBox cbx = sender as ComboBox;                cbx.IsEnabled = false;            }        }    }}

当下来框的数据源是List时可以满足上述联动效果,可以当Combox改为newtb 时Combox中的数据就不显示了????

原创粉丝点击