簡體   English   中英

如何在兩個同步框中動態顯示ListBoxes

[英]How to dynamically show ListBoxes in two synchronized boxes

我目前正在將數據從一個列表框傳輸到另一個列表框。 使用WPF,我可以:

            <Grid>
                <ListBox Margin="10,29,194,301" Name="LeftListBox"/>
                <ListBox Margin="0,29,16,301" Name="RightListBox" HorizontalAlignment="Right" Width="173" />
                <Button Name="AddButton" Height="23" Margin="34,135,227,0" VerticalAlignment="Top"
                Click="AddButton_Click">Add &gt;&gt;</Button>
                <Button Name="RemoveButton" Margin="227,135,34,264" 
                Click="RemoveButton_Click">&lt;&lt; Remove</Button>
            </Grid>

對於我的C#代碼,我創建了兩個方法,它們使用字符串數組和右數組來加載左框的元素。 現在,我的問題是我希望將左框的元素放置在右框列表的最后一個元素之后的右框中。 因此,當我單擊添加時,它應該執行以下方法:

    private void AddButton_Click(object sender, RoutedEventArgs e)
    {
        // Find the right item and it's value and index
        currentItemText = LeftListBox.SelectedValue.ToString();
        currentItemIndex = LeftListBox.SelectedIndex;

        ObservableCollection<string> oList;
        oList = new System.Collections.ObjectModel.ObservableCollection<string>(toRemoveList);
        RightListBox.DataContext = oList;

        Binding binding = new Binding();
        RightListBox.SetBinding(ListBox.ItemsSourceProperty, binding);

        (RightListBox.ItemsSource as ObservableCollection<string>).Add(currentItemText);
        if (toAddList != null)
        {
            toAddList.RemoveAt(currentItemIndex);
        }

        // Refresh data binding
                   ApplyDataBinding();
    }

但是問題是,當我從左側框中選擇一個項目,然后單擊添加時,它將新項目添加到右側框中,但是當我添加第二個項目時,它將替換在第一步中添加的最后一個項目。

之后,第二個問題是,如何實現RemoveButton_Click? 和以前的方法一樣嗎?

您無需為此做太多的代碼。 請遵循以下給出的步驟,以獲取更可靠且可維護的方法。

  1. 創建兩個與左側和右側ListBox相對應的Observablecollection
  2. Observablecollection綁定到ListBox
  3. Add按鈕上單擊,從分配給左側列表框的可觀察集合中刪除該item ,並將其添加到綁定到右網格的可觀察集合中。

您無需顯式更新綁定。 可觀察的集合會自動通知集合更改。

在代碼中-

public ObservableCollection<ApplicationFormats> Formats { get; set; }

Xaml-

<ListBox Name="LeftListBox" ItemsSource="{Binding Formats}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Name}"/>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM