以下是我在MainWindow.xaml.cs中的代码:
namespace Test
{
public partial class MainWindow : Window
{
public class ChannelInfo : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void Notify(string propertyName)
{
if (this.PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
private string _channelDescription;
public string ChannelDescription
{
get
{
return _channelDescription;
}
set
{
if (value != _channelDescription)
{
_channelDescription = value;
Notify("ChannelDescription");
}
}
}
}
public ObservableCollection<ChannelInfo> Channels { get; set; }
public MainWindow()
{
InitializeComponent();
Channels = new ObservableCollection<ChannelInfo>()
{
new ChannelInfo() { ChannelDescription = "Ib" }
};
DataContext = Channels;
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
//((ObservableCollection<ChannelInfo>)DataContext).Add(new ChannelInfo() { ChannelDescription = "Ib" });
}
}
}
在我的XAML中,我的TextBox
定义如下:
<TextBox Height="23" Text="{Binding ChannelDescription}" HorizontalAlignment="Left" Margin="180,106,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" />
现在我的问题是如果我在构造函数本身中向Channels
添加一个项目,那么TextBox
正在显示绑定文本。但是当我在上面的Window_Loaded
中添加它(取消注释该行)时,不显示文本。