2016-04-25 79 views
0

我有一個ListBox我想填充兩個TextBoxes中的數據,方法是單擊一個按鈕。我認爲問題來自我在listbox中的不同textblock。下面是我理想中的圖像: TheUIlistboxMainWindow.xaml使用DataBinding從兩個文本框中填充列表框

<ListBox x:Name="listBox" 
       ItemsSource="{Binding Issues}" Grid.Column="1" HorizontalAlignment="Left" Height="366" VerticalAlignment="Top" Width="453" Margin="0,0,-1,0"> 
     <StackPanel Margin="3"> 
      <DockPanel > 
       <TextBlock FontWeight="Bold" Text="Issue:" 
       DockPanel.Dock="Left" 
       Margin="5,0,10,0"/> 
       <TextBlock Text=" " /> 
       <TextBlock Text="{Binding Issue}" Foreground="Green" FontWeight="Bold" /> 
      </DockPanel> 
      <DockPanel > 
       <TextBlock FontWeight="Bold" Text="Comment:" Foreground ="DarkOrange" 
       DockPanel.Dock="Left" 
       Margin="5,0,5,0"/> 
       <TextBlock Text="{Binding Comment}" /> 

      </DockPanel> 
     </StackPanel> 
    </ListBox> 

MainWindow.xaml.cs

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


    public sealed class ViewModel 
    { 
     public ObservableCollection<Issue> Issues { get; private set; } 

     public ViewModel() 
     { 
      Issues = new ObservableCollection<Issue>(); 
     } 
    } 

    private void addIssue_Click(object sender, RoutedEventArgs e) 
    { 
     var vm = new ViewModel(); 
     vm.Issues.Add(new Issue { Name = "Jon Skeet", Comment = "lolilol" }); 
     DataContext = vm; 
     InitializeComponent(); 
    } 
} 

Issue.cs

public sealed class Issue 
{ 

    public string Name { get; set; } 
    public string Comment { get; set; } 
} 

我按照這個教程,但我不不想實施數據庫: Tuto 我也嘗試使用這個stackoverflow question 我的錯誤是'System.InvalidOperationException'The Items collection must be empty to use ItemsSource 但不確定這是問題的核心。

+0

你爲什麼在每個按鈕點擊時設置你的datacontext? – Pikoh

+0

因爲我想每次按下按鈕時都要添加一對Issue/Comment – Babuh

+0

您不需要那樣做。 ObservableCollection負責在每次添加新問題時更新UI – Pikoh

回答

0

消除任何您插入<ListBox> and </ListBox>之間,因爲它是作爲Items集合的一部分處理。

取而代之的是將該內容在<ListBox.ItemTemplate>...</ListBox.ItemTemplate>之間移動。

+0

它完美的作品!非常感謝 ! – Babuh

0

您無需每次更新ContextInitializeComponent,至少您的情況。

public partial class MainWindow : Window 
{ 
    ViewModel vm = new ViewModel(); 
    public MainWindow() 
    { 
     InitializeComponent(); 
     DataContext = vm; 
    } 


    public sealed class ViewModel 
    { 
     public ObservableCollection<Issue> Issues { get; private set; } 

     public ViewModel() 
     { 
      Issues = new ObservableCollection<Issue>(); 
     } 
    } 

    private void addIssue_Click(object sender, RoutedEventArgs e) 
    {  
     vm.Issues.Add(new Issue { Name = "Jon Skeet", Comment = "lolilol" });  
    } 
} 
+0

我沒有錯誤,但這並沒有增加任何東西到'Listbox':/ 編輯:好吧,我的壞我有同樣的錯誤,這不會再打開窗口 – Babuh