我有一個ListBox
我想填充兩個TextBoxes
中的數據,方法是單擊一個按鈕。我認爲問題來自我在listbox
中的不同textblock
。下面是我理想中的圖像: TheUI 我listbox
的MainWindow.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
但不確定這是問題的核心。
你爲什麼在每個按鈕點擊時設置你的datacontext? – Pikoh
因爲我想每次按下按鈕時都要添加一對Issue/Comment – Babuh
您不需要那樣做。 ObservableCollection負責在每次添加新問題時更新UI – Pikoh