WPF Bind ListBoxItem to DataGrid
本文关键字:DataGrid to ListBoxItem Bind WPF | 更新日期: 2023-09-27 17:52:13
我需要以以下方式绑定ListBoxItem和DataGrid:用户双击ListBoxItem并执行sql查询,检索到的数据显示在DataGrid上。我有:
<DataGrid x:Name="GridStatistics" Margin="0,144,0,0" />
<ListBox x:Name="LstStat" HorizontalAlignment="Left" Height="129" Margin="10,10,0,0"
VerticalAlignment="Top" Width="330" FontSize="16"
ItemsSource="{Binding StatisticsQueries}" Cursor="Arrow" PreviewMouseRightButtonDown="LstStat_PreviewMouseRightButtonDown" PreviewMouseRightButtonUp="LstStat_PreviewMouseRightButtonUp" MouseDoubleClick="LstStat_MouseDoubleClick">
<ListBox.ItemTemplate>
<DataTemplate>
<Label Content="{Binding Path=Name}" FontWeight="Medium" FontSize="18" FontFamily="HelveticaNeueCyr"/>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ContextMenu>
<ContextMenu>
<MenuItem Header="Show" Click="MenuItem_OnClick" />
</ContextMenu>
</ListBox.ContextMenu>
</ListBox>
和我的c#代码:
public ObservableCollection<Query> StatisticsQueries {get{...}}
private void LstStat_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
if (LstStat.SelectedIndex < 0) return;
var item = LstStat.SelectedItem as Query;
using (var connection = new MySqlConnection(DatabaseModel.ConnectionString))
{
connection.Open();
if (item != null)
using (var cmd = new MySqlCommand(item.Text, connection))
{
var dt = new DataTable();
var adapter = new MySqlDataAdapter(cmd);
adapter.Fill(dt);
GridStatistics.DataContext = dt;
}
connection.Close();
}
e.Handled = true;
}
类Query public class Query : INotifyPropertyChanged
具有代码中使用的所有属性,因此没有错误。
虽然数据被正确检索,但DataGrid根本没有反应。可能在绑定或设置DataContext时出现了一些错误。
你能帮我正确绑定ListBoxItem DoubleMouseClick和DataGrid DataContext吗?我应该为此创建一个单独的类吗?
Try it :
using (var cmd = new MySqlCommand(item.Text, connection))
{
.
.
GridStatistics.ItemsSource = dt.DefaultView;
}
解决了这个问题:
1)添加:
public DataTable StatisticsDataTable { get; private set; }
2)然后在这里改变我的方法部分:
StatisticsDataTable = dt;
GridStatistics.DataContext = StatisticsDataTable;
3) XAML绑定变成如下:
ItemsSource="{Binding}"
感谢所有试图帮助我的人!