0

В меня есть такое окно,я открываю файл .xml и дессерилизую данные из файла записываю
в textboxs,но товаров может быть много текстбоксов может не хватить и их нужно добавить если они не поместились на окно тогда сделать текстбоксов прокрутку вниз.

введите сюда описание изображения

Код окна

<Window x:Class="PriceCreator.MainWindow"
        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:PriceCreator"
        mc:Ignorable="d"
        Title="Price Creator for => rozetka.com.ua" Height="1000" Width="1200" Name="window">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="52"/>
            <RowDefinition Height="1*"/>
            <RowDefinition Height="2*"/>
            <RowDefinition Height="32"/>
        </Grid.RowDefinitions>

        <Grid Grid.Row="0" Grid.Column="0" Margin="10">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="140"/>
                <ColumnDefinition Width="1*"/>

            </Grid.ColumnDefinitions>
            <Button x:Name="btnLoadSave" Grid.Column="0" FontSize="15" Margin="2" Content="Load/Save" Click="BtnLoadSave_Click"/>
            <Label Name="lbPath" Grid.Column="1" FontSize="16" Content="Name file"></Label>
        </Grid>
        <GroupBox Grid.Row="1" x:Name="grbMandatoryInformation" Header="Mandatory information" FontSize="16" Margin="10 0 10 10" Background="#DFE5EB" Foreground="#005565" BorderBrush="#005565">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="105"/>
                    <ColumnDefinition Width="415*"/>
                    <ColumnDefinition Width="426*"/>
                    <ColumnDefinition Width="14*"/>
                </Grid.ColumnDefinitions>
                <Grid.RowDefinitions>
                    <RowDefinition Height="31"/>
                    <RowDefinition Height="31"/>
                    <RowDefinition Height="31"/>
                    <RowDefinition Height="34"/>
                    <RowDefinition Height="31"/>
                </Grid.RowDefinitions>
                <Label Grid.Row="0" Grid.Column="0" Content="Имя"/>
                <TextBox x:Name="tbName" Grid.Row="0" Grid.Column="1" Margin="2" Grid.ColumnSpan="2"/>

                <Label  Grid.Row="1" Grid.Column="0" Content="Компания"/>
                <TextBox  Name="tbCompany" Grid.Row="1" Grid.Column="1" Margin="2" Grid.ColumnSpan="2"/>

                <Label Grid.Row="2" Grid.Column="0" Content="Категории"/>
                <ComboBox   Name="CbCategory" Grid.Row="2" Grid.Column="1" Margin="2" Grid.ColumnSpan="2" SelectionChanged="CbCategory_SelectedIndexChanged"/>

                <Label Grid.Row="3" Grid.Column="0" Content="Адрес сайта" Margin="2"/>
                <TextBox Name="tbUrl" Grid.Row="3" Grid.ColumnSpan="2" Margin="2"  Grid.Column="1" />


                <Button Grid.Row="4" Grid.Column="0"  FontSize="15" Margin="2" Content="+" Click="btnAddCotedory"/>
                <TextBox Name="tbcotegory"  Grid.Row="4" Grid.Column="1" Margin="2" Grid.ColumnSpan="2" KeyDown="AddCotedory_KeyDown"/>

            </Grid>

        </GroupBox>
        <GroupBox Grid.Row="2" x:Name="grbProducts" Header="Products" FontSize="16" Margin="10 0 10 10" Background="#DFE5EB" Foreground="#005565" BorderBrush="#005565">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="28"/>
                    <ColumnDefinition Width="345*"/>
                    <ColumnDefinition Width="297*"/>
                    <ColumnDefinition Width="290*"/>
                </Grid.ColumnDefinitions>
                <Grid.RowDefinitions>
                    <RowDefinition Height="31"/>
                    <RowDefinition Height="30"/>
                    <RowDefinition Height="31"/>
                    <RowDefinition Height="30"/>
                    <RowDefinition Height="31"/>
                </Grid.RowDefinitions>

                <CheckBox x:Name="cb1" Grid.Row="0" Grid.Column="0"  Margin="5" />
                <TextBox Name="tb1" Grid.Row="0" Grid.Column="1" Margin="2" Grid.ColumnSpan="3" FontSize="14"/>

                <CheckBox x:Name="cb2" Grid.Row="1" Grid.Column="0" Margin="5"/>
                <TextBox Name="tb2" Grid.Row="1" Grid.Column="1" Margin="2" Grid.ColumnSpan="3" FontSize="14"/>

                <CheckBox x:Name="cb3" Grid.Row="2" Grid.Column="0" Margin="5"/>
                <TextBox  Name="tb3" Grid.Row="2" Grid.Column="1" Margin="2" Grid.ColumnSpan="3" FontSize="14"/>

                <CheckBox x:Name="cb4" Grid.Row="3" Grid.Column="0" Margin="5"/>
                <TextBox  Name="tb4" Grid.Row="3" Grid.Column="1" Margin="2" Grid.ColumnSpan="3" FontSize="14"/>



            </Grid>
        </GroupBox>

        <StatusBar Grid.Row="4" Grid.Column="0" Grid.ColumnSpan="6" DockPanel.Dock="Bottom" Margin="0" Height="32" Background="#DFE5EB">
            <TextBlock x:Name="Footer" Text="Footer" Margin="3 0 3 0" Padding="0" Background="#DFE5EB"/>
            <StatusBarItem HorizontalAlignment="Right" Background="#E4E8ED">
                <ResizeGrip Opacity="0.75" Background="#E4E8ED"/>
            </StatusBarItem>
        </StatusBar>
    </Grid>
