[英]C# WPF Binding two ListBoxes on TabControl
I would like to have a TabControl
with two TabItems
and one Listbox
on each Item. 我想有一个
TabControl
,每个项目上有两个TabItems
和一个Listbox
。 I want both ListBoxes
to show the same content and so I bound both to the same ObservableCollection<T>
. 我希望两个
ListBoxes
都显示相同的内容,所以我将两者都绑定到相同的ObservableCollection<T>
。 At first the items are shown correctly in Listbox1
. 首先,项目正确显示在
Listbox1
。 Also if i switch to ListBox2
the Items show up here as well. 另外,如果我切换到
ListBox2
则项目ListBox2
显示在此处。 If I go back to Listbox1
afterwards all the items are gone and stay in ListBox2
. 如果之后我回到
Listbox1
,所有项目都消失了,留在ListBox2
。 I want both ListBoxes
to hold and show the same ListBoxItems
constantly. 我希望两个
ListBoxes
去把握和表现出同样的ListBoxItems
不断。 Really would appreciate some help! 真的很感谢您的帮助!
My XAML Code: 我的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 Code: 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;
}
Don't add any visual elements such as ListBoxItem
to the source collection. 不要将任何可视元素(例如
ListBoxItem
添加到源集合。 Add strings
instead and you will get the expected results: 而是添加
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;
}
}
A visual element can only appear once in the visual tree. 视觉元素只能在视觉树中出现一次 。 This basically means that the
ListBoxItem
that you add to the first ListBox
cannot be displayed in the second ListBox
and vice versa. 这基本上意味着您添加到第一个
ListBox
的ListBoxItem
无法显示在第二个ListBox
,反之亦然。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.