C# 文本块未更新
我添加了一个文本块,并将数组的第一项绑定到该文本块。我调用了一些API来获取该数组的数据。但向该数组添加值时,文本块不会更新。调用API时,获取数据需要一段时间,此时将呈现文本块。因此,呈现文本块后,UI不会更新 XAML:C# 文本块未更新,c#,wpf,textblock,C#,Wpf,Textblock,我添加了一个文本块,并将数组的第一项绑定到该文本块。我调用了一些API来获取该数组的数据。但向该数组添加值时,文本块不会更新。调用API时,获取数据需要一段时间,此时将呈现文本块。因此,呈现文本块后,UI不会更新 XAML: 为了将多个文本块绑定到可修改的字符串集合,您可以轻松地将ItemsControl与以下视图模型结合使用: public class ViewModel { public ObservableCollection<string> Items { get;
为了将多个文本块绑定到可修改的字符串集合,您可以轻松地将ItemsControl与以下视图模型结合使用:
public class ViewModel
{
public ObservableCollection<string> Items { get; }
= new ObservableCollection<string>(
Enumerable
.Range(1, 20)
.Select(i => i.ToString())); // or any other initial values
}
在XAML中,使用ItemsControl:
<ItemsControl ItemsSource="{Binding Items}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
将替换集合中的第一个字符串,从而更新ItemsControl。
this.ItemSource[0]=“测试之后”代码>不会触发任何类型的会触发绑定的更改通知。除此之外,设置Mode=TwoWay
对TextBlock的Text属性没有意义,并且UpdateSourceTrigger=PropertyChanged
对单向绑定没有影响。@Clemens那么在向该数组添加项时,如何更新该文本块?使用实现INotifyPropertyChanged的类的实例填充该数组。例如,创建适当的StringWrapper类。然后像Text=“{Binding Path=ItemSource[0].Value}”那样绑定,并通过this.ItemSource[0].Value=“Test After”更新Value属性除此之外,还不清楚为什么要对数组元素进行这样的绑定。这有点不寻常。@LupuSilviu这显然是一个字符串[]
public class ViewModel
{
public ObservableCollection<string> Items { get; }
= new ObservableCollection<string>(
Enumerable
.Range(1, 20)
.Select(i => i.ToString())); // or any other initial values
}
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModel();
}
<ItemsControl ItemsSource="{Binding Items}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
((ViewModel)DataContext).Items[0] = "Hello";