</Window>

Мои попытки четны вот мой код проблема в том что все элементы исчезают при добавлении TextBox:

private void btn_addnew_Click(object sender, RoutedEventArgs e)
        {

            //Creating Rows..
            RowDefinition row0 = new RowDefinition();
            row0.Height = new GridLength(40);
            grid1.RowDefinitions.Add(row0);

            //Creating columns..
            ColumnDefinition col0 = new ColumnDefinition();
            col0.Width = new GridLength(30);
            grid1.ColumnDefinitions.Add(col0);


            int i = count;

            //1st Column TextBox

            txt1 = new TextBox();
            txt1.Margin = new Thickness(10, 10, 0, 0);
            Grid.SetRow(txt1, i);
            Grid.SetColumn(txt1, 0);

            txt1.Tag = txt1;
            grid1.Children.Add(txt1);
            count++;
        }
16
  • 1
    Вы действуете в корне не верно, ознакомьтесь с привязками WPF, шаблонами и элементом ItemsControl (+ с его наследниками), который генерирует коллекции элементов 10 июл 2019 в 9:10
  • Можно будет таким образом одновременно добавлять CheckBox и TextBox,CheckBox-тоже играет важную роль?
    – user330641
    10 июл 2019 в 9:54
  • 1
    Можно конечно, шаблон может быть сколь угодно сложным 10 июл 2019 в 10:14
  • 1
    Рекомендую вам хорошенько изучить пример: ru.stackoverflow.com/q/615927/218063 10 июл 2019 в 10:16
  • 1
    Если вызвался сеттер, значит данные изменились. Все просто. Разберите пример на который я вам давал ссылку. 12 июл 2019 в 13:45

2 ответа 2

0

Динамически будет так в xaml

//код для примера взят из головы

  <DataGrid>
        <DataGrid.Columns>
       <DataGridTextColumn
                    Header="ЗАГОЛОВОК1"
                    Binding="{Binding ИМЯПРИВЯЗКИ1}"/>
       <DataGridTextColumn
                    Header="ЗАГОЛОВОК2"
                    Binding="{Binding ИМЯПРИВЯЗКИ2}"/>
        </DataGrid.Columns>
        </DataGrid>
2
  • Как понял она берет данные .xlm фаила Header="ЗАГОЛОВОК1"-как хочу пометить колонку, Binding="{Binding ИМЯПРИВЯЗКИ1}-тег?
    – user330641
    10 июл 2019 в 9:44
  • Binding - привязка к данным, грубо говоря какие данные будут выводится в эту колонку, про заголовок так.
    – Dude36
    10 июл 2019 в 9:48
0

Ответ

Вот еще интересный ресурс:http://catcut.net/VrEB

Код wpf

