C#WPF在TabControl上绑定两个ListBox

时间:2018-05-04 08:48:05

标签: c# wpf binding listbox listboxitem

我希望TabControl在每个项目上有两个TabItems和一个Listbox。我希望ListBoxes显示相同的内容,因此我将两者绑定到同一个ObservableCollection<T>。首先,项目在Listbox1中正确显示。此外,如果我切换到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;
        }

1 个答案:

答案 0 :(得分:0)

不要将任何视觉元素(例如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;
    }
}

视觉元素只能在可视化树中出现一次。这基本上意味着您添加到第一个ListBoxItem的{​​{1}}无法在第二个ListBox中显示,反之亦然。