DataGrid中的子控件Combox之數據源綁定(WPF)

看到同事有一個這樣的需求,自己就寫了一個小例子

如何根據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中的數據就不顯示了????
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章