Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/293.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 文本块未更新_C#_Wpf_Textblock - Fatal编程技术网

C# 文本块未更新

C# 文本块未更新,c#,wpf,textblock,C#,Wpf,Textblock,我添加了一个文本块,并将数组的第一项绑定到该文本块。我调用了一些API来获取该数组的数据。但向该数组添加值时,文本块不会更新。调用API时,获取数据需要一段时间,此时将呈现文本块。因此,呈现文本块后,UI不会更新 XAML: 为了将多个文本块绑定到可修改的字符串集合,您可以轻松地将ItemsControl与以下视图模型结合使用: public class ViewModel { public ObservableCollection<string> Items { get;

我添加了一个文本块,并将数组的第一项绑定到该文本块。我调用了一些API来获取该数组的数据。但向该数组添加值时,文本块不会更新。调用API时,获取数据需要一段时间,此时将呈现文本块。因此,呈现文本块后,UI不会更新

XAML:


为了将多个文本块绑定到可修改的字符串集合,您可以轻松地将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属性字符串[]
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";