Как читать XML-документ и добавлять его значения в поля со списком и текстовые поля - PullRequest
0 голосов
/ 28 января 2019

EditingModel.cs:

private ObservableCollection<string> color;
public ObservableCollection<string> Color
{
    get { return color; }
    set
    {
        color = value;
        NotifyPropertyChanged("Color");
    }
}
private ObservableCollection<string> shapes;
public ObservableCollection<string> Shapes
{
    get { return shapes; }
    set
    {
        shapes = value;
        NotifyPropertyChanged("Shapes");
    }
}
private ObservableCollection<string> size;
public ObservableCollection<string> Size
{
    get { return size; }
    set
    {
        size = value;
        NotifyPropertyChanged("Size");
    }
}

EditingsViewModel.cs:

private string selectedcolor;
public string SelectedColor
{
    get { return selectedcolor; }
    set
    {
        if (value != selectedcolor)
        {
            selectedcolor = value; NotifyPropertyChanged("SelectedColor");
        }
    }
}
private string selectedshapes;
public string SelectedShapes
{
    get { return selectedshapes; }
    set
    {
        if (value != selectedshapes)
        {
            selectedshapes = value; NotifyPropertyChanged("SelectedShapes");
        }
    }
}
private string selectedsize;
public string SelectedSize
{
    get { return selectedsize; }
    set
    {
        if (value != selectedsize)
        {
            selectedsize = value; NotifyPropertyChanged("SelectedSize");
        }
    }
}

XML-документ: (имя документа xml - EditingsValue.xml)

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE MYEDITINGS[]>
<MYEDITINGS>
  <Group name="GeneralEditings">
     <EditingsName name="COLOR" value="red"/>
     <EditingsName name="SHAPES" value="circle"/>
     <EditingsName name="SIZE" value="medium"/>
     <EditingsName name="FILE PATH" value="C:\ProgramFiles"/>
  </Group>
</MYEDITINGS>

EditingsView.xaml:

<ComboBox SelectedValue="{Binding SelectedColor,Mode=TwoWay}" Height="25" Width="150"    HorizontalContentAlignment="Right"  VerticalAlignment="Center"  ItemsSource="{Binding Color}"/ >
<ComboBox SelectedValue="{Binding SelectedShapes,Mode=TwoWay}" Height="25" Width="150"   HorizontalContentAlignment="Right"  VerticalAlignment="Center"  ItemsSource="{Binding Shapes}"/ >
<ComboBox SelectedValue="{Binding SelectedSize,Mode=TwoWay}" Height="25" Width="150"    HorizontalContentAlignment="Right"  VerticalAlignment="Center"  ItemsSource="{Binding Size}" />
<TextBox     Height="26"  Grid.Column="3"  IsReadOnly="True" TextAlignment="Right" VerticalContentAlignment="Center"  HorizontalAlignment="Left" VerticalAlignment="Center"  Width="150"   Text="{Binding ElementName=Mygroups, Path=DataContext.FolderPath,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}"  />
<Button   KeyboardNavigation.TabIndex="2"  Grid.Column="4"  Content="Browse"    Height="29" VerticalAlignment="Bottom"   MinWidth="45"   Command="{Binding  ElementName=Mygeoups,Path=DataContext.FolderCommand}" CommandParameter="{Binding}" />

В приведенном выше коде я устанавливаю значение по умолчаниюдля моего поля со списком, используя SelectedIndex , а затем позволяя пользователям выбирать свои собственные значения.Затем я записываю выбранные значения пользователя в XML-документ , как указано выше.До этого все работает нормально.Но теперь мое требование заключается в том, чтобы, если я снова открою свое приложение, я не должен получать значения по умолчанию в полях со списком и текстовых полях, вместо этого я должен прочитать документ XML и отобразить значения этого в полях со списком и текстовыми полями.

Как этого добиться с помощью MVVM (wpf).Может ли кто-нибудь помочь мне.

Заранее спасибо.

1 Ответ

0 голосов
/ 28 января 2019

Думаю, это поможет вам

Для конструктора EditingsViewModel.cs Прочитайте файл XML, присвойте значения модели

  public EditingsViewModel()
    {
           ComboBoxModel = new EditingModel();

        //Xml Path
        string xmlpath = @"D:\MyDocument.xml";

        var doc = new XmlDocument();
        doc.Load(xmlpath);
        XmlNode colorNode = doc.SelectSingleNode(@"/MYEDITINGS/Group/EditingsName[@name = 'COLOR']/@value");
        XmlNode shapesNode = doc.SelectSingleNode(@"/MYEDITINGS/Group/EditingsName[@name = 'SHAPES']/@value");
        XmlNode sizeNode = doc.SelectSingleNode(@"/MYEDITINGS/Group/EditingsName[@name = 'SIZE']/@value");
        XmlNode filePathNode = doc.SelectSingleNode(@"/MYEDITINGS/Group/EditingsName[@name = 'FILE PATH']/@value");

        //Binding the Color to the Color Property
        var observableColors = new System.Collections.ObjectModel.ObservableCollection<string>() { "red","yellow","green"};
        ComboBoxModel.Color = observableColors;

        //Binding the Shapes to the Shape Property
        var observableShapes = new System.Collections.ObjectModel.ObservableCollection<string>() { "circle", "Triangle", "Rectangle" };
        ComboBoxModel.Shapes = observableShapes;

        //Binding the Size to the Size Property
        var observableSize = new System.Collections.ObjectModel.ObservableCollection<string>() { "medium", "high", "low" };
        ComboBoxModel.Size = observableSize;

        //Assign the Color Default vlaue from the Xml Document 
        SelectedColor = colorNode.Value;

        //Assign the Shape Default vlaue from the Xml Document 
        SelectedShapes = shapesNode.Value;

        //Assign the Size  Default vlaue from the Xml Document 
        SelectedSize = sizeNode.Value;

        //Assign the FilePath Default vlaue from the Xml Document 
        FolderPath = filePathNode.Value;
    }

EditingsView.xaml - Удалить свойство выбранного индекса

   <ComboBox SelectedValue="{Binding SelectedColor,Mode=TwoWay}" Height="25" Width="150"    HorizontalContentAlignment="Right"  VerticalAlignment="Center"  ItemsSource="{Binding ComboBoxModel.Color}"/>
    <ComboBox SelectedValue="{Binding SelectedShapes,Mode=TwoWay}" Height="25" Width="150"   HorizontalContentAlignment="Right"  VerticalAlignment="Center"  ItemsSource="{Binding ComboBoxModel.Shapes}"/>
    <ComboBox SelectedValue="{Binding SelectedSize,Mode=TwoWay}" Height="25" Width="150"    HorizontalContentAlignment="Right"  VerticalAlignment="Center"  ItemsSource="{Binding ComboBoxModel.Size}" />
    <TextBox Name="Mygroups"    Height="26"  Grid.Column="3"  IsReadOnly="True" TextAlignment="Right" VerticalContentAlignment="Center"  HorizontalAlignment="Left" VerticalAlignment="Center"  Width="150"   Text="{Binding ElementName=Mygroups, Path=DataContext.FolderPath,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}"  />
    <Button   KeyboardNavigation.TabIndex="2"  Grid.Column="4"  Content="Browse"    Height="29" VerticalAlignment="Bottom"   MinWidth="45"   Command="{Binding  ElementName=Mygeoups,Path=DataContext.FolderCommand}" CommandParameter="{Binding}" />
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...