数据绑定到ObservableCollection

时间:2013-08-16 06:45:39

标签: c# wpf data-binding observablecollection

以下是我在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中添加它(取消注释该行)时,不显示文本。

0 个答案:

没有答案