![](/img/trans.png)
[英]Listbox with databinding to ObservableCollection won't update UI
[英]ObservableCollection binding to listbox ui doesn't update
我知道我应该使用MVVM模式,但我正在尝试逐步接近它。 所以这是我的列表框:
<ListBox x:Name="BoardList" ItemsSource="{Binding notes}" >
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
<TextBox IsReadOnly="True" ScrollViewer.VerticalScrollBarVisibility="Visible" Text="{Binding text}" TextWrapping="Wrap" Foreground="DarkBlue"></TextBox>
<AppBarButton Visibility="{Binding visibility}" Icon="Globe" Click="OpenInBrowser" x:Name="Link"></AppBarButton>
<AppBarButton Icon="Copy" Click="Copy"></AppBarButton>
<AppBarButton Icon="Delete" Click="Delete"></AppBarButton>
</StackPanel>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
在Mainpage.xaml.cs中,我声明以下内容:
ObservableCollection<BoardNote> notes = new ObservableCollection<BoardNote>();
因此,如果我理解这项权利,就不必担心“ INotifyCollectionChanged”的问题,因为我使用的是可观察的集合? 因此,我得到了一个像这样的文本框:
<Textbox x:Name="UserInputNote" Placeholdertext="Type in a text for your note"></Textbox>
还有一个将新注释添加到ObservableCollection和click事件的按钮,如下所示:
notes.Add(new BoardNote(UserInputNote.Text));
因此,现在,用户每次单击按钮以保存新笔记时,UI均应更新。 但是什么也没发生。 我做错了什么?
如果需要,这里是BoardNote类:
class BoardNote
{
public string text
{
get; set;
}
public BoardNote(string text)
{
this.text = text;
}
public Visibility visibility
{
get
{
if (text.StartsWith("http"))
return Visibility.Visible;
else
return Visibility.Collapsed;
}
}
}
您需要实现INotifyPropertyChanged。 这是一种方法。
创建此NotificationObject类。
public class NotificationObject : INotifyPropertyChanged
{
protected void RaisePropertyChanged<T>(Expression<Func<T>> action)
{
var propertyName = GetPropertyName(action);
RaisePropertyChanged(propertyName);
}
private static string GetPropertyName<T>(Expression<Func<T>> action)
{
var expression = (MemberExpression)action.Body;
var propertyName = expression.Member.Name;
return propertyName;
}
private void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
然后,您的BoardNote类将以这种方式继承它:
class BoardNote : NotificationObject
{
private string _text
public string Text
{
get {return _text;}
set
{
if(_text == value) return;
_text = value;
RaisePropertyChanged(() => Text);
}
}
public BoardNote(string text)
{
this.text = text;
}
public Visibility visibility
{
get
{
if (text.StartsWith("http"))
return Visibility.Visible;
else
return Visibility.Collapsed;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.