【发布时间】:2015-12-13 21:50:46
【问题描述】:
我有以下测试代码……
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 事件处理程序内的每个属性值都发生变化。
点击开始按钮前显示'John Doe'
作为 RowItems[0].FirstName = "Bill";完成显示应该显示“Bill Doe”
在 RowItems[0].Surname = "Smith" 之后;完成显示应该显示“Bill Smith”
I.E 我需要在属性值更改后立即更改显示。
任何帮助将不胜感激。
【问题讨论】:
-
这里的代码/XAML 看起来是正确的。您能告诉我们 StartButton_Click() 中的代码吗?
-
@gregstoll - 它应该在 Code Behind(向下滚动)窗格的底部。
-
哈,对不起,我错过了!