将列表绑定到ItemsControl:如何刷新

约翰尼斯·沙赫特(Johannes Schacht)

我将一个列表绑定到ItemsControl。我很好。但是,当我向列表中添加字符串时,控件不会更新。我试图引发PropertyChanged事件以强制进行更新,但这无济于事。我究竟做错了什么?

这是XAML:

<Window x:Class="tt.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">
<StackPanel>
    <ItemsControl ItemsSource="{Binding Strings}"/>
    <Button Click="Button_Click">Add</Button>
</StackPanel>
</Window>

这是背后的代码:

 public partial class MainWindow : Window, INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;
        Strings.Add("One");
        Strings.Add("Two");
    }

    public List<string> _strings = new List<string>();
    public List<string> Strings
    {
        get { return _strings; }
        set
        {
            if (_strings == value) return;
            _strings = value;
            if (this.PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs("Strings"));
        }
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        Strings.Add("More");
        if (this.PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs("Strings"));
    }
}
克米亚塞克(Kmatyaszek)

更改List<string>ObservableCollection<string>msdn)。

public ObservableCollection<string> _strings = new ObservableCollection<string>();
public ObservableCollection<string> Strings
{
    get { return _strings; }
    set
    {
        if (_strings == value) return;
        _strings = value;
        if (this.PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs("Strings"));
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何将列表绑定到ItemsControl中的文本框

将标签绑定到ItemsControl

如何将 ItemsControl(网格外)绑定到网格?

如何将PreviewMouseDown绑定到ItemsControl中的FormattedText

如何将枚举ItemsControl绑定到WPF中的集合?

无法将 ItemsControl 绑定到 ObservableCollection

将命令绑定到 ItemsControl 内的按钮

如何将列表绑定到DropDownList

如何访问绑定到UserControl的ItemsControl的项目?

如何将ListBox绑定到列表并绑定int?

如何将 ObservableCollection 的前 N 个项目绑定到 ItemsControl?

如何将 Expander 的 IsExpanded 属性绑定到 Items.Count 作为 ItemsControl in Style 的 Expander 内容

将Dictionary <string,DataTable>绑定到ItemsControl不起作用

将内部 ContentControl 控件绑定到父 ItemsControl 项

如何将列表模型绑定到视图?

如何将GridView绑定到XAML中的视频列表?

如何将模型值绑定到静态下拉列表

如何将基本类型列表绑定到DataGrid

如何将ComboBox绑定到JavaFX中的列表?

如何将数据绑定到弹簧形式的列表

如何将剑道下拉列表绑定到模型属性?

如何将命令从IntemsControl列表绑定到主ViewModel?

如何将Vue数据绑定到下拉列表

如何将itemSource绑定到XAML中的列表

Silverlight 如何将属性绑定到列表项值

如何将命令绑定到列表框项目?

如何将属性绑定到动态对象列表

如何将列表项绑定到gridview

将列表集合绑定到列表视图