C#WPF ObservableCollection不更新Grid

时间:2014-04-11 17:04:51

标签: wpf grid observablecollection auto-update

我的ObservableCollection实现不会更新我的网格,我不知道原因:

第一个XAML-Window'UserControlStaff.xaml'显示可以看到用户数据的网格。第二个XAML-Window允许添加用户,称为“CreateUser.xaml”。 XAML-Windows背后的代码也附在这篇文章中。

我的代码如下:

[XAML] UserControlStaff.xaml

<UserControl x:Class="MyApp.UserControlStaff"
             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" 
             d:DesignHeight="300" d:DesignWidth="786">

    <StackPanel x:Name="spStaff" Orientation="Vertical" Visibility="Visible">
        <Button Background="Azure" Click="btnCreateUser_Click" HorizontalAlignment="Left" Width="786" Height="40">
            <Bold>Mitarbeiter hinzufügen</Bold></Button>
        <ScrollViewer MaxHeight="504">
            <DataGrid Background="#DBDB72" ItemsSource="{Binding UserDataObject}" CanUserAddRows="false" Width="786" />
        </ScrollViewer>
    </StackPanel>

</UserControl>

[代码] UserControlStaff.xaml.cs

namespace MyApp
{
    /// <summary>
    /// Interaktionslogik für UserControlStaff.xaml
    /// </summary>
    public partial class UserControlStaff : UserControl
    {
        ObservableCollection<User> mUserDataObject = new ObservableCollection<User>();

        public ObservableCollection<User> UserDataObject
        {
            get
            {
                return mUserDataObject;
            }
        }

        public UserControlStaff()
        {
            InitializeComponent();
            DataContext = this;

            try
            {
                string connectionString = ConfigurationManager.ConnectionStrings["MyApp.Properties.Settings.ConString"].ConnectionString;
                string queryString = string.Empty;

                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    queryString = "SELECT ID, username AS Username, Password AS Passwort, (SELECT role FROM Roles WHERE ID = t1.role) AS Rolle FROM Users t1 ORDER BY ID";
                    SqlCommand cmd = new SqlCommand(queryString, connection);
                    SqlDataAdapter sda = new SqlDataAdapter(cmd);
                    DataTable dt = new DataTable("Users");
                    sda.Fill(dt);

                    foreach (DataRow row in dt.Rows)
                    {
                        int pID = 0;
                        string pUsername = "";
                        string pPassword = "";
                        string pRole = "";

                        foreach (DataColumn col in dt.Columns)
                        {
                            if (col.ToString().Trim() == "ID")
                            {
                                pID = int.Parse(row[col].ToString());
                            }
                            else if (col.ToString().Trim() == "Username")
                            {
                                pUsername = row[col].ToString();
                            }
                            else if (col.ToString().Trim() == "Passwort")
                            {
                                pPassword = row[col].ToString();
                            }
                            else if (col.ToString().Trim() == "Rolle")
                            {
                                pRole = row[col].ToString();
                            }
                        }
                        // Show Users DB table in MainWindow
                        mUserDataObject.Add(new User { ID = pID, Username = pUsername, Password = pPassword, Role = pRole });
                    }

                    // Show Users DB table in MainWindow
                    //XAML Grid: Name="gridUsers"
                    //CS Code: gridUsers.DataContext = dt.DefaultView;
                }
            }
            catch {
                throw;
            }
        }

        private void btnCreateUser_Click(object sender, RoutedEventArgs e)
        {
            CreateUser popup = new CreateUser();
            popup.Show();
        }

        private void UpdateUserData()
        {
            // implement
        }

        private void DeleteUserData()
        {
            // implement
        }
    }
}

[XAML] CreateUser.xaml

