WPF .Net 4.0 Datagrid, comboboxes de mise en cascade en cascade sur la mise à jour de cellule, seulement après la mise à jour de la ligne

StackOverflow https://stackoverflow.com/questions/5300279

Question

Je suis nouveau à WPF et je trouve que le WPF .Net 4.0 Datagrid ne semble pas manipuler comboboxes en cascade. Seulement après mise au point est retiré d'une rangée font les cellules correctement renseignées avec les bonnes données pour les boîtes de sélection. Je peux réellement voir les points de débogage étant frappé après mise au point sur la ligne est perdue mais pas lorsque le focus d'une cellule est perdue.

Ce type de comportement ne semble pas être le cas avec l'ancienne boîte à outils WPF DataGrid où tout est comme prévu.

La solution évidente est ici pour aller avec la boîte à outils WPF, mais c'est un nouveau projet en .Net 4.0 donc n'a pas de sens pour revenir en arrière (peut-être que je vais reconsidérer cette question). Il est aussi je crois comprendre que la boîte à outils WPF a sa propre part de défauts et me obliger à apprendre et de travailler autour de ceux bien.

J'ai à peu près parcouru un certain nombre de ressources sur le Web et n'ont pas eu beaucoup de chance. Un thème récurrent semble être que les cellules ne sont pas une partie de l'arbre visuel qui crée la situation (pas sûr si cela valide ou non).

Toute aide sur l'événement est je l'ai manqué ou des échantillons de travail sont très appréciés.

Merci à l'avance.

SCÉNARIOS

WPF .Net 4.0 Data Grid.

  1. À partir de la ligne 1.
  2. Double cliquez sur la cellule de pays, le changement de la Chine aux États-Unis
  3. Double cliquez sur la cellule Ville, avis que les villes sont encore pour la Chine (non prévu)
  4. déplacer le focus sur la ligne 2.
  5. Double cliquez sur la cellule Ville pour la ligne 1 à nouveau, notez que les villes ont été mises à jour. New York et Washington sont maintenant des options.

WPF Toolkit

  1. À partir de la ligne 1.
  2. Double cliquez sur la cellule de pays, le changement de la Chine aux États-Unis
  3. Double cliquez sur la cellule Ville, avis que les villes sont pour les États-Unis (prévu)

Le code est presque identique pour les deux moins l'utilisation Boîte à outils WPF (Les échantillons sont Blog Jialiang )

CODE

WPF .Net 4.0

<Window x:Class="CSWPFCascadeDataGridComboBoxColumns.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:CSWPFCascadeDataGridComboBoxColumns"    
Title="Cascade DataGridComboBoxColumns" Height="300" Width="300" Loaded="Window_Loaded">
<DockPanel LastChildFill="True">
    <DataGrid Name="dataGrid" ItemsSource="{Binding}" 
                      AutoGenerateColumns="False" 
                      PreparingCellForEdit="datagrid_PreparingCellForEdit">
        <DataGrid.Columns>
            <DataGridComboBoxColumn x:Name="column1" Width="80"/>
            <DataGridComboBoxColumn x:Name="column2" Width="80"/>               
        </DataGrid.Columns>
    </DataGrid>
</DockPanel>

