2017-02-18 37 views
0

我有一個簡單的字符串列表,我想要顯示在列表框中,取決於按下按鈕時是否選中複選框。我在我的按鈕偵聽這樣的邏輯:列表框中的項目更新不正常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"/>

+0

您還可以爲此列表框共享相應的XAML嗎? –

+0

@DaveS我已經添加了列表框的XAML,謝謝 – James

回答

2

首先,你只能綁定屬性來控制。一個字段不能被綁定。所以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屬性。
+0

非常感謝你,非常感謝你,調查DependencyPropertys以及,似乎是一個有用的工具。另外值得一提的是,對於上面的解決方案,XAML綁定必須設置爲{{Binding PermissionList}' – James

+0

啊,你打我吧。非常感謝,但。 – James