如果我没有正确大写某些内容,请原谅我。我习惯了 Java,但我正在努力遵守 C# 约定!
我在为 DataGrid 中的列动态设置数据时遇到问题。我成功添加了列动态设置列标题,但我似乎无法设置数据。结果如下:
正如记录器告诉我的那样,正在读取数据,并且 columnData 包含正确的值。(我没有使用 Debug 类,因为我在没有 Visual C# 的机器上进行测试)。
我认为我的 DataGrid 类是问题所在。此外,我认为问题在于我如何使用绑定(我还没有很好地掌握如何做到这一点)
这是我的课:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
namespace mdr
{
class MDRResult : System.Windows.Controls.DataGrid
{
private string[] headers;
private string[][] fields;
public MDRResult(string[] headers, string[][] fields) : base()
{
int columnNumber = 0;
foreach (string s in headers)
{
System.Windows.Controls.DataGridTextColumn column = new System.Windows.Controls.DataGridTextColumn();
column.Header = s;
string[] columnData = new string[fields.Length];
int rowNumber = 0;
foreach (string[] row in fields)
{
columnData[rowNumber] = row[columnNumber];
rowNumber++;
}
SurfaceWindow1.logger.WriteLine("Adding column " + s + " with data ");
foreach (string str in columnData)
SurfaceWindow1.logger.WriteLine("\t" + str);
Binding b = new Binding();
//b.Mode = BindingMode.OneTime;
b.Source = columnData;
column.Binding = b;
Columns.Add(column);
columnNumber++;
}
}
}
}
我的 XAML 与另一个类配对。这是 XAML:
<s:SurfaceWindow x:Class="mdr.SurfaceWindow1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:s="http://schemas.microsoft.com/surface/2008"
Title="SurfaceApplication1" mc:Ignorable="d" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006">
<Grid Background="#FFC7C7C7">
<s:ScatterView HorizontalAlignment="Left" Margin="248,1,0,0" Name="resultsView" VerticalAlignment="Top" Background="#FFDBDBDB" Grid.RowSpan="2">
</s:ScatterView>
<Grid HorizontalAlignment="Left" Width="270">
<Grid.RowDefinitions>
<RowDefinition Height="274*" />
<RowDefinition Height="307*" />
</Grid.RowDefinitions>
<Grid HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0, 20, 0, 0">
<s:SurfaceTextBox Height="37" HorizontalAlignment="Right" Margin="70,0,0,0" Name="fileLocation" VerticalAlignment="Center" Width="173" Background="White" Foreground="Black" BorderBrush="Black" VerticalContentAlignment="Center" Text="http://endeavour.dartmouth.edu/eva/MDR-SampleData.txt" />
<Label Content="File:" Height="10" VerticalAlignment="Center" HorizontalAlignment="Left" Margin="5,0,0,0" Name="FileLabel" Width="50" Foreground="Black" />
</Grid>
<Grid HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0, 70, 0, 0">
<s:SurfaceTextBox Height="37" HorizontalAlignment="Right" Margin="70,0,0,0" Name="cv" VerticalAlignment="Center" Width="173" Background="White" Foreground="Black" BorderBrush="Black" VerticalContentAlignment="Center" Text="10" />
<Label Content="CV:" Height="10" VerticalAlignment="Center" HorizontalAlignment="Left" Margin="5,0,0,0" Name="CVLabel" Width="50" Foreground="Black" />
</Grid>
</Grid>
<Grid Height="400" Margin="0, 120, 0, 0" HorizontalAlignment="Left" Width="270">
<s:SurfaceSlider ValueChanged="minSlider_ValueChanged" Grid.Row="1" Height="300" HorizontalAlignment="Left" Margin="62,6,0,0" Name="minSlider" VerticalAlignment="Top" Width="27" Orientation="Vertical" TickPlacement="BottomRight" IsSnapToTickEnabled="True" Minimum="1" />
<s:SurfaceSlider ValueChanged="maxSlider_ValueChanged" Height="300" HorizontalAlignment="Right" Margin="0,6,46,0" Name="maxSlider" VerticalAlignment="Top" Width="27" Grid.Row="1" IsDirectionReversed="False" Orientation="Vertical" Value="1" TickPlacement="BottomRight" IsSnapToTickEnabled="True" Minimum="1" />
<Label Content="Min: 1" Height="26" HorizontalAlignment="Left" Margin="1,133,0,0" Name="minLabel" VerticalAlignment="Top" Width="77" Foreground="Black" />
<Label Content="Max: 1" Height="26" HorizontalAlignment="Left" Margin="103,133,0,0" Name="maxLabel" VerticalAlignment="Top" Width="88" Foreground="Black" />
<Label Content="Level" Grid.Row="1" Height="17" HorizontalAlignment="Center" Margin="0,0,0,0" Name="label3" VerticalAlignment="Top" Width="60" Foreground="Black" />
</Grid>
<s:SurfaceButton Click="onMDRSubmit" Content="Run" Height="50" HorizontalAlignment="Left" Margin="40,0,0,40" Name="runButton" VerticalAlignment="Bottom" Width="172" FontSize="32" BorderBrush="Black" Grid.Row="1" Background="#FF9A9A9A" HorizontalContentAlignment="Center" />
</Grid>
</s:SurfaceWindow>
这是课程:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Surface;
using Microsoft.Surface.Presentation;
using Microsoft.Surface.Presentation.Controls;
using Microsoft.Surface.Presentation.Input;
using System.IO;
using System.Diagnostics;
using System.Data;
using System.Collections;
namespace mdr
{
/// <summary>
/// Interaction logic for SurfaceWindow1.xaml
/// </summary>
public partial class SurfaceWindow1 : SurfaceWindow
{
/// <summary>
/// Default constructor.
/// </summary>
///
MDRInterface mdr;
public static StreamWriter logger;
public static String directory;
public SurfaceWindow1()
{
InitializeComponent();
// Add handlers for window availability events
AddWindowAvailabilityHandlers();
}
/// <summary>
/// Occurs when the window is about to close.
/// </summary>
/// <param name="e"></param>
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
// Remove handlers for window availability events
RemoveWindowAvailabilityHandlers();
}
/// <summary>
/// Adds handlers for window availability events.
/// </summary>
private void AddWindowAvailabilityHandlers()
{
// Subscribe to surface window availability events
ApplicationServices.WindowInteractive += OnWindowInteractive;
ApplicationServices.WindowNoninteractive += OnWindowNoninteractive;
ApplicationServices.WindowUnavailable += OnWindowUnavailable;
}
/// <summary>
/// Removes handlers for window availability events.
/// </summary>
private void RemoveWindowAvailabilityHandlers()
{
// Unsubscribe from surface window availability events
ApplicationServices.WindowInteractive -= OnWindowInteractive;
ApplicationServices.WindowNoninteractive -= OnWindowNoninteractive;
ApplicationServices.WindowUnavailable -= OnWindowUnavailable;
}
/// <summary>
/// This is called when the user can interact with the application's window.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnWindowInteractive(object sender, EventArgs e)
{
//TODO: enable audio, animations here
}
/// <summary>
/// This is called when the user can see but not interact with the application's window.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnWindowNoninteractive(object sender, EventArgs e)
{
//TODO: Disable audio here if it is enabled
//TODO: optionally enable animations here
}
/// <summary>
/// This is called when the application's window is not visible or interactive.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnWindowUnavailable(object sender, EventArgs e)
{
//TODO: disable audio, animations here
}
private void AddMDRResult(string result)
{
DataTable table = new DataTable();
string[] rows = result.Split('\n');
foreach (string s in rows[0].Split('\t'))
{
if (s.Length == 0) continue;
logger.WriteLine("Adding header " + s);
table.Columns.Add(s);
}
bool first = true;
foreach (string s in rows)
{
if (first)
{
first = false;
continue;
}
DataRow row = table.NewRow();
int i = 0;
logger.WriteLine("Row " + table.Rows.Count + ": ");
foreach (string value in s.Split('\t'))
{
if (value.Length == 0)
continue;
logger.WriteLine("\t element " + i + ": " + value);
row[i] = value;
i++;
}
for (i = 0; i < table.Columns.Count; i++)
logger.Write(row[i] + "\t");
logger.WriteLine();
table.Rows.Add(row);
}
DataView view = table.AsDataView();
ScatterViewItem item = new ScatterViewItem();
ArrayList headersList = new ArrayList();
foreach (string s in rows[0].Split('\t'))
{
if (s.Length == 0) continue;
headersList.Add(s);
}
object[] list = headersList.ToArray();
string[] headers = new string[list.Length];
for(int i = 0; i < headers.Length; i++)
headers[i] = list[i].ToString();
ArrayList fieldList = new ArrayList();
first = true;
foreach (string s in rows)
{
if (first) {first = false; continue;}
int i = 0;
string[] row = new string[headers.Length];
foreach (string value in s.Split('\t'))
{
if (value.Length == 0)
continue;
row[i] = value;
i++;
}
fieldList.Add(row);
}
list = fieldList.ToArray();
string[][] fields = new string[list.Length][];
for(int i = 0; i < list.Length; i++)
fields[i] = (string[])(list[i]);
item.Content = new MDRResult(headers, fields);
item.Width = 500;
item.Height = 500;
resultsView.Items.Add(item);
}
private void onMDRSubmit(object sender, RoutedEventArgs args)
{
if (logger == null)
{
directory = Directory.GetCurrentDirectory();
if (directory[directory.Length - 1] == '\\')
directory = directory.Substring(0, directory.Length - 1);
String logFile = directory + "\\log\\surface.txt";
Debug.WriteLine("Creating log file: " + logFile);
if (File.Exists(logFile))
File.Delete(logFile);
Directory.CreateDirectory("\\log\\");
FileStream stream = File.Create(logFile);
logger = new StreamWriter(stream);
logger.AutoFlush = true;
}
if (mdr == null)
{
logger.WriteLine("Initializing MDR wrapper...");
mdr = new MDRInterface();
logger.WriteLine("Initialized MDR wrapper!");
}
logger.WriteLine("Starting MDR...");
string text = cv.Text;
string result = mdr.RunMDR(int.Parse(text), (int)minSlider.Value, (int)maxSlider.Value, (long)0, fileLocation.Text);
logger.WriteLine("Finished MDR! Adding to results list.");
AddMDRResult(result);
}
private void minSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
try
{
if (e.NewValue > maxSlider.Value)
minSlider.Value = e.OldValue;
minLabel.Content = "Min: " + minSlider.Value;
}
catch (NullReferenceException ex)
{
//ignore
}
}
private void maxSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
try
{
if (e.NewValue < minSlider.Value)
maxSlider.Value = e.OldValue;
maxLabel.Content = "Max: " + maxSlider.Value;
}
catch (NullReferenceException ex)
{
//ignore
}
}
}
}