【问题标题】:C#/WPF INotifyPropertyChanged never OpenC#/WPF INotifyPropertyChanged 从不打开
【发布时间】:2017-12-08 13:04:19
【问题描述】:

呼呼,

我阅读了很多帖子,但没有一个是真正有用的。所以我问自己。 希望有人可以帮助我,我不认为它是重复的。

我有一个列表,这些数据来自数据库。数据显示在 文本框 中,我希望能够更改数据。所以我写了一个INotifyPropertyChanged。但它没有按我的意愿工作。我总是看到旧值而不是新值。

WPF 代码:

    <dxn:NavBarGroup Name="_navBarOverlay" Header="Benutzerübersicht">
            <Grid Style="{StaticResource GridStyleAccordion}">
                <DataGrid x:Name="userDataGrid" CanUserReorderColumns="True" CanUserResizeColumns="True" CanUserResizeRows="True" RowDetailsVisibilityMode="VisibleWhenSelected" IsReadOnly="True" AlternatingRowBackground="{DynamicResource WihaGrauB}" ColumnWidth="auto" ColumnHeaderHeight="30"   AutoGenerateColumns="False" Grid.Row="0"   Width="auto" Height="auto">
                    <DataGrid.Columns>
                        <DataGridTextColumn Header="OperatorID" Binding="{Binding OperatorID}" MinWidth="200" Width="3*"/>
                        <DataGridTextColumn Header="Benutzer"  Binding="{Binding Name}" MinWidth="150" Width="2*" />
                        <DataGridCheckBoxColumn Header="Aktiv" Binding="{Binding Aktiv}" MinWidth="50" Width="*"/>
                    </DataGrid.Columns>
                    <DataGrid.RowDetailsTemplate>
                        <DataTemplate>
                            <DockPanel>
                                <Button x:Name="deleteButton" DockPanel.Dock="Left" Height="40" Width="30" Click="deleteButton_Click" Margin="10,0,0,0">
                                    <StackPanel>
                                        <Image Source="{Binding ImageUrl}" />
                                    </StackPanel>
                                </Button>
                                <Grid Margin="10">
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition Width="Auto"/>
                                        <ColumnDefinition Width="*"/>
                                    </Grid.ColumnDefinitions>
                                    <Grid.RowDefinitions>
                                        <RowDefinition Height="Auto"/>
                                        <RowDefinition Height="Auto"/>
                                        <RowDefinition Height="Auto"/>
                                        <RowDefinition Height="Auto"/>
                                        <RowDefinition Height="Auto"/>
                                        <RowDefinition Height="Auto"/>
                                        <RowDefinition Height="Auto"/>
                                    </Grid.RowDefinitions>
                                    <TextBlock Text="OperatorID: " FontFamily="{DynamicResource WihaFontFamaly}" Grid.Row="1" FontWeight="Bold" Margin="2,2,2,2"/>
                                    <TextBox x:Name="operatorText" IsReadOnly="True" Text="{Binding OperatorID}" Width="150" HorizontalAlignment="Left" Grid.Row="1" Grid.Column="2" TextAlignment="Center"  Margin="2,2,2,2" />
                                    <TextBlock Text="Name: " FontFamily="{DynamicResource WihaFontFamaly}" FontWeight="Bold" Grid.Row="2" Margin="2,2,2,2"/>
                                    <TextBox  x:Name="nameText" Text="{Binding  Path=Name, Mode=TwoWay}" Grid.Column="2" Width="150" MaxLength="128" TextAlignment="Center" HorizontalAlignment="Left" Grid.Row="2"  Margin="2,2,2,2"  />
                                    <TextBlock Text="DeviceID: " FontFamily="{DynamicResource WihaFontFamaly}" FontWeight="Bold" Grid.Row="3" Margin="2,2,2,2"/>
                                    <TextBox Text="{Binding DeviceID}" Grid.Column="3" Width="150" HorizontalAlignment="Left" MaxLength="255" TextCompositionManager.PreviewTextInput="passwordBoxNeu_PreviewTextInput" Grid.Row="3" TextAlignment="Center"  Margin="2,2,2,2"/>
                                    <TextBlock Text="Passwort: " FontFamily="{DynamicResource WihaFontFamaly}" FontWeight="Bold" Grid.Row="4" Margin="2,2,2,2" />
                                    <TextBox Text="{Binding Passwort}" Grid.Column="4" Width="150" HorizontalAlignment="Left" Grid.Row="4" TextAlignment="Center" MaxLength="4" TextCompositionManager.PreviewTextInput="passwordBoxNeu_PreviewTextInput"  Margin="2,2,2,2"/>
                                    <TextBlock Text="Aktiv:" FontWeight="Bold" FontFamily="{DynamicResource WihaFontFamaly}" Grid.Row="5" Margin="2,2,2,2"/>
                                    <CheckBox Grid.Column="5" Grid.Row="5" IsChecked="{Binding Aktiv}" Margin="2,2,2,2" />
                                    <Button Style="{StaticResource ButtonStyleWIHA}" Click="saveUserPanel_Click" Name="saveUserPanel" Content="Save" Grid.Row="6" />
                                </Grid>
                            </DockPanel>
                        </DataTemplate>
                    </DataGrid.RowDetailsTemplate>
                </DataGrid>
            </Grid>
        </dxn:NavBarGroup>

