2014-02-05 7 views
0

Я пытаюсь написать метод, который принимает файл xml.config из некоторого места в файловой системе через кнопку «Загрузить», анализирует его и после этого работает с определенными строками в типе атрибутов элементов и mapTo, получив подстроки из этих атрибутов. Проблема в том, что вместо того, чтобы получать строки в таблице, я получаю несколько строк. Кто-нибудь знает, в чем проблема?Передача строковых значений из списка в datagrid

Кнопка и вызов метода выглядит следующим образом:

private void button1_Click(object sender, RoutedEventArgs e) 
     { 
      OpenFileDialog fDialog = new OpenFileDialog(); 

      fDialog.Title = "Open XML file"; 
      fDialog.Filter = "XML files|*.config"; 
      fDialog.InitialDirectory = @"C:\"; 

      bool? control = fDialog.ShowDialog(); 
      if (control.Value) 
      { 
       var filePath = fDialog.FileName; 
       ReadAdvancedConfigFile(filePath); 
      } 

     } 

метод, который получает значения из XML-файла, взять подстроку для каждого типа атрибута и МАПТО, поместите их в две отдельные списки и попытаться написать содержание списка в сетке данных выглядит следующим образом:

private void ReadAdvancedConfigFile(string path) 
{ 
    XElement root = null; 
    root = XElement.Load(new XmlTextReader(path)); 

    if (root != null) 
    { 
     XNamespace ns = "http://schemas.microsoft.com/practices/2010/unity"; 
     var registers = root.Element(ns + "unity").Element(ns + "container").Descendants(ns + "register"); 

     if (registers.Count() > 0) 
      { 
      var tipList = registers.Select(x => x.Attribute("type").Value); 
      var mapToList = registers.Select(x => x.Attribute("mapTo").Value); 
      List<string> listresult = new List<string>(); 
      List<string> listresultm = new List<string>(); 

       foreach (string tpl in tipList) 
       { 
        int end = tpl.IndexOf(','); 
        int start = tpl.LastIndexOf('.', (end == -1 ? tpl.Length - 1 : end)) + 1; 
        string result = tpl.Substring(start, (end == -1 ? tpl.Length : end) - start); 
        listresult.Add(result); 
       } 
       foreach (string mpl in mapToList) 
       { 
        int endm = mpl.IndexOf(','); 
        int startm = mpl.LastIndexOf('.', (endm == -1 ? mpl.Length - 1 : endm)) + 1; 
        string resultm = mpl.Substring(startm, (endm == -1 ? mpl.Length : endm) - startm); 
        listresultm.Add(resultm); 
       } 

       int maxLenList = Math.Max(listresult.Count, listresultm.Count); 
       for (int i = 0; i < maxLenList; i++) 
       { 
        if (i < listresult.Count && i < listresultm.Count) 
        { 
         _obsCollection.Add(new Tuple<string, string>(listresult[i], listresultm[i])); 
        } 
        else if (i >= listresult.Count) 
        { 
         _obsCollection.Add(new Tuple<string, string>(string.Empty, listresultm[i])); 
        } 
        else if (i >= listresultm.Count) 
        { 
         _obsCollection.Add(new Tuple<string, string>(listresultm[i], string.Empty)); 
        } 
       } 
      tabela.ItemsSource = _obsCollection; 
     } 
    } 
} 

Содержание XML.config файла выглядит следующим образом:

<?xml version="1.0" encoding="utf-8" ?> 
<configuration> 

    <configSections> 
     <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/> 
    </configSections> 

    <unity xmlns="http://schemas.microsoft.com/practices/2010/unity"> 

     <container name="container"> 

      <register name="configService" type="Web.Common.Interfaces.IConfigService, Web.Common" 
         mapTo="Web.Common.Services.ConfigServiceImpl, Web.Common"> 
       <lifetime type="singleton" /> 
       <constructor> 
        <param name="res" value="Resources.ClientStrings"> </param> 
        <param name="configFile" value="webclient.config"> </param> 
       </constructor> 
       <!--<property name="LocalisationService" dependencyName="LocalisationService" />--> 
       <!--This is a property injection from the language plugin --> 
      </register> 

      <register name="scaleCoefConfigService" type="Web.WebClient.Services.IScaleCoefConfigService, Web.WebClient.TDMSWebApp" 
         mapTo="Web.WebClient.Services.Implementations.ScaleCoefConfigServiceImpl, Web.WebClient.TDMSWebApp"> 
       <lifetime type="singleton" /> 
       <constructor> 
        <param name="configService"> 
         <dependency name="configService"/> 
        </param> 
       </constructor> 
      </register> 

      <register name="sessionService" type="Web.Common.Interfaces.ISessionService, Web.Common" 
         mapTo="Web.Common.Services.SessionServiceImpl, Web.Common"> 
       <lifetime type="singleton" /> 
      </register> 

      <register name="licenseManagerService" type="Web.Common.Interfaces.ILicenseManagementService, Web.Common" 
         mapTo="Web.Common.Services.LicenseManagementServiceImpl, Web.Common"> 
       <lifetime type="singleton" /> 
      </register> 
     </container> 
    </unity> 
</configuration> 

И вот как я создал Tuple для пары строк. В этом классе также определение метода ReadAdvancedConfigFile и кнопку Load, конечно:

public partial class CreateAreaDialogWindow : System.Windows.Window 
     { 
      ObservableCollection<Tuple<string, string>> _obsCollection = new ObservableCollection<Tuple<string, string>>(); 

      public CreateAreaDialogWindow() 
      { 
       InitializeComponent(); 
      } 
} 

XAML код для DataGrid это:

<DataGrid AutoGenerateColumns="False" Height="146" HorizontalAlignment="Left" Margin="34,275,0,0" Name="tabela" VerticalAlignment="Top" Width="384" SelectionChanged="tabela_SelectionChanged" /> 

Надеется, что я не получил это слишком сложно.

+0

Вы можете добавить скриншот с проблемой. Мне не все понятно. –

+0

@PatrickHofman снимок экрана с datagrid с линиями? Или что-то другое? –

+0

Да, вот что я имел в виду. –

ответ

1

Вы установили AutoGenerateColumns="False", и вы не указали колонки.

Попробуйте это, и она работает:

<DataGrid AutoGenerateColumns="True" /> 

Или увидеть MSDN о том, как создавать столбцы.

+0

Я люблю тебя! : D Это сработало! :) Большое спасибо. Я знаю, что это было глупо, но я все еще учился, и это может быть сложно :) –

+0

И спасибо за ссылку. Мне нужно это :) Причина следующая Я должен исследовать, как добавить флажки в этот столбец для каждого значения :) –

Смежные вопросы