我在WP8.1上有一个ListBox
,想在那里绑定一些项目。这样做很好,但更改ItemSource
上的值并不会改变ListBox
<ListBox x:Name="myListBox" Width="Auto" HorizontalAlignment="Stretch" Background="{x:Null}" Foreground="{x:Null}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel x:Name="PanelTap" Tapped="PanelTap_Tapped">
<Border x:Name="BorderCollapsed">
<StackPanel Margin="105,0,0,0">
<TextBlock Text="{Binding myItem.location, Mode=TwoWay}" />
</StackPanel>
</Border>
</ListBox.ItemTemplate>
</ListBox>
我通过
绑定项目ObservableCollection<LBItemStruct> AllMyItems = new ObservableCollection<LBItemStruct>();
与
public sealed class LBItemStruct
{
public bool ext { get; set; }
public Container myItem { get; set; }
}
public sealed class Container
{
public string location{ get; set; }
...
}
当我现在想要更改TextBlock
文本时,没有任何反应
private void PanelTap_Tapped(object sender, TappedRoutedEventArgs e)
{
int sel = myListBox.SelectedIndex;
if (sel >= 0)
{
myListBox[sel].myItem.location = "sonst wo";
}
}
当我点击面板(通过调试检查)时,PanelTap_Tapped
被触发,但TextBlock文本没有改变
答案 0 :(得分:2)
如果您希望在属性更改时更新视图,则需要使源对象实现INotifyPropertyChaned
,并引发PropertyChanged
事件:
public sealed class Container : INotifyPropertyChanged
{
public string location
{
get { return _location; }
set { _location = value; RaisePropertyChanged("location"); }
}
private string _location;
...
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string propName)
{
var handler = PropertyChanged;
if (handler != null)
handler(new PropertyChangedEventArgs(this, propName));
}
}