用户列表类:

    public class User : INotifyPropertyChanged
    {
        private string _name = string.Empty;
        public event PropertyChangedEventHandler PropertyChanged;
        public string Name
        {
            get { return this._name; }
            set
            {
                if (value != this._name)
                {
                    this._name = value;
                    NotifyPropertyChanged("Name");
                }
            }
        }
        public string OperatorID { get; set; }
        public bool Aktiv { get; set; }
        public string ImageUrl { get; set; }
        public string DeviceID { get; set; }
        public string Passwort { get; set; }

        private void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

我的事件处理器:

     private void saveUserPanel_Click(object sender, RoutedEventArgs e)
    {

        var user = (sender as Button).DataContext as User;

        if (user != null)
        {

            SqlConnection conn = new SqlConnection("Server=127.0.0.1;Database=Wiha;Trusted_Connection=true");
            conn.Open();
            SqlCommand cmd = new SqlCommand("dbo.wiha_operator_Update", conn);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add(new SqlParameter("@OperatorID", user.OperatorID));
            cmd.Parameters.Add(new SqlParameter("@DeviceID", user.DeviceID));
            cmd.Parameters.Add(new SqlParameter("@Name", user.Name));
            cmd.Parameters.Add(new SqlParameter("@Password", user.Passwort));
            cmd.Parameters.Add(new SqlParameter("@Active", user.Aktiv));
            using (SqlDataReader rdr = cmd.ExecuteReader())
            {
                while (rdr.Read())
                {
                    if (rdr[0].Equals("S"))
                    {

                        popup = new ToolBox(string.Format("Operator '{0}' wurde bearbeitet.", user.OperatorID));
                        popup.Show();
                        //ShowAllOperator();
                    }
                    else
                    {
                        popup = new ToolBox(string.Format("Fehler beim bearbeiten des Operator '{0}'", user.OperatorID));
                        popup.Show();
                    }

                }
            }

        }
    }

    public void ShowAllOperator()
    {
        try
        {
            List<User> users = new List<User>();
            // string sql = "SELECT * FROM wiha_Operators";
            SqlConnection conn = new SqlConnection("Server=127.0.0.1;Database=Wiha;Trusted_Connection=true");
            conn.Open();
            // SqlCommand cmd = new SqlCommand(sql, conn);
            SqlCommand cmd = new SqlCommand("dbo.wiha_operators_SelectAll", conn);
            cmd.CommandType = CommandType.StoredProcedure;
            using (SqlDataReader rdr = cmd.ExecuteReader())
            {

                while (rdr.Read())
                {
                    users.Add(new User() { Name = rdr.GetValue(2).ToString(), OperatorID = rdr.GetValue(0).ToString(), Aktiv = rdr.GetValue(4).Equals(true), ImageUrl = "C:/Users/Jason/Desktop/DeleteIcon.png", DeviceID = rdr.GetValue(1).ToString(), Passwort = rdr.GetValue(3).ToString() });
                }

            }
            userDataGrid.ItemsSource = users;
        }
        catch (Exception)
        {

            throw;
        }
    }

希望有人可以帮助我:D

【问题讨论】:

  • 你总是看到旧值是什么意思?您是指在添加新用户之后还是在更改文本框时?
  • 同时更改文本框。当在 TextBox 中时,例如“TestUser”,我想将其更改为“TestUser2”。我总是看到“TestUser”。
  • 请注意,默认情况下,绑定到 TextBox 的 Text 属性是 TwoWay。无需指定。
  • 很高兴知道谢谢:D

标签: c# wpf list binding inotifypropertychanged


【解决方案1】:

您只需要告知 WPF 将如何绑定到您的数据,并在您的绑定中添加更多信息:

<TextBox Text="{Binding XXXX, UpdateSourceTrigger=PropertyChanged}" />

原因很简单:每次更改 Text 属性时,您都在指示视图更新。而对于 TextBox,这通常只会在您离开控件时发生。

NotifyPropertyChanged 以另一种方式工作:从您的 C# 代码中,您希望指示您的视图使用新值进行更新。查看您的课程,这仅发生在 Name 属性中。

【讨论】:

    猜你喜欢
    • 2011-06-25
    • 2021-08-25
    • 1970-01-01
    • 2021-09-07
    • 2017-05-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多