【发布时间】:2018-11-16 07:56:48
【问题描述】:
我是对象绑定的新手,但我无法成功。
我有一个带有以下文本框的 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代码中,我定义了我的Project类的一个实例,叫做currentproj,如下:
public partial class MainWindow : Window{
Project currentproj;
public MainWindow()
{
currentproj = new Project();
InitializeComponent();
}}
项目类(在 Project.cs 文件中定义)如下:
公共部分类项目:组件,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 事件始终为空,但我不明白为什么。
【问题讨论】:
-
您是否尝试过在 XAML 中的
Binding中设置Mode=TwoWay?