我有4个包含复选框项目的列表框项目。我试图从同一个数据集绑定它们,但似乎我做得不对。当我以这种方式绑定它们时,只有第4个列表框项目显示项目名称,其余的只显示空白复选框。
另外我想知道我是否以这种方式绑定复选框,以后如何访问所选数据库中的ID值(因为我只设置了内容而我没有设置selectedValuePath或类似的东西)?
以下是我的代码:
XML
<ListBox x:Name="listBox1" ItemsSource="{Binding}" HorizontalAlignment="Left" Height="52" Margin="141,264,0,0" VerticalAlignment="Top" Width="307" SelectionMode="Multiple">
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox x:Name="checkBox1" Content="{Binding NacinGrejanja}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Label Content="Tip Objekta:" HorizontalAlignment="Left" Margin="30,323,0,0" VerticalAlignment="Top"/>
<ListBox x:Name="listBox2" ItemsSource="{Binding}" HorizontalAlignment="Left" Height="26" Margin="141,323,0,0" VerticalAlignment="Top" Width="307">
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox x:Name="checkBox1" Content="{Binding TipObjekta}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Label Content="Opis Objekta:" HorizontalAlignment="Left" Margin="31,366,0,0" VerticalAlignment="Top"/>
<ListBox x:Name="listBox3" ItemsSource ="{Binding}" HorizontalAlignment="Left" Height="52" Margin="142,366,0,0" VerticalAlignment="Top" Width="307">
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox x:Name="checkBox3" Content="{Binding OpisObjekta}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Label Content="Dodatno:" HorizontalAlignment="Left" Margin="31,437,0,0" VerticalAlignment="Top"/>
<ListBox x:Name="listBox4" ItemsSource ="{Binding}" HorizontalAlignment="Left" Height="52" Margin="142,437,0,0" VerticalAlignment="Top" Width="307">
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox x:Name="checkBox4" Content="{Binding Dodatno}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
C#
private void Window_Loaded_1(object sender, RoutedEventArgs e)
{
Dataset1 ds= new Dataset1 ();
GrejanjeTableAdapter gta = new GrejanjeTableAdapter();
TipObjektaTableAdapter tta = new TipObjektaTableAdapter();
OpisObjektaTableAdapter ota = new OpisObjektaTableAdapter();
DodatnoTableAdapter dta = new DodatnoTableAdapter();
gta.Fill(ds.Grejanje);
tta.Fill(ds.TipObjekta);
ota.Fill(ds.OpisObjekta);
dta.Fill(ds.Dodatno);
this.DataContext = ds.Grejanje;
this.DataContext = ds.TipObjekta;
this.DataContext = ds.OpisObjekta;
this.DataContext = ds.Dodatno;
}
答案 0 :(得分:1)
而不是:
this.DataContext = ds.Grejanje;
this.DataContext = ds.TipObjekta;
this.DataContext = ds.OpisObjekta;
this.DataContext = ds.Dodatno;
你应该试试这个:
listbox1.ItemsSource = ds.Grejanje;
listbox2.ItemsSource = ds.TipObjekta;
listbox3.ItemsSource = ds.OpisObjekta;
listbox4.ItemsSource = ds.Dodatno;
您不需要ItemsSource="{Binding}"
项目上的ListBox
。
要获取所选项,您需要将IsChecked
项的CheckBox
属性绑定到IsChecked
布尔属性,如下所示:
<CheckBox x:Name="checkBox1" IsChecked={Binding IsSelected} Content="{Binding NacinGrejanja}"/>
如果NacinGrejanja
不包含IsChecked
属性,那么您应该将其包含在包含它的类中。
NacinGrejanja
的ID应该包含在实例中,因此您在获取所选项目的ID时不会有任何问题。如果不是,那么再用一个类来包装。