該問題已在標題中進行了解釋。請仔細查看XAML和代碼,因爲我是C#中的一名業餘愛好者(只有基本知識),並且幾乎是全新的Data Binding。因此,這裏是我的XAML:帶有數據綁定到ObservableCollection的列表框不會更新UI
public sealed partial class MainPage : Page
{
ObservableCollection<BoardNote> notes = new ObservableCollection<BoardNote>();
public MainPage() //empty for post
{
this.InitializeComponent();
}}
類BoardNote
:
class BoardNote : NotificationObject
{
private string _text { get; set; }
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;
}
}
}
而且Notification
類:
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;
}
<ListBox x:Name="BoardList" ItemsSource="{Binding notes, Mode=OneWay,UpdateSourceTrigger=PropertyChanged}" >
<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
Listbox
在按鈕上不添加新項目。我不知道該怎麼做,我是新來的,但我很快就瞭解新事物。
您是否定義了Datacontext在頁面中? (綁定獲取內容) –
@JuanPabloGarciaCoello我忘了,現在我調整它:DataContext =「{綁定說明,模式= OneWay,UpdateSourceTrigger = PropertyChanged}」,但它仍然無效,數據上下文有什麼區別和itemsource? –