我從一些示例代碼開始說明我的問題。但我是新來的,所以它可能是我錯過了一些基本的東西。但是這個例子非常接近我想要做的事情。WPF:更新/刷新/重新綁定ItemSource?
XAML(主窗口):
<StackPanel>
<Button Click="ButtonRemove_Click">Remove</Button>
<Button Click="ButtonAdd_Click">Add</Button>
<TabControl Name="TabFilter" ItemsSource="{Binding Tabs}">
<TabControl.ContentTemplate>
<DataTemplate>
<ScrollViewer VerticalScrollBarVisibility="Auto">
<ItemsControl ItemsSource="{Binding Path=TextList}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Text}"/>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
</StackPanel>
C#代碼:
public class TestText : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public string Text
{
get
{
return _Text;
}
set
{
_Text = value;
NotifyPropertyChanged();
}
}
private string _Text;
public TestText(string text)
{
Text = text;
}
}
public class Tabs : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public ObservableCollection<TestText> TextList { get; set; }
public Tabs(ObservableCollection<TestText> list)
{
this.TextList = list;
if (TextList.Count == 0)
TextList.Add(new TestText("Testing"));
}
}
public partial class MainWindow : Window
{
public ObservableCollection<TestText> TextList { get; set; }
public ObservableCollection<Tabs> Tabs { get; set; }
public MainWindow()
{
TextList = new ObservableCollection<TestText>();
Tabs = new ObservableCollection<Tabs>();
Tabs.Add(new Tabs(TextList));
InitializeComponent();
}
private void ButtonAdd_Click(object sender, RoutedEventArgs e)
{
Tabs.Add(new Tabs(TextList));
}
private void ButtonRemove_Click(object sender, RoutedEventArgs e)
{
Tabs.RemoveAt(0);
}
}
當我啓動程序我得到含有 「測試」 一個標籤。然後,我單擊刪除刪除選項卡。當我點擊添加一個新的標籤被創建。 這是我的問題。由於集合沒有改變,我期望或想要的是,新創建的選項卡反映集合中的內容。它應該是內容爲「測試」的選項卡,但該選項卡爲空。
我在做什麼錯了?
謝謝,但現在我覺得很愚蠢=)我試圖舉出一個例子來說明我的真實問題,然後錯過了關於所選標籤的簡單事情。但它回答了這個問題。共享列表也僅僅是一個例子,我不打算爲幾個標籤使用相同的列表。 – raptorjr 2014-10-20 14:12:09