<Window x:Class="MyApp.CreateUser"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Mitarbeiter hinzufügen" Height="300" Width="400">
    <Grid>
        <Label Content="Username" HorizontalAlignment="Left" Margin="10,44,0,0" VerticalAlignment="Top" Width="120" Height="30"/>
        <Label Content="Passwort" HorizontalAlignment="Left" Margin="10,88,0,0" VerticalAlignment="Top" Width="120" Height="30"/>
        <Label Content="Rolle" HorizontalAlignment="Left" Margin="10,132,0,0" VerticalAlignment="Top" Width="120" Height="30"/>
        <TextBox HorizontalAlignment="Left" Height="30" Margin="150,44,0,0" TextWrapping="Wrap" Name="TextBoxUsername" Text="{Binding Path=Username}" VerticalAlignment="Top" Width="180"/>
        <TextBox HorizontalAlignment="Left" Height="30" Margin="150,88,0,0" TextWrapping="Wrap" Name="TextBoxPassword" Text="{Binding Path=Password}" VerticalAlignment="Top" Width="180"/>
        <ComboBox HorizontalAlignment="Left" Height="30" Margin="150,132,0,0" VerticalAlignment="Top" Width="180" Loaded="ComboBox_Loaded" SelectionChanged="ComboBox_SelectionChanged"/>
        <Button Click="btnSaveUserData_Click" Content="Speichern" HorizontalAlignment="Left" Margin="217,219,0,0" VerticalAlignment="Top" Height="30" Width="75"/>
        <Button Click="btnCloseWindow_Click" Content="Abbrechen" HorizontalAlignment="Left" Margin="297,219,0,0" VerticalAlignment="Top" Height="30" Width="75"/>
    </Grid>
</Window>

[代码] CreateUser.xaml.cs

namespace MyApp
{
    /// <summary>
    /// Interaktionslogik für CreateUser.xaml
    /// </summary>
    public partial class CreateUser : Window
    {
        User userObject;

        public CreateUser()
        {
            InitializeComponent();

            this.userObject = new User();
        }

        private void ComboBox_Loaded(object sender, RoutedEventArgs e)
        {
            // ToDO: Rollenzuweisung automatisieren aus Datenbanktabelle MyApp.Roles
            List<string> data = new List<string>();
            data.Add("Chef");
            data.Add("Restaurantmitarbeiter");
            data.Add("Fahrer");

            // ... Get the ComboBox reference.
            var comboBox = sender as ComboBox;

            // ... Assign the ItemsSource to the List.
            comboBox.ItemsSource = data;

            // ... Make the second item selected.
            comboBox.SelectedIndex = 1;
        }

        private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // ... Get the ComboBox.
            var comboBox = sender as ComboBox;

            // ... Set SelectedItem as Window Title.
            string value = comboBox.SelectedItem as string;
            //this.Title = "Selected: " + value;

            this.userObject.Role = value;
        }

        private void btnSaveUserData_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                this.userObject.Username = TextBoxUsername.Text;
                this.userObject.Password = TextBoxPassword.Text;

                int UserRole;

                // ToDO: Rollenzuweisung automatisieren aus Datenbanktabelle MyApp.Roles
                if (this.userObject.Role == "Chef")
                {
                    UserRole = 1;
                }
                else if (this.userObject.Role == "Restaurantmitarbeiter")
                {
                    UserRole = 2;
                }
                else if (this.userObject.Role == "Fahrer")
                {
                    UserRole = 3;
                }
                else
                {
                    UserRole = 2; // Default UserRole is "Restaurantmitarbeiter"
                }


                if (this.userObject.Username.Trim() != "" && this.userObject.Password.Trim() != "")
                {
                    CreateUserData(this.userObject.Username, this.userObject.Password, UserRole);
                    // ToDO: Update DataGrid in UserControlStaff
                    this.Close();

                    MessageBox.Show("Mitarbeiter hinzugefügt!");
                } else {
                    MessageBox.Show("Bitte Username und Passwort eingeben.");
                }
            }
            catch { throw; }
        }

        private void CreateUserData(string pUsername, string pPassword, int pRole)
        {
            string connectionString = ConfigurationManager.ConnectionStrings["MyApp.Properties.Settings.ConString"].ConnectionString;
            string queryString = "INSERT INTO Users (ID, username, password, role) VALUES ((SELECT TOP 1 ID+1 FROM Users ORDER BY ID DESC), '" + pUsername + "', '" + pPassword + "', '" + pRole + "')";

            SqlConnection connection = new SqlConnection(connectionString);
            SqlCommand cmd = new SqlCommand(queryString, connection);
            SqlDataAdapter sda = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable("Users");
            sda.Fill(dt);

            string UserRole;
            if (pRole == 1)
            {
                UserRole = "Chef";
            }
            else if (pRole == 2)
            {
                UserRole = "Restaurantmitarbeiter";
            }
            else if (pRole == 3)
            {
                UserRole = "Fahrer";
            }
            else
            {
                UserRole = "Restaurantmitarbeiter"; // Default UserRole is "Restaurantmitarbeiter"
            }

            // Add to Observable Collection
            // ToDO
            // mUserDataObject.Add(new User { ID = pID, Username = pUsername, Password = pPassword, Role = pRole });
        }

        private void btnCloseWindow_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }
    }
}

0 个答案:

没有答案