<Window x:Class="PriceCreator.MainWindow"
        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:PriceCreator"
        mc:Ignorable="d"
        Title="Price Creator for => rozetka.com.ua" Height="1000" Width="1500" Name="window">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="52"/>
            <RowDefinition Height="1*"/>
            <RowDefinition Height="2*"/>
            <RowDefinition Height="32"/>
        </Grid.RowDefinitions>

        <Grid Grid.Row="0" Grid.Column="0" Margin="10">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="140"/>
                <ColumnDefinition Width="1*"/>

            </Grid.ColumnDefinitions>
            <Button x:Name="btnLoadSave" Grid.Column="0" FontSize="15" Margin="2" Content="Load/Save" Click="BtnLoadSave_Click"/>
            <Label Name="lbPath" Grid.Column="1" FontSize="16" Content="Name file"></Label>
        </Grid>
        <GroupBox Grid.Row="1" x:Name="grbMandatoryInformation" Header="Mandatory information" FontSize="16" Margin="10 0 10 10" Background="#DFE5EB" Foreground="#005565" BorderBrush="#005565">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="105"/>
                    <ColumnDefinition Width="415*"/>
                    <ColumnDefinition Width="426*"/>
                    <ColumnDefinition Width="14*"/>
                </Grid.ColumnDefinitions>
                <Grid.RowDefinitions>
                    <RowDefinition Height="31"/>
                    <RowDefinition Height="31"/>
                    <RowDefinition Height="31"/>
                    <RowDefinition Height="34"/>
                    <RowDefinition Height="31"/>
                </Grid.RowDefinitions>
                <Label Grid.Row="0" Grid.Column="0" Content="Имя"/>
                <TextBox x:Name="tbName" Grid.Row="0" Grid.Column="1" Margin="2" Grid.ColumnSpan="2"/>

                <Label  Grid.Row="1" Grid.Column="0" Content="Компания"/>
                <TextBox  Name="tbCompany" Grid.Row="1" Grid.Column="1" Margin="2" Grid.ColumnSpan="2"/>

                <Label Grid.Row="2" Grid.Column="0" Content="Категории"/>
                <ComboBox   Name="CbCategory" Grid.Row="2" Grid.Column="1" Margin="2" Grid.ColumnSpan="2" SelectionChanged="CbCategory_SelectedIndexChanged"/>

                <Label Grid.Row="3" Grid.Column="0" Content="Адрес сайта" Margin="2"/>
                <TextBox Name="tbUrl" Grid.Row="3" Grid.ColumnSpan="2" Margin="2"  Grid.Column="1" />


                <Button Grid.Row="4" Grid.Column="0"  FontSize="15" Margin="2" Content="+" Click="btnAddCotedory"/>
                <TextBox Name="tbcotegory"  Grid.Row="4" Grid.Column="1" Margin="2" Grid.ColumnSpan="2" KeyDown="AddCotedory_KeyDown"/>

            </Grid>

        </GroupBox>
        <GroupBox Grid.Row="2"  Header="Products" FontSize="16" Margin="10 0 10 10" Background="#DFE5EB" Foreground="#005565" BorderBrush="#005565">
            <ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto">
                <ItemsControl Name="ICProduct">
                    <ItemsControl.ItemTemplate>
                        <DataTemplate>
                            <Grid Margin="0,0,0,5">
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="30" />
                                    <ColumnDefinition Width="100*" />
                                </Grid.ColumnDefinitions>
                                <CheckBox  Grid.Column="0" IsChecked="{Binding active}" Margin="5"/>
                                <TextBox   Grid.Column="1" Text="{Binding Text}" />
                            </Grid>
                        </DataTemplate>
                    </ItemsControl.ItemTemplate>
                </ItemsControl>
            </ScrollViewer>
        </GroupBox>

        <StatusBar Grid.Row="4" Grid.Column="0" Grid.ColumnSpan="6" DockPanel.Dock="Bottom" Margin="0" Height="32" Background="#DFE5EB">
            <TextBlock x:Name="Footer" Text="Footer" Margin="3 0 3 0" Padding="0" Background="#DFE5EB"/>
            <StatusBarItem HorizontalAlignment="Right" Background="#E4E8ED">
                <ResizeGrip Opacity="0.75" Background="#E4E8ED"/>
            </StatusBarItem>
        </StatusBar>
    </Grid>
</Window>

Код с# код окна

using Microsoft.Win32;
using System;
using System.Windows;
using System.Windows.Input;

namespace PriceCreator
{

    public partial class MainWindow : Window
    {
        bool statusOvpen = true;
        //GetData gd = new GetData();
        Functional func = new Functional();
        string Path;

