【问题标题】:text box value won't updated using data bind文本框值不会使用数据绑定更新
【发布时间】:2013-09-06 15:21:14
【问题描述】:

为了防止评论区长篇大论,我再问一遍。

我有一个绑定到对象的TextBox

当我更改对象值时,TextBox 文本值不会更改。

我阅读了关于此问题的所有讨论,但没有弄清楚。

XAML:

<TabItem Header="תלמידים" Name="Tabstudents" >
            <Grid Height="757" Margin="0">
                <Border BorderBrush="Silver" BorderThickness="1" Height="450" HorizontalAlignment="Stretch" Margin="4,0,11,287" Name="brdrStudents" VerticalAlignment="Bottom" Width="Auto">
                    <Grid Height="441">
                        <TextBlock Style="{StaticResource textStyle}" Height="33" Name="txtblkStudenName" Text="שם פרטי:" Width="159" HorizontalAlignment="Left" VerticalAlignment="Bottom" Margin="20,0,0,400" />
                        <TextBlock Style="{StaticResource textStyle}" Height="33" Name="txtblkStudenNotes" Text="שם משפחה:" Width="159" HorizontalAlignment="Left" VerticalAlignment="Bottom" Margin="20,00,0,360" />
                        <TextBlock Style="{StaticResource textStyle}" Height="33" Name="txtBlkStudenTecher" Text="תעודת זהות:" Width="159" HorizontalAlignment="Left" VerticalAlignment="Bottom" Margin="20,0,0,320" />
                        <TextBlock Style="{StaticResource textStyle}" Height="33" Name="txtblkStudenAdress" Text="כתובת:" Width="159" HorizontalAlignment="Left" VerticalAlignment="Bottom" Margin="20,0,0,120" />
                        <TextBlock Style="{StaticResource textStyle}" Height="33" Name="txtBlkStudenPrice" Text="טלפון בית:" Width="159" HorizontalAlignment="Left" VerticalAlignment="Bottom" Margin="20,0,0,280" />
                        <TextBlock Style="{StaticResource textStyle}" Height="33" Name="txtblkStudenPicForm" Text="אישור צילום:" Width="159" HorizontalAlignment="Left" VerticalAlignment="Bottom" Margin="460,0,0,400" />
                        <TextBlock Style="{StaticResource textStyle}" Height="33" Name="txtBlkStudenDates" Text="טלפון סלולרי:" Width="159" HorizontalAlignment="Left" VerticalAlignment="Bottom" Margin="20,0,0,240" />
                        <TextBlock Style="{StaticResource textStyle}" Height="33" Name="txtblkStudenMedical" Text="בעיות רפואיות:" Width="159" HorizontalAlignment="Left" VerticalAlignment="Bottom" Margin="460,0,0,320" />
                        <TextBlock Style="{StaticResource textStyle}" Height="33" Name="txtBlkStudenDivideMoney" Text="טלפון הורים:" Width="159" HorizontalAlignment="Left" VerticalAlignment="Bottom" Margin="20,0,0,200" />
                        <TextBlock Style="{StaticResource textStyle}" Height="33" Name="txtblkStudenParentsConf" Text="אישור הורים:" Width="159" HorizontalAlignment="Left" VerticalAlignment="Bottom" Margin="460,0,0,360" />
                        <TextBlock Style="{StaticResource textStyle}" Height="33" Name="txtBlkStudenPlace" Text="שמות ההורים:" Width="159" HorizontalAlignment="Left" VerticalAlignment="Bottom" Margin="20,0,0,160" />
                        <TextBlock Style="{StaticResource textStyle}" Height="33" Name="txtblkStudenBirth" Text="תאריך לידה:" Width="159" HorizontalAlignment="Left" VerticalAlignment="Bottom" Margin="20,0,0,80" />
                        <TextBlock Style="{StaticResource textStyle}" Height="33" Name="txtblkStudenClasses" Text="רשימת חוגים:" Width="159" HorizontalAlignment="Left" VerticalAlignment="Bottom" Margin="663,0,0,280" />
                        <TextBlock Height="33" HorizontalAlignment="Left" Margin="1006,0,0,400" Name="txtBlkPayments" Style="{StaticResource textStyle}" Text="תשלומים:" VerticalAlignment="Bottom" Width="159" />

                        <TextBox Height="36" HorizontalAlignment="Left" Margin="174,0,0,400" Name="txtStudenName" VerticalAlignment="Bottom" Width="240" IsEnabled="False" >
                            <TextBox.Text>
                                <Binding NotifyOnSourceUpdated="True" Path="firstName" UpdateSourceTrigger="PropertyChanged" >
                                </Binding>
                            </TextBox.Text>
                        </TextBox>
                        <TextBox Height="36" HorizontalAlignment="Left" Margin="174,0,0,360" Name="txtStudenLastName" VerticalAlignment="Bottom" Width="240" IsEnabled="False" >
                            <TextBox.Text>
                                <Binding NotifyOnSourceUpdated="True" Path="lastName" UpdateSourceTrigger="PropertyChanged" >
                                </Binding>
                            </TextBox.Text>
                        </TextBox>
                        <TextBox Height="36" HorizontalAlignment="Left" Margin="174,0,0,320" Name="txtStudenID" VerticalAlignment="Bottom" Width="240" IsEnabled="False" >
                            <TextBox.Text>
                                <Binding NotifyOnSourceUpdated="True" Path="studentID" UpdateSourceTrigger="PropertyChanged" >
                                </Binding>
                            </TextBox.Text>
                        </TextBox>
                        <TextBox Height="36" HorizontalAlignment="Left" Margin="174,0,0,120" Name="txtStudenAdress" VerticalAlignment="Bottom" Width="240" IsEnabled="False" Text="{Binding lastName}"/>
                        <TextBox Height="36" HorizontalAlignment="Left" Margin="174,0,0,280" Name="txtStudenHomePhone" VerticalAlignment="Bottom" Width="240" IsEnabled="False" Text="{Binding homePhone}"/>
                        <TextBox Height="36" HorizontalAlignment="Left" Margin="174,0,0,240" Name="txtStudenCellPhone" VerticalAlignment="Bottom" Width="240" IsEnabled="False" Text="{Binding cellPhone}"/>
                        <TextBox Height="36" HorizontalAlignment="Left" Margin="614,0,0,320" Name="txtStudenMedical" VerticalAlignment="Bottom" Width="240" IsEnabled="False" Text="{Binding medProblems}"/>
                        <TextBox Height="36" HorizontalAlignment="Left" Margin="174,0,0,200" Name="txtStudenParentsPhone" VerticalAlignment="Bottom" Width="240" IsEnabled="False" Text="{Binding parentsPhone}"/>
                        <TextBox Height="36" HorizontalAlignment="Left" Margin="174,0,0,160" Name="txtStudenParentsName" VerticalAlignment="Bottom" Width="240" IsEnabled="False" Text="{Binding parentsName}"/>
                        <TextBox Height="36" HorizontalAlignment="Left" Margin="174,0,0,80" Name="txtStudenBirthDay" VerticalAlignment="Bottom" Width="240" IsEnabled="False" Text="{Binding birthDate}"/>

                        <Button Content="ערוך תלמיד" Style="{StaticResource myButtonStyle}" Height="40" HorizontalAlignment="Left" Margin="130,0,0,10" Name="btnEditStuden" VerticalAlignment="Bottom" Width="118" />
                        <Button Content="הוסף תלמיד" Style="{StaticResource myButtonStyle}" Height="40" HorizontalAlignment="Left" Margin="6,0,0,10" Name="btnAddStuden" VerticalAlignment="Bottom" Width="118" />
                        <Button Content="מחק תלמיד" Style="{StaticResource myButtonStyle}" Height="40" HorizontalAlignment="Left" Margin="254,0,0,10" Name="btnDeleteStudent" VerticalAlignment="Bottom" Width="118" />
                        <Button Style="{StaticResource myButtonStyle}" Content="הבא" Height="23" HorizontalAlignment="Left" Margin="633,0,0,6" Name="btnStudenNext" VerticalAlignment="Bottom" Width="75"/>
                        <Button Style="{StaticResource myButtonStyle}" Content="הקודם" Height="23" HorizontalAlignment="Left" Margin="552,0,0,6" Name="btnStudenPrev" VerticalAlignment="Bottom" Width="75"/>

                        <ListBox Height="207" HorizontalAlignment="Left" Margin="614,0,0,80" Name="lstBxClasses" VerticalAlignment="Bottom" Width="240" ItemsSource="{Binding Path=classesList.className}"/>


                        <TextBlock Height="33" HorizontalAlignment="Left" Margin="913,0,0,260" Name="txtBlkDebt" Style="{StaticResource textStyle}" Text="יתרת חשבון:" VerticalAlignment="Bottom" Width="131" />

                        <Rectangle Height="4" HorizontalAlignment="Left" Margin="913,0,0,400" Name="rectangle2" Stroke="Black" VerticalAlignment="Bottom" Width="312" />
                        <Rectangle Height="426" HorizontalAlignment="Left" Margin="900,0,0,10" Name="rectangle3" Stroke="Black" VerticalAlignment="Bottom" Width="333" />
                        <TextBox Height="36" HorizontalAlignment="Left" IsEnabled="False" Margin="909,0,0,226" Name="txtDebt" VerticalAlignment="Bottom" Width="312" />
                        <Button Content="הרשם לחוג" Height="40" HorizontalAlignment="Left" Margin="909,0,0,20" Name="btnPay" Style="{StaticResource myButtonStyle}" VerticalAlignment="Bottom" Width="312" Click="btnPay_Click" />
                        <CheckBox Height="36" HorizontalAlignment="Left" Margin="614,15,0,0" Name="cbPicConf" VerticalAlignment="Top" FontSize="24" Width="38" BorderThickness="1" IsChecked="{Binding isPicFormExists}" IsEnabled="False" />
                        <CheckBox BorderThickness="1" FontSize="24" Height="36" HorizontalAlignment="Left" Margin="614,51,0,0" Name="cbParentsConf" VerticalAlignment="Top" Width="38" IsChecked="{Binding isParentsConfExists}" IsEnabled="False" />

                    </Grid>
                </Border>
                <Label Content="רשימת תלמידים" HorizontalAlignment="Stretch" Margin="18,0,30,234" Name="lblStudentsList" VerticalAlignment="Bottom" Width="1208" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" FontSize="36" />
                <TextBlock Height="33" HorizontalAlignment="Left" Margin="68,0,0,196" Name="textBlock1" Style="{StaticResource textStyle}" Text="שם פרטי:" VerticalAlignment="Bottom" Width="159" />
                <TextBlock Height="33" HorizontalAlignment="Left" Margin="492,0,0,192" Name="textBlock2" Style="{StaticResource textStyle}" Text="תעודת זהות:" VerticalAlignment="Bottom" Width="159" />
                <TextBox Height="36" HorizontalAlignment="Left" IsEnabled="True" Margin="219,0,0,192" Name="txtFindFirstName" VerticalAlignment="Bottom" Width="240" />
                <TextBox Height="36" HorizontalAlignment="Left" IsEnabled="True" Margin="638,0,0,192" Name="txtFindID" VerticalAlignment="Bottom" Width="240" />
                <DataGrid AutoGenerateColumns="False" Height="126" Name="dgStudents" Width="1157" Margin="25,0,74,64" VerticalAlignment="Bottom" ItemsSource="{Binding}" ScrollViewer.CanContentScroll="True" 
  ScrollViewer.VerticalScrollBarVisibility="Auto"
  ScrollViewer.HorizontalScrollBarVisibility="Auto" IsReadOnly="True" SelectionChanged="dgStudents_SelectionChanged">
                    <DataGrid.Columns>
                        <DataGridTextColumn Header="שם פרטי" Width="175" Binding="{Binding firstName}" />
                        <DataGridTextColumn Header="שם משפחה" Width="175" Binding="{Binding lastName}" />
                        <DataGridTextColumn Header="תעודת זהות" Width="175" Binding="{Binding studentID}" />
                        <DataGridTextColumn Header="תאריך לידה" Width="175" Binding="{Binding birthDate}" />
                        <DataGridTextColumn Header="מאזן חשבון" Width="175" Binding="{Binding accountBalance}" />
                        <DataGridTextColumn Header="טלפון - בית" Width="175" Binding="{Binding homePhone}" />
                        <DataGridTextColumn Header="טלפון סלולרי" Width="175" Binding="{Binding cellPhone}" />
                        <DataGridTextColumn Header="טלפון - הורים" Width="175" Binding="{Binding parentsPhone}" />
                        <DataGridTextColumn Header="שם ההורים" Width="175" Binding="{Binding parentsName}" />
                        <DataGridTextColumn Header="כתובת" Width="175" Binding="{Binding adress}" />
                        <DataGridCheckBoxColumn Header="טופס אישור צילום" Width="175" Binding="{Binding isPicFormExists}" />
                        <DataGridCheckBoxColumn Header="טופס אישור הורים" Width="175" Binding="{Binding isParentsConfExists}" />
                        <DataGridTextColumn Header="בעיות רפואיות" Width="175" Binding="{Binding medProblems}" />
                    </DataGrid.Columns>
                </DataGrid>
            </Grid>
        </TabItem>

