Code:
<Window x:Class="WPF_CheckListBox.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">
<Window.Resources>
<DataTemplate x:Key="CheckListBox">
<StackPanel Orientation="Horizontal">
<CheckBox Name="ChkList" Content="{Binding Path=ProdName}"></CheckBox>
</StackPanel>
</DataTemplate>
</Window.Resources>
<Grid>
<ListBox Height="181" HorizontalAlignment="Left" Margin="179,12,0,0" Name="listBox1" VerticalAlignment="Top" Width="159" ItemTemplate="{StaticResource CheckListBox}" ItemsSource="{Binding}" />
<Button x:Name="btnOk" Height="23" Width="80" Margin="219,210,204,78" Content="OK" Click="btnOk_Click"></Button>
</Grid>
</Window>
Code:
namespace WPF_CheckListBox
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
try
{
listBox1.DataContext = GetTableName(); // Bind Tables Name in ListBox
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
private void btnOk_Click(object sender, RoutedEventArgs e)
{
try
{
GetSelectedCheckObjItem(); // Get a selected checkbox items
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
#region Methods
/// <summary>
/// Get table name from nortwind databases
/// </summary>
/// <returns>DataTable</returns>
private DataTable GetTableName()
{
try
{
SqlConnection SqlCon = new SqlConnection();
SqlCon.ConnectionString = @"Data Source=DANH-PC;Initial Catalog=shradhabookstores;Persist Security Info=True;User ID=sa;Password=123456";
SqlCon.Open();
SqlCommand SqlComm = new SqlCommand("SELECT [ProdName] FROM Products");
SqlComm.Connection = SqlCon;
DataTable Table = new DataTable();
SqlDataAdapter SqlDa = new SqlDataAdapter();
SqlDa.SelectCommand = SqlComm;
SqlDa.Fill(Table);
return Table;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
/// <summary>
/// Find Child Control from ContentPresenter
/// </summary>
/// <typeparam name="ChildControl"></typeparam>
/// <param name="DependencyObj"></param>
/// <returns></returns>
private ChildControl FindVisualChild<ChildControl>(DependencyObject DependencyObj)
where ChildControl : DependencyObject
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(DependencyObj); i++)
{
DependencyObject Child = VisualTreeHelper.GetChild(DependencyObj, i);
if (Child != null && Child is ChildControl)
{
return (ChildControl)Child;
}
else
{
ChildControl ChildOfChild = FindVisualChild<ChildControl>(Child);
if (ChildOfChild != null)
{
return ChildOfChild;
}
}
}
return null;
}
/// <summary>
/// Get a selected checkbox items
/// </summary>
private void GetSelectedCheckObjItem()
{
StringBuilder sb = new StringBuilder();
try
{
for (int i = 0; i < listBox1.Items.Count; i++)
{
// Get a all list items from listbox
ListBoxItem ListBoxItemObj = (ListBoxItem)listBox1.ItemContainerGenerator.ContainerFromItem(listBox1.Items[i]);
// find a ContentPresenter of that list item.. [Call FindVisualChild Method]
ContentPresenter ContentPresenterObj = FindVisualChild<ContentPresenter>(ListBoxItemObj);
// call FindName on the DataTemplate of that ContentPresenter
DataTemplate DataTemplateObj = ContentPresenterObj.ContentTemplate;
CheckBox Chk = (CheckBox)DataTemplateObj.FindName("ChkList", ContentPresenterObj);
// get a selected checkbox items.
if (Chk.IsChecked == true)
{
// MessageBox.Show(Chk.Content.ToString().Trim());
sb.Append(Chk.Content.ToString() + ",");
}
}
Console.WriteLine(sb);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
#endregion
}
}
khi chay nếu listbox có thanh trượt (nhiều dòng) thì sẽ xảy ra lỗi
A first chance exception of type 'System.ArgumentNullException' occurred in PresentationCore.dll
A first chance exception of type 'System.Exception' occurred in WPF_CheckListBox.exe
Ngoài cách ở trên có cách nào khác để làm ví dụ trên giúp em với