簡體   English   中英

列表框中的項目不定期更新WPF

[英]Items in a listbox updating erratically WPF

我有一個簡單的字符串列表,希望根據在按下按鈕時是否選中復選框來在列表框中顯示這些字符串。 我的按鈕監聽器中有以下邏輯:

private void fileSavePerms_Click(object sender, RoutedEventArgs e)
{
    foreach (CheckBox checkbox in checkboxList)
    {
        if (checkbox.IsChecked == true && !permissionList.Contains(checkbox.Name))
        {
            permissionList.Add(checkbox.Name);
        }

        else if (checkbox.IsChecked == false && permissionList.Contains(checkbox.Name))
        {
            permissionList.Remove(checkbox.Name);
        }
    }
    permListBox.ItemsSource = permissionList;
}

據我所知,這是您可以在單擊按鈕時進行非常簡單的數據綁定的方法。 但是,列表框是第一次按預期的方式更新,但隨后會更新錯誤的列表內容(我嘗試使用該列表框來填充列表)。 我看不到輸出可識別的模式。

此外,過一會兒(單擊幾下按鈕),我將捕獲一個異常,說“ an ItemsControl is inconsistent with its items source ”。

我是錯誤地設置了綁定還是在錯誤的時間分配了ItemsControl

更新:

列表框的XAML:

<ListBox x:Name="permListBox" ItemsSource="{Binding permissionList}" HorizontalAlignment="Left" Height="36" Margin="28,512,0,0" VerticalAlignment="Top" Width="442"/>

首先,您只能將屬性綁定到控件。 字段不能綁定。 因此, permissionList必須是您設置為Window.DataContext屬性的DataContext對象的屬性。

如果設置正確,則可以每次創建一個新的List<string> ,然后將其分配給綁定到控件的屬性。 您不必將其分配給控件的ItemsSource屬性

假設您的窗口的數據上下文設置為窗口本身。

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        this.DataContext = this;
    }

    public List<string> PermissionList
    {
        get { return (List<string>)GetValue(PermissionListProperty); }
        set { SetValue(PermissionListProperty, value); }
    }

    public static readonly DependencyProperty PermissionListProperty =
        DependencyProperty.Register(
            "PermissionList",
            typeof(List<string>),
            typeof(MainWindow),
            new PropertyMetadata(new List<string>())
        );

    private void fileSavePerms_Click(object sender, RoutedEventArgs e)
    {
        // You create a new instance of List<string>
        var newPermissionList = new List<string>();

        // your foreach statement that fills this newPermissionList
        // ...

        // At the end you simply replace the property value with this new list
        PermissionList = newPermissionList;
    }
}

在XAML文件中,您將具有以下內容:

<ListBox 
    ItemsSource="{Binding PermissionList}"
    HorizontalAlignment="Left"
    VerticalAlignment="Top"
    Margin="28,512,0,0"
    Height="36"
    Width="442"/>

當然,該解決方案可以改進。

  • 您可以使用System.Collections.ObjectModel.ObservableCollection<string>類型,這樣您就不必每次都不再創建List<string>的新實例,而是可以清除列表並將新項添加到foreach語句中。
  • 您可以使用具有此權限列表的ViewModel類(例如MainViewModel ),還可以實現INotifyPropertyChanged接口,然后將此類的實例設置為WPF窗口的DataContext屬性。

暫無
暫無

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

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