[英]C# WPF Binding two ListBoxes on TabControl
我想有一個TabControl
,每個項目上有兩個TabItems
和一個Listbox
。 我希望兩個ListBoxes
都顯示相同的內容,所以我將兩者都綁定到相同的ObservableCollection<T>
。 首先,項目正確顯示在Listbox1
。 另外,如果我切換到ListBox2
則項目ListBox2
顯示在此處。 如果之后我回到Listbox1
,所有項目都消失了,留在ListBox2
。 我希望兩個ListBoxes
去把握和表現出同樣的ListBoxItems
不斷。 真的很感謝您的幫助!
我的XAML代碼:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="350*"/>
<RowDefinition Height="100*"/>
</Grid.RowDefinitions>
<Button Grid.Row="1" Margin="5,5,5,5" Content="Add" Click="Button_Click"/>
<TabControl Grid.Row="0">
<TabItem Header="Test1">
<ListBox ItemsSource="{Binding Components}"/>
</TabItem>
<TabItem Header="Test2">
<ListBox ItemsSource="{Binding Components}"/>
</TabItem>
</TabControl>
</Grid>
CS代碼:
private ListBoxItem _oBoxItem;
private Int32 i = 0;
private ObservableCollection<ListBoxItem> components = new ObservableCollection<ListBoxItem>();
public ObservableCollection<ListBoxItem> Components
{
get
{
if (components == null)
components = new ObservableCollection<ListBoxItem>();
return components;
}
}
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
_oBoxItem = new ListBoxItem();
_oBoxItem.Content = "Part " + i.ToString();
Components.Add(_oBoxItem);
i += 1;
}
不要將任何可視元素(例如ListBoxItem
添加到源集合。 而是添加strings
,您將獲得預期的結果:
public partial class MainWindow : Window
{
private Int32 i = 0;
private ObservableCollection<string> components = new ObservableCollection<string>();
public ObservableCollection<string> Components
{
get
{
if (components == null)
components = new ObservableCollection<string>();
return components;
}
}
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Components.Add("Part " + i.ToString());
i += 1;
}
}
視覺元素只能在視覺樹中出現一次 。 這基本上意味着您添加到第一個ListBox
的ListBoxItem
無法顯示在第二個ListBox
,反之亦然。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.