代码隐藏:

 public partial class MainWindow : Window, INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private student _selectedStudent;

    public student selectedStudent  // This is the object
    {
        get { return _selectedStudent; }
        set
        {
            if (value != _selectedStudent)
            {
                _selectedStudent = value;
                OnPropertyChanged("_selectedStudent");
            }
        }
    }
    public MainWindow()
    {
            InitializeComponent();

            selectedStudent = clsLoadStudent();
            this.DataContext = selectedStudent;  // Here I use the object as a datacontext.
    }
    private void dgStudents_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        selectedStudent = new student();
        selectedStudent = (student)dgStudents.SelectedItem;


    }
    protected void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null) // if there is any subscribers
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

有人告诉我实施OnPropertyChanged。我想是的。

【问题讨论】:

  • OnPropertyChanged("_selectedStudent"); 应该是 OnPropertyChanged("selectedStudent");
  • 在调试中,您是否看到分配 selectedStudent 时调用了 OnPropertyChanged? firstName 是公共财产吗?
  • LPL - 已更改。同样的问题。 Blam - 是的,是的......同样的问题。
  • 你打电话给OnPropertyChanged("firstName"); 不带下划线?
  • 多种方式(用于改进)。我认为最简单的是将 Border 的 DataContext 绑定到 dgStudents.SelectedItem。 &lt;Border DataContext="{Binding SelectedItem, ElementName=dgStudents}" Name="brdrStudents" ... 并删除 dgStudents_SelectionChanged 处理程序。

