【问题标题】:wpf two way binding not workingwpf双向绑定不起作用
【发布时间】:2011-10-14 09:04:02
【问题描述】:

我有

 <Grid Name="thisPage">
  <TextBlock Name="tbtb" />
  <ScrollViewer Name="sv4" Visibility="Hidden">
    <ItemsControl ItemsSource="{Binding}">
                 <ItemsControl.ItemTemplate>
                     <DataTemplate>
                       <TextBox Text="{Binding Title, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" TextChanged="TextBox_TextChanged"/> 
                     </DataTemplate> 
                 </ItemsControl.ItemTemplate> 
             </ItemsControl>
   </ScrollViewer>
  </Grid>

在 MainWindow.vb 中,我有

movieArray as ObservableCollection(of Movie)

For i As Integer = 0 To 5 
        Me.movieArray.Add(New Movie(i)) 
    Next

Me.sv4.DataContext = Me.movieArray
Me.listBox5.DataContext = Me.movieArray

 Private Sub TextBox_TextChanged(sender As System.Object, e As System.Windows.Controls.TextChangedEventArgs)

        Me.tbtb.Text = ""
        For Each m As Movie In movieArray
            Me.tbtb.Text += p.Title.ToString + " ^ "
        Next
       End Sub

Class Movie
    Implements INotifyPropertyChanged

  Public Event PropertyChanged As PropertyChangedEventHandler _
        Implements INotifyPropertyChanged.PropertyChanged

    Private Sub NotifyPropertyChanged(ByVal info As String)
        RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(info))
    End Sub

 Property Title As Integer
        Get
            Return Me._title
        End Get
        Set(value As Integer)
            Me._title = value
            If Not (value = _title) Then
                Me._title= value
                NotifyPropertyChanged("Title")
            End If
        End Set
    End Property 

对于我的下一页,

 <Grid Name="nextPage" Visibility="Hidden" > 
            <ListBox Name="listBox5" >
            <ItemsControl ItemsSource="{Binding}">
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Title}"/>
                    </DataTemplate> 
                </ItemsControl.ItemTemplate> 
            </ItemsControl>
        </ListBox>
        </Grid > 

要更改页面,我只需使用返回、下一步按钮切换 thisPage 和 nextPage 的可见性。

我不确定我做错了什么:-

  1. listbox5 仅显示原始值,未更改任何内容 文本框。
  2. tbtb,但是能够更新其值

【问题讨论】:

  • 知道了。它是 if 条件之前 set 方法中额外的Me._title = value

标签: wpf vb.net binding inotifypropertychanged two-way


【解决方案1】:

我认为问题可能出在您的“标题”属性设置器上。

我是 C# 专家,不是 VB 专家...但似乎永远不会调用 NotifyPropertyChanged。

value = _title 将始终为真,因为您只是在上一行代码中设置了Me._title = value。因此,您将永远不会执行 if 语句中的任何代码。

【讨论】:

    【解决方案2】:

    为什么你使用 Textchanged evetn 以两种方式绑定你不需要那种东西。两种方式绑定是直接将值从视图绑定到属性以及从属性绑定到视图

    所以不要使用 textchanged 事件并重试。这会起作用。

    【讨论】:

    • 它验证最初是否正常工作,如果它在 textchanged 中工作,它应该在下一页工作。另外,我试过没有 textchanged,它不工作
    猜你喜欢
    • 2014-04-10
    • 1970-01-01
    • 2019-11-13
    • 2012-02-14
    • 1970-01-01
    • 2014-03-12
    • 1970-01-01
    相关资源
    最近更新 更多