我有以下测试代码......
XAML:
<Page
x:Class="Test.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Test"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:data="using:Test"
mc:Ignorable="d">
<Grid Background="White">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Button Name="StartButton" Content="Start" Click="StartButton_Click" Height="30" Width="200"/>
<ItemsControl Name="MyItemsControl" Grid.Row="1" Background="Gray" ItemsSource="{x:Bind RowItems, Mode=OneWay}">
<ItemsControl.ItemTemplate>
<DataTemplate x:DataType="data:MyData">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{x:Bind FirstName, Mode=OneWay}" Margin="10,0,5,0"/>
<TextBlock Text="{x:Bind Surname, Mode=OneWay}"/>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
</Page>
代码背后:
namespace Test
{
public class MyData : INotifyPropertyChanged
{
private string firstName;
public string FirstName
{
get { return firstName; }
set { firstName = value; OnPropertyChanged("FirstName"); }
}
private string surName;
public string Surname
{
get { return surName; }
set { surName = value; OnPropertyChanged("Surname"); }
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
public class LoadData
{
public static void Get_RowItems(ObservableCollection<MyData> Items)
{
Items.Add(new MyData() { FirstName = "John", Surname = "Doe" });
}
}
public sealed partial class MainPage : Page
{
private ObservableCollection<MyData> RowItems;
public MainPage()
{
this.InitializeComponent();
RowItems = new ObservableCollection<MyData>();
LoadData.Get_RowItems(RowItems);
}
private void StartButton_Click(object sender, RoutedEventArgs e)
{
RowItems[0].FirstName = "Bill";
RowItems[0].Surname = "Smith";
}
}
}
虽然运行它看起来很好,但ItemsControl只在StartButton_Click事件处理程序完成后更新,但我需要它在StartButton_Click事件处理程序内的每个属性值更改时更新。
点击开始按钮之前,显示屏显示&#39; John Doe&#39;
作为RowItems [0] .FirstName =&#34; Bill&#34 ;;完成显示后应显示比尔·多伊&#39;
在RowItems [0]之后。姓氏&#34;史密斯&#34 ;;完成显示应该显示比尔史密斯&#39;
I.E我需要在属性值更改后立即更改显示。
任何帮助都将不胜感激。
答案 0 :(得分:2)
就像我上面说的那样,你的代码看起来很正确。显示异步呈现,因此可能只是更新被批处理。你可以试试像:
private async void StartButton_Click(object sender, RoutedEventArgs e)
{
RowItems[0].FirstName = "Bill";
await Task.Delay(2000);
RowItems[0].Surname = "Smith";
}
设置名字后,这将暂停2秒钟。我怀疑你会看到&#34; Bill Doe&#34; 2秒,然后&#34;比尔史密斯&#34;。
如果是这种情况,那么一切基本上都按预期工作。在这种情况下,您需要更多地解释您想要发生的事情。如果显示器显示&#34; Bill Doe&#34;只需几分之一秒,然后显示比尔史密斯&#34;,如果它的更新速度超过你能看到的,该怎么办?