don*_*yte 3 vb.net wpf binding mvvm visual-studio-2010
可能重复:将
WPF属性绑定到变量的数据
如何将我的module1属性绑定到WPF TextBox1?
WPF代码:
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBox Height="23" HorizontalAlignment="Left" Margin="210,146,0,0" Name="TextBox1" VerticalAlignment="Top" Width="120" />
</Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)
VB.net代码:
Module Module1
ReadOnly Property tbBinding As String
Get
Return "Success!"
End Get
End Property
End Module
Run Code Online (Sandbox Code Playgroud)
下面是根据我得到的反馈和我正在做的阅读工作的代码。/ ####### progres中的当前代码(尝试使用类而不是模块)####### /
XAML:
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid DataContext="Class1">
<TextBox Height="23" HorizontalAlignment="Left" Margin="210,146,0,0" Name="TextBox1" VerticalAlignment="Top" Width="120" Text="{Binding Path=tbBinding2}"/>
<Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="192,74,0,0" Name="Button1" VerticalAlignment="Top" Width="75" />
</Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)
第1类:
Imports System.ComponentModel
Public Class Class1
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
Dim varField As String = String.Empty
Public Property tbBinding2 As String
Get
Return varField
End Get
Set(value As String)
varField = value
NotifyPropertyChanged("tbBinding2")
End Set
End Property
End Class
Run Code Online (Sandbox Code Playgroud)
主窗口:
Class MainWindow
Private Sub Button1_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles Button1.Click
Dim myClass1 As New Class1
myClass1.tbBinding2 = "Success!"
End Sub
End Class
Run Code Online (Sandbox Code Playgroud)
您没有在DataContext任何地方设置
WPF有两层:数据层和UI层。数据层是null默认设置,您可以通过设置DataContext任何UI对象的属性来进行设置。绑定用于将数据从数据层拉到UI层。
因此,如果您说MainWindow.DataContext = new Class1(),那么您将数据层beind设置为对象MainWindow的新实例Class1。
写<TextBox Text="{Binding tbProperty}" />在XAML告诉WPF在数据层来寻找所谓财产tbProperty,并使用它的Text价值TextBox。
如果您tbProperty在Class1用作的对象DataContext中更改,则该更改也将反映在TextBox.Text(前提是您已实现INotifyPropertyChanged)。并且,如果将绑定模式设置为TwoWay(默认设置为TextBox.Text),则更改为TextBox.Text也会更新tbProperty数据层中的。
实际上,DataContext如果您有兴趣,我最近在我的博客上发布了概述。
| 归档时间: |
|
| 查看次数: |
8628 次 |
| 最近记录: |