        public MainWindow()
        {
            InitializeComponent();
        }


        /// <summary>
        ///AddCotedory_KeyDown-При при нажатии Enter добавляем в список новою категрию.
        /// </summary>
        private void AddCotedory_KeyDown(object sender, KeyEventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(tbcotegory.Text)&& !string.IsNullOrEmpty(tbcotegory.Text))
            {
                if (e.Key == Key.Return)
                {
                    CbCategory.Items.Add(tbcotegory.Text);
                    tbcotegory.Text = string.Empty;
                }
            }

        }

        private void btnAddCotedory(object sender, RoutedEventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(tbcotegory.Text) && !string.IsNullOrEmpty(tbcotegory.Text))
            {   
                CbCategory.Items.Add(tbcotegory.Text);
                tbcotegory.Text = string.Empty;
            }

        }

        /// <summary>
        ///CbCategory_SelectedIndexChanged-ввожу данные в TextBox зависимости от выбранной категории.
        /// </summary>
        private void CbCategory_SelectedIndexChanged(object sender, EventArgs e)
        {
            ICProduct.ItemsSource = null;
            int currentMyComboBoxIndex = CbCategory.SelectedIndex + 1;
            func.СheckCategory(statusOvpen,currentMyComboBoxIndex,ICProduct);

        }


        private void BtnLoadSave_Click(object sender, RoutedEventArgs e)
        {
            const string Filter = "XML files (*.XML)|*.XML";
            OpenFileDialog dlg = new OpenFileDialog();
            SaveFileDialog sfd = new SaveFileDialog();
            dlg.Filter = Filter;
            sfd.Filter=Filter;

            if (statusOvpen)
            {

                if (dlg.ShowDialog() == true)
                {
                    Path = dlg.FileName;
                    lbPath.Content = Path;
                    func.init(Path, ref tbName, ref tbCompany, ref tbUrl, ref CbCategory);
                    statusOvpen = false;
                }


            }
            else if (sfd.ShowDialog() == true)statusOvpen = true;

        }


    }
}

Код функционалом для окна

using System.Collections.Generic;
using System.Windows.Controls;

namespace PriceCreator
{
    class Functional: GetData
    {

        class Data
        {
            public string Text { get; set; }
            public bool active { get; set; }
        }
        List<Data> items = new List<Data>();




        GetData gd = new GetData();
        public void init(string Path,ref TextBox Name, ref TextBox Company, ref TextBox Url,ref ComboBox Category)
        {    
            gd.GetXlmData(Path);
            Name.Text = gd.Name;
            Company.Text = gd.Company;
            Url.Text = gd.Url;
            Category.SelectedIndex = 0;//Установка начального  списка.
            foreach (var ct in gd.Сategories) Category.Items.Add(ct);
        }
        public int GetCountProduct(bool statusOvpen, int currentMyComboBoxIndex)
        {
            int CountPovar = 0;
            if (!statusOvpen)
            {
                foreach (var offer in gd.Offers)
                {
                    if (offer.CategoryId != currentMyComboBoxIndex) break;

                    if (offer.CategoryId == currentMyComboBoxIndex) CountPovar++;
                }
            }
            return CountPovar;
        }


        public void СheckCategory(bool statusOvpen, int currentMyComboBoxIndex, ItemsControl ICProduct)
        {
            int tem = GetCountProduct(statusOvpen, currentMyComboBoxIndex); int CountPovar; 
            if (tem != 0) CountPovar = GetCountProduct(statusOvpen, currentMyComboBoxIndex);
            else return;


                items.Clear();
                for (var i = 0; i < CountPovar; i++)
                {
                    if (gd.Offers[i].Available)
                    { 
                        string temp = string.Empty;
                        foreach (var par in gd.Offers[i].Param) temp += par.Name + " " + par.Text + "    ";
                        items.Add(new Data() { Text = "Имя продукта:" + gd.Offers[i].Name + " " + "Цена:" + gd.Offers[i].Price + " " + temp + "  Количество Товаров:" + gd.Offers[i].Stock_quantity, active = true });
                    }
                    else
                    {
                        string temp = string.Empty;
                        foreach (var Des in gd.Offers[i].Description) temp += Des + " ";
                        items.Add(new Data() { Text = temp, active = false });
                    }

                }

               ICProduct.ItemsSource = items;

        }

    }
}
0

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.