C#列表框更新绑定文本
本文关键字:绑定 文本 更新 列表 | 更新日期: 2023-09-27 18:29:46
我在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 Text不会更改
如果您想在属性更改时更新视图,那么您需要让源对象实现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));
}
}