我正在尝试制作 ListBox 根据一些变化的数据更新其内容。XAML 如下
StackPanel Orientation="Vertical">
<ListBox x:Name="listWatch" >
<ListBox.ItemTemplate>
<DataTemplate>
<Grid ShowGridLines="True">
<Grid Grid.Column="0" Background="{Binding Path=Color">
<TextBlock Text="{ Binding Path=LTP}" Padding="2 2 2 2"/>
</Grid>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Button x:Name="btn" Click="btn_Click" Content="Button" />
我用于表单数据结构的类如下
public class WatchRow : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
string _color;
decimal _lTP;
public WatchRow(decimal LTP,string color)
{
this.LTP = LTP;
this.Color = color;
}
public string Color
{
get { return _color; }
set{
_color = value;
OnPropertyChanged(_color);
}
}
public decimal LTP
{
get { return _lTP; }
set
{
_lTP = value;
OnPropertyChanged(_lTP.ToString());
}
}
protected void OnPropertyChanged(string info)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(info));
}
}
}
public class Watch:ObservableCollection<WatchRow>
{
public Watch():base()
{
}
}
文件后面的代码就像
Watch watch = new Watch();
private void PhoneApplicationPage_Loaded_1(object sender, RoutedEventArgs e)
{
watch.Add(new WatchRow(132, "black"));
watch.Add(new WatchRow(123, "red"));
listWatch.ItemsSource = watch;
watch[0].Color = "green";
}
private void btn_Click(object sender, RoutedEventArgs e)
{
watch[0].Color = "green";
}
我的问题是我无法通过在 btn_Click 中设置颜色属性(watch[0].Color = "green";)来更改列表框项的颜色,如代码所示。但是相同的代码在PhoneApplicationPage_Loaded_1 中有效。我不知道我错了什么。有任何想法吗?