MainWindow.xaml.cs

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    public enum Country
    {
        China,
        UnitedStates
    }
    public enum ChinaCity
    {
        Beijing,
        Shanghai
    }
    public enum UnitedStatesCity
    {
        NewYork,
        Washington
    }

    DataTable table = null;
    string[] strChinaCities, strUnitedStateCities;

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        /////////////////////////////////////////////////////////////////
        // get all enumeration values of type enum Country
        //
        Array countries = Enum.GetValues(typeof(Country));

        /////////////////////////////////////////////////////////////////
        // copy all Country enumeration values to a string array
        //
        string[] strCountries = new string[countries.Length];
        for (int i = 0; i < countries.Length; i++)
        {
            strCountries[i] = (countries as Country[])[i].ToString();
        }

        /////////////////////////////////////////////////////////////////
        // get all enumeration values of type enum ChinaCity
        //
        Array chinaCities = Enum.GetValues(typeof(ChinaCity));

        /////////////////////////////////////////////////////////////////
        // copy all ChinaCity enumeration values to a string array
        //
        strChinaCities = new string[chinaCities.Length];
        for (int i = 0; i < chinaCities.Length; i++)
        {
            strChinaCities[i] = (chinaCities as ChinaCity[])[i].ToString();
        }

        /////////////////////////////////////////////////////////////////
        // get all enumeration values of type enum UnitedStatesCity
        //
        Array unitedStateCities = Enum.GetValues(typeof(UnitedStatesCity));

        /////////////////////////////////////////////////////////////////
        //copy all UnitedStateCity enumeration values to a string array
        //
        strUnitedStateCities = new string[unitedStateCities.Length];
        for (int i = 0; i < unitedStateCities.Length; i++)
        {
            strUnitedStateCities[i] = (unitedStateCities as UnitedStatesCity[])[i].ToString();
        }

        //////////////////////////////////////////////////////////////////
        // combine both the two city enumeration value into one string array
        //
        string[] strAllCities = new string[strChinaCities.Length + strUnitedStateCities.Length];
        strChinaCities.CopyTo(strAllCities, 0);
        strUnitedStateCities.CopyTo(strAllCities, strChinaCities.Length);

        ///////////////////////////////////////////////////////////////////////////////
        // data bind the two DataGridComboBoxColumn's ItemsSource property respectively
        //
        BindingOperations.SetBinding(this.column1, DataGridComboBoxColumn.ItemsSourceProperty,
            new Binding() { Source = strCountries });
        BindingOperations.SetBinding(this.column2, DataGridComboBoxColumn.ItemsSourceProperty,
            new Binding() { Source = strAllCities });

        /////////////////////////////////////////////////////////////////
        // create a DataTable and add two DataColumn into it
        //
        table = new DataTable();
        table.Columns.Add("Country");
        table.Columns.Add("City");

        /////////////////////////////////////////////////////////////////
        // add a DataRow into this DataTable
        //
        table.Rows.Add(new object[] { "China", "Beijing" });

        /////////////////////////////////////////////////////////////////
        // set the DataContext property of the DataGrid to the DataTable
        //
        this.dataGrid.DataContext = table;

        /////////////////////////////////////////////////////////////////
        // set the Header of both DataGridComboBoxColumn and bind the
        // SelectedItemBinding property of both DataGridComboBoxColumn
        this.column1.Header = "Country";
        this.column1.SelectedItemBinding = new Binding("Country");
        this.column2.Header = "City";
        this.column2.SelectedItemBinding = new Binding("City");

    }

    /// <summary>
    /// this PreparingCellForEdit event handler gets the hosted editing ComboBox control 
    /// and bind its ItemsSource property according to the value of the Country
    /// </summary>             
    private void datagrid_PreparingCellForEdit(object sender, DataGridPreparingCellForEditEventArgs e)
    {
        if (e.Column.Header.Equals("City"))
        {
            ComboBox cboEditingElement = e.EditingElement as ComboBox;
            if ((e.Row.Item as DataRowView)["Country"].Equals("China"))
            {
                //////////////////////////////////////////////////////////////////////////
                // bind the ItemsSource property of the cmbEditingElement to China city
                // string array if the selected country is China
                //
                BindingOperations.SetBinding(cboEditingElement, ComboBox.ItemsSourceProperty,
                    new Binding() { Source = strChinaCities });
            }
            else
            {
                //////////////////////////////////////////////////////////////////////////
                // bind the ItemsSource property of the cmbEditingElement to United State
                // city string array if the selected country is United State
                //
                BindingOperations.SetBinding(cboEditingElement, ComboBox.ItemsSourceProperty,
                    new Binding() { Source = strUnitedStateCities });
            }
        }
    }
}

WPF Toolkit code

MainWindow.xaml

<Window x:Class="CSWPFCascadeDataGridComboBoxColumns.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:CSWPFCascadeDataGridComboBoxColumns"
xmlns:toolkit ="http://schemas.microsoft.com/wpf/2008/toolkit"
Title="Cascade DataGridComboBoxColumns" Height="300" Width="300" Loaded="Window_Loaded">
<DockPanel LastChildFill="True">
    <toolkit:DataGrid Name="dataGrid" ItemsSource="{Binding}" 
                      AutoGenerateColumns="False" 
                      PreparingCellForEdit="datagrid_PreparingCellForEdit">
        <toolkit:DataGrid.Columns>
            <toolkit:DataGridComboBoxColumn x:Name="column1" Width="80"/>
            <toolkit:DataGridComboBoxColumn x:Name="column2" Width="80"/>               
        </toolkit:DataGrid.Columns>
    </toolkit:DataGrid>
</DockPanel>

