#c# #wpf #dictionary #xaml #user-interface
#c# #wpf #словарь #xaml #пользовательский интерфейс
Вопрос:
В настоящее время я пытаюсь загрузить отдельное окно, которое появляется, когда пользователь щелкает определенное местоположение на карте. Я хочу, чтобы в окне отображались данные бизнес-объекта, которые хранятся в словаре на C #.
По какой-то причине я не могу заставить окно отображать что-либо, оно просто остается пустым.
Я определяю все столбцы / строки в своем собственном коде и заполняю таблицу данных, а не в конструкторе.
Вот мой код для некоторых подсказок:
XAML: BusinessDataWindow.xaml
<Window x:Class="BusinessLocator.BusinessDataTable"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:DigoohBusinessLocator"
mc:Ignorable="d"
Title="BusinessDataTable" Height="450" Width="800">
<Grid>
<DataGrid x:Name="BusinessDataGrid" ItemsSource="{Binding Source = BusinessDataGridView}" AutoGenerateColumns="True" HorizontalAlignment="Left" Height="412" VerticalAlignment="Top" Width="785">
</DataGrid>
</Grid>
И вот код, лежащий в основе XAML (пожалуйста, извините за некоторые строки с комментариями):
BusinessDataWindow.xaml.cs
/// <summary>
/// Interaction logic for BusinessDataTable.xaml
/// </summary>
public partial class BusinessDataWindow : Window
{
//System.Windows.Controls.DataGrid BusinessDataGrid;
//DataGridView BusinessDataGridView;
DataTable BusinessDataTable;
Dictionary<string, Business> BusinessLocationDictionary;
public BusinessDataWindow(Dictionary<string, Business> BusinessLocationDictionary)
{
//this.BusinessDataGrid = null;
this.BusinessLocationDictionary = BusinessLocationDictionary;
this.initializeDataGridView();
//this.InitializeComponent();
//this.Loaded = new RoutedEventHandler(DataGrid_Loaded);
}
public DataGridView BusinessDataGridView
{
get;
set;
}
private void initializeDataGridView()
{
this.BusinessDataGridView = new DataGridView();
this.BusinessDataTable = new DataTable();
int businessCount = this.BusinessLocationDictionary.Values.Count;
string nameColumn = "Name";
string placeIdColumn = "Place ID";
string addressColumn = "Address";
string phoneNumberColumn = "Phone Number";
string OwnerColumn = "Owner";
// Add the columns to the DataGridView.
this.BusinessDataTable.Columns.Add(new DataColumn(nameColumn, typeof(string)));
this.BusinessDataTable.Columns.Add(new DataColumn(placeIdColumn, typeof(string)));
this.BusinessDataTable.Columns.Add(new DataColumn(addressColumn, typeof(string)));
this.BusinessDataTable.Columns.Add(new DataColumn(phoneNumberColumn, typeof(string)));
this.BusinessDataTable.Columns.Add(new DataColumn(OwnerColumn, typeof(string)));
List<Business> BusinessList = this.BusinessLocationDictionary.Values.ToList<Business>();
// Add the rows to the DataGridView.
for (int rowIndex = 0; rowIndex < businessCount; rowIndex )
{
this.BusinessDataTable.Rows.Add(BusinessList.ElementAt(rowIndex));
this.populateDataGridCells();
}
}
private void populateDataGridCells()
{
int businessCount = this.BusinessLocationDictionary.Values.Count;
List<Business> BusinessList = this.BusinessLocationDictionary.Values.ToList<Business>();
// Populate the rows to the DataGridView.
for (int rowIndex = 0; rowIndex < businessCount; rowIndex )
{
DataGridViewRow row = this.BusinessDataGridView.Rows[rowIndex];
row.Cells[rowIndex].Value = BusinessList.ElementAt(rowIndex);
}
this.BusinessDataGridView.DataSource = this.BusinessDataTable;
}
}
Комментарии:
1. Надеюсь, вы не прокомментировали InitializeComponent() 😀
2. Должен ли я сам реализовать этот метод для отображения чего-либо?
3. Также в строке: строка DataGridViewRow = this. BusinessDataGridView.Rows[RowIndex]; Я получаю систему. Исключение ArgumentOutOfRangeException. Индекс был вне диапазона.
4. Когда вы добавляете> window, заглушка имеет initializecomponent в ctor. Эта линия поворотов создает ваш пользовательский интерфейс. Если вам нужен какой-либо вид, очень важно иметь его в вашем конструкторе.
5. Вы используете rowindex для индексации как x, так и y. Строк и столбцов. Это кажется маловероятным, чтобы быть правильным. Я не понимаю, что ты пытаешься сделать. У вас есть таблица данных и словарь, которые кажутся несвязанными. Я не понимаю, почему у тебя есть и то, и другое. Чтобы привязать таблицу данных, вы должны привязать ее представление по умолчанию к itemssource сетки данных. Datagrid в wpf.
Ответ №1:
Вы прокомментировали это.InitializeComponent(); в вашем конструкторе. Без вызова этого метода никакие элементы управления не будут сгенерированы.
Итак, это должно выглядеть так:
public BusinessDataWindow(Dictionary<string, Business> BusinessLocationDictionary)
{
//this.BusinessDataGrid = null;
this.BusinessLocationDictionary = BusinessLocationDictionary;
this.initializeDataGridView();
this.InitializeComponent();
//this.Loaded = new RoutedEventHandler(DataGrid_Loaded);
}
Что касается вашей ошибки в строке DataGridViewRow row = this.BusinessDataGridView.Rows[RowIndex]; это потому, что в вашем BusinessDataGridView нет строк.