标签: c# wpf xaml data-binding textbox


【解决方案1】:

您已经在MainWindow 类上实现了INotifyPropertyChanged,这是正确的,但是您使用DataContext 作为您的代码所建议的属性名称(这不起作用,可能是您的绑定不起作用的原因):

//Below DataContext binding needs to be changed, you are binding directly to property, instead you should bind to you MainWindow object
public MainWindow()
{
        InitializeComponent();

        selectedStudent = clsLoadStudent();
        //this.DataContext = selectedStudent;  // Does not work
        this.DataContext = this;  // Correct way           
}   

然后,您应该将Textbox 文本属性绑定更改为指向您的student 对象属性中的属性,如下所示(selectedStudent.FirstName):

<TextBox Height="36" HorizontalAlignment="Left" Margin="174,0,0,400" Name="txtStudenName" VerticalAlignment="Bottom" Width="240" IsEnabled="False" Text={Binding selectedStudent.FirstName, NotifyOnTargetUpdated=True, UpdateSourceTrigger=PropertyChanged}/>

此外,您应该为属性名称引发 propertychanged 事件:

OnPropertyChanged("selectedStudent");

【讨论】:

    【解决方案2】:

    如果您打算使用MainWindow.xaml.cs,那么我建议您定义一个DependencyProperty 来代替:

    public static readonly DependencyProperty StudentProperty = DependencyProperty.
        Register("Student", typeof(Student), typeof(MainWindow), new 
        UIPropertyMetadata(100.0));
    
    public Student Student
    {
        get { return (Student)GetValue(StudentProperty); }
        set { SetValue(StudentProperty, value); }
    }
    

    然后,您必须设置您的DataContext... 最简单(但不是最好)的方法是在构造函数中执行此操作:

    public MainWindow()
    {
        InitializeComponent();
        Student = new Student() { FirstName = "John", OtherProperty = "Something else" };
        DataContext = this;
    }
    

    现在从您的Student 对象绑定到一个属性(假设您在其中有一个名为FirstName 的属性):

    <TextBox Text="{Binding Student.FirstName}" />
    

    【讨论】:

    • 我不明白。什么时候为对象赋值?
    • 您可以随时随地执行此操作...我更新了答案,将其添加到构造函数中。
    【解决方案3】:

    你需要再次设置DataContext

    private void dgStudents_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            selectedStudent = new student();
            DataContext = (student)dgStudents.SelectedItem;
        }
    

    【讨论】:

    • 好吧,如果我这样做,它就解决了问题:txt.dataContext = dg.selectedItem。对于每个文本框。我认为数据绑定可以防止这样的事情...... ??
    • 窗口位于文本框的顶层。如果您没有设置文本框的 DataContext ,它将尝试使用父控件之一 => Grid=>Grid=>TabItem .... 窗口。当您在代码中设置 this.DataContex 时,您正在设置 Window 的 DataContext,以便其他控件也可以使用它(文本框)。我的代码也应该可以工作。我建议您查看 MVVM 模式,因为 ModelView 类应该是 View(Window) 的 DataContext 上的类。 ModelView 会将属性公开为 SelectedStudent,您将从 TextBox (Text="{Binding SelectedStudent.FirstName}) 绑定到此属性。
    猜你喜欢
    • 1970-01-01
    • 2011-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-18
    • 1970-01-01
    • 2015-05-16
    • 1970-01-01
    相关资源
    最近更新 更多