[英]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.