我是对象绑定的新手,我不能成功地使它工作。
我有一个带有以下文本框的xaml窗口:
<Grid x:Name="gr_main" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="180,65,0,0" DataContext="{Binding currentproj}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBox Grid.Row="0" Grid.Column="2" x:Name="txt_localdir" Height="25" TextWrapping="Wrap" Width="247" IsEnabled="False" Text="{Binding Path=Localdir, UpdateSourceTrigger=PropertyChanged}"/>
在主窗口的cs代码中,我定义了一个名为currentproj的Project类的实例,如下所示:
public partial class MainWindow : Window{
Project currentproj;
public MainWindow()
{
currentproj = new Project();
InitializeComponent();
}}
项目类(在Project.cs文件中定义)如下:
public partial class Project:Component,INotifyPropertyChanged { 公共事件PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
private string _localdir;
public string Localdir
{
get { return _localdir; }
set
{
if (value != _localdir)
{
_localdir = value;
NotifyPropertyChanged("Localdir");
}
}
}
public Project()
{
InitializeComponent();
}
public Project(IContainer container)
{
container.Add(this);
InitializeComponent();
}}
但是,即使我将textbox.text属性绑定到currentproj对象的Localdir路径,也永远不会更新文本框。当我设置Localdir的值时,我看到PropertyChanged事件是alwais null,但我不明白为什么。
答案 0 :(得分:1)
数据绑定适用于DataContext。网格的DataContext设置不正确,应该删除。
所以网格定义应该是:
<Grid x:Name="gr_main" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="180,65,0,0">
将Window DataContext设置为currentProj,方法是:
public partial class MainWindow : Window{
Project currentproj;
public MainWindow()
{
currentproj = new Project();
DataContext = currentproj;
InitializeComponent();
}}