MainWindow.xaml.cs

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    public enum Country
    {
        China,
        UnitedStates
    }
    public enum ChinaCity
    {
        Beijing,
        Shanghai
    }
    public enum UnitedStatesCity
    {
        NewYork,
        Washington
    }

    DataTable table = null;
    string[] strChinaCities, strUnitedStateCities;

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        /////////////////////////////////////////////////////////////////
        // get all enumeration values of type enum Country
        //
        Array countries = Enum.GetValues(typeof(Country));

        /////////////////////////////////////////////////////////////////
        // copy all Country enumeration values to a string array
        //
        string[] strCountries = new string[countries.Length];
        for (int i = 0; i < countries.Length; i++)
        {
            strCountries[i] = (countries as Country[])[i].ToString();
        }

        /////////////////////////////////////////////////////////////////
        // get all enumeration values of type enum ChinaCity
        //
        Array chinaCities = Enum.GetValues(typeof(ChinaCity));

        /////////////////////////////////////////////////////////////////
        // copy all ChinaCity enumeration values to a string array
        //
        strChinaCities = new string[chinaCities.Length];
        for (int i = 0; i < chinaCities.Length; i++)
        {
            strChinaCities[i] = (chinaCities as ChinaCity[])[i].ToString();
        }

        /////////////////////////////////////////////////////////////////
        // get all enumeration values of type enum UnitedStatesCity
        //
        Array unitedStateCities = Enum.GetValues(typeof(UnitedStatesCity));

        /////////////////////////////////////////////////////////////////
        //copy all UnitedStateCity enumeration values to a string array
        //
        strUnitedStateCities = new string[unitedStateCities.Length];
        for (int i = 0; i < unitedStateCities.Length; i++)
        {
            strUnitedStateCities[i] = (unitedStateCities as UnitedStatesCity[])[i].ToString();
        }

        //////////////////////////////////////////////////////////////////
        // combine both the two city enumeration value into one string array
        //
        string[] strAllCities = new string[strChinaCities.Length + strUnitedStateCities.Length];
        strChinaCities.CopyTo(strAllCities, 0);
        strUnitedStateCities.CopyTo(strAllCities, strChinaCities.Length);

        ///////////////////////////////////////////////////////////////////////////////
        // data bind the two DataGridComboBoxColumn's ItemsSource property respectively
        //
        BindingOperations.SetBinding(this.column1, DataGridComboBoxColumn.ItemsSourceProperty,
            new Binding() { Source = strCountries });
        BindingOperations.SetBinding(this.column2, DataGridComboBoxColumn.ItemsSourceProperty,
            new Binding() { Source = strAllCities });

        /////////////////////////////////////////////////////////////////
        // create a DataTable and add two DataColumn into it
        //
        table = new DataTable();
        table.Columns.Add("Country");
        table.Columns.Add("City");

        /////////////////////////////////////////////////////////////////
        // add a DataRow into this DataTable
        //
        table.Rows.Add(new object[] { "China", "Beijing" });

        /////////////////////////////////////////////////////////////////
        // set the DataContext property of the DataGrid to the DataTable
        //
        this.dataGrid.DataContext = table;

        /////////////////////////////////////////////////////////////////
        // set the Header of both DataGridComboBoxColumn and bind the
        // SelectedItemBinding property of both DataGridComboBoxColumn
        this.column1.Header = "Country";
        this.column1.SelectedItemBinding = new Binding("Country");
        this.column2.Header = "City";
        this.column2.SelectedItemBinding = new Binding("City");

    }

    /// <summary>
    /// this PreparingCellForEdit event handler gets the hosted editing ComboBox control 
    /// and bind its ItemsSource property according to the value of the Country
    /// </summary>             
    private void datagrid_PreparingCellForEdit(object sender, DataGridPreparingCellForEditEventArgs e)
    {
        if (e.Column.Header.Equals("City"))
        {
            ComboBox cboEditingElement = e.EditingElement as ComboBox;
            if ((e.Row.Item as DataRowView)["Country"].Equals("China"))
            {
                //////////////////////////////////////////////////////////////////////////
                // bind the ItemsSource property of the cmbEditingElement to China city
                // string array if the selected country is China
                //
                BindingOperations.SetBinding(cboEditingElement, ComboBox.ItemsSourceProperty,
                    new Binding() { Source = strChinaCities });
            }
            else
            {
                //////////////////////////////////////////////////////////////////////////
                // bind the ItemsSource property of the cmbEditingElement to United State
                // city string array if the selected country is United State
                //
                BindingOperations.SetBinding(cboEditingElement, ComboBox.ItemsSourceProperty,
                    new Binding() { Source = strUnitedStateCities });
            }
        }
    }
}
Était-ce utile?

La solution

Je suis toujours étonné comment on peut passer beaucoup de temps des recherches sur une seule question à poser la question à la communauté, puis trouver une réponse dans les 60 minutes. Donc, étant nouveau pour WPF a certainement part de foire des morceaux à prendre.

J'ai trouvé la réponse sur le post suivant Microsoft: WPF-DataBind-combobox-en-DataGrid

Apparemment, il est aussi simple que le réglage de la UpdateSourceTrigger = PropertyChanged sur la liaison de l'élément sélectionné.

De Microsoft:

« consolidations dans les modèles d'édition de DataGrid normalement obtenir leur ensemble UpdateSourceTrigger Explicite, de sorte que les propriétés de la source ne sont pas mis à jour jusqu'à ce que l'utilisateur engage la ligne. Vous pouvez remplacer cela en définissant UpdateSourceTrigger = PropertyChanged sur la liaison pour ComboBox.SelectedItem. »

Espérons que quelqu'un d'autre que moi-même vous le trouverez utile.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top