我知道我应该使用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”的东西,因为我正在使用一个observablecollection? 所以我得到了一个像这样的文本框:
<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;
}
}
}
答案 0 :(得分:0)
您需要实现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;
}
}
}