1

Тема: Refresh win form WPF

Є вюшка, в якій створюються динамічно елементи, потрібно по натиснені кнопки, рефрешнути вюшку, щоб зникли динамічно створені елементи.
Наперед дякую за допомогу.

2

Re: Refresh win form WPF

Якщо можете додайте солюшин, без нього важко щось сказати.

3

Re: Refresh win form WPF

Прихований текст
namespace Elast.Client.Views.StoreTypeViews
{
    internal sealed class StoreWareViewModel : BaseViewModel
    {
        #region Fields

        private readonly IFactoryRepository _factoryRepository;
        private readonly IBoxRepository _boxRepository;
        private readonly IProductModelRepository _productModelRepository;
        private IFactoryTypeRepository _typeRepository;

        private FactoryType _selectedFactoryType;
        private Factory _selectedFactory;
        private Factory _selectedFactoryForEditProductModel;
        private string _nameProductModel;
        private string _articleProductModel;
        private List<FactoryType> _factoryTypeList;
        private float _boxCountProductModel;
        private float _countProductModel;
        private float _totalCountProductModel;

        #endregion

        #region Commands

        public RelayCommand AddProductModel { get; set; }
        //public RelayCommand EditProductModel { get; set; }
        //public RelayCommand<ProductModel> DeleteProductModel { get; set; }

        #endregion

        #region Properties

        public List<Factory> AllFactories { get; set; }
        public List<FactoryType> FactoryTypesList
        {

            get { return _factoryTypeList; }
            set
            {
                _factoryTypeList = value;
                OnPropertyChanged(() => FactoryTypeList);
            }
        }

        private ObservableCollection<ProductModel> _productModelsByFactory;


        public ObservableCollection<ProductModel> ProductModelsByFactory
        {
            get { return _productModelsByFactory; }
            set
            {
                _productModelsByFactory = value;
                OnPropertyChanged(() => ProductModelsByFactory);
            }
        }

        public Factory SelectedFactory
        {
            get { return _selectedFactory; }
            set
            {
                _selectedFactory = value;
                if (value != null)
                {
                    FactoryTypeList = _typeRepository.GetByFactoryId(value.FactoryId);
                    SelectedFactoryType = FactoryTypeList.FirstOrDefault();
                }
                OnPropertyChanged(() => SelectedFactory);
            }
        }

        public FactoryType SelectedFactoryType
        {
            get { return _selectedFactoryType; }
            set
            {
                _selectedFactoryType = value;
                OnPropertyChanged(() => SelectedFactoryType);
                AddProductModel.OnCanExecuteChanged();
            }
        }

        public List<FactoryType> FactoryTypeList
        {
            get { return _factoryTypeList; }
            set
            {
                _factoryTypeList = value;
                OnPropertyChanged(() => FactoryTypeList);
            }
        }

        public string ArticleProductModel
        {
            get { return _articleProductModel; }
            set
            {
                _articleProductModel = value;
                AddProductModel.OnCanExecuteChanged();
                OnPropertyChanged(() => ArticleProductModel);
            }
        }

        public float BoxCountProductModel
        {
            get { return _boxCountProductModel; }
            set
            {
                _boxCountProductModel = value;
                AddProductModel.OnCanExecuteChanged();
                OnPropertyChanged(() => BoxCountProductModel);
            }
        }

        public float CountProductModel
        {
            get { return _countProductModel; }
            set
            {
                _countProductModel = value;
                AddProductModel.OnCanExecuteChanged();
                OnPropertyChanged(() => CountProductModel);
            }
        }

        #endregion

        public Func<List<Box>> GetDynamicBoxParams { get; set; }

        /// <summary>
        ///     ctor.
        /// </summary>
        public StoreWareViewModel()
        {

            AddProductModel = new RelayCommand(
                () => true,
                () =>
                {
                    var productBoxParams = GetDynamicBoxParams.Invoke();

                    var newProductModel = new ProductModel()
                    {
                        FactoryId = SelectedFactory.FactoryId,
                        FactoryTypeId = SelectedFactoryType.FactoryTypeId,
                        Article = ArticleProductModel,
                        CreatedOn = DateTime.Now,
                    };
                    _productModelRepository.AddProductModel(newProductModel);

                    productBoxParams.ForEach(x => x.ProductModelId = newProductModel.ProductModelId);
                    _boxRepository.AddBoxes(productBoxParams);

                    ArticleProductModel = string.Empty;
                    // >>RefreshView<<
                });

            _boxRepository = new BoxReposirory();
            _factoryRepository = new FactoryRepository();
            _productModelRepository = new ProductModelRepository();
            _typeRepository = new FactoryTypeRepository();

            AllFactories = new List<Factory>(GetAllFactories());

            SelectedFactory = AllFactories.FirstOrDefault();

        }


        private IEnumerable<Factory> GetAllFactories()
        {
            return _factoryRepository.GetAllFactories();
        }
    }
}



код біхаєнд:
namespace Elast.Client.Views.StoreTypeViews
{
    /// <summary>
    /// Interaction logic for StoreTypeWareView.xaml
    /// </summary>
    public partial class StoreTypeWareView : IView
    {
        private StoreWareViewModel _viewModel;

        private readonly List<Box> _productDynamicParamses;

        public StoreTypeWareView()
        {
            InitializeComponent();
            _productDynamicParamses = new List<Box>();
        }

        public string ViewName
        {
            get { return ViewNames.StoreWare; }
        }

        public void InitView()
        {
            DataContext = _viewModel = new StoreWareViewModel();
            AddNumeric();
            _viewModel.GetDynamicBoxParams = () =>
            {
                Box productDynamicParams = null;

                foreach (var control in LayoutGrid.Children.Cast<UIElement>()
                        .Where(x => x is RadNumericUpDown))
                {
                    if ((control as RadNumericUpDown).Name.Equals("boxCount"))
                    {
                        productDynamicParams = new Box
                        {
                            BoxCount = (int) (control as RadNumericUpDown).Value.Value
                        };
                    }
                    else
                    {
                        productDynamicParams.BoxSize = (int)((RadNumericUpDown) control).Value.Value;
                        productDynamicParams.ResidueInBox = productDynamicParams.BoxSize;
                        _productDynamicParamses.Add(productDynamicParams);
                    }

                }

                return _productDynamicParamses;
            };
        }

        private void Add_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            AddNumeric();
        }

        private int _setRow = 1;

        void countInBox_ValueChanged(object sender, RadRangeBaseValueChangedEventArgs e)
        {
            CalculateTotal();
        }

        void boxCount_ValueChanged(object sender, RadRangeBaseValueChangedEventArgs e)
        {
            CalculateTotal();
        }

        private void CalculateTotal()
        {
            double boxCount = default(double);
            double totalCount = default(double);

            foreach (var control in LayoutGrid.Children.Cast<UIElement>()
                .Where(x => x is RadNumericUpDown))
            {
                if ((control as RadNumericUpDown).Name.Equals("boxCount"))
                {
                    boxCount = ((RadNumericUpDown)control).Value.Value;
                }
                else
                {

                    totalCount += boxCount * ((RadNumericUpDown)control).Value.Value;

                    boxCount = default(double);
                }
            }

            Total.Text = totalCount.ToString();

        }

        private void AddNumeric()
        {
            RadNumericUpDown boxCount = new RadNumericUpDown
            {
                Height = 35,
                Minimum = 1,
                Name = "boxCount",
                Width = 130,
                Margin = new Thickness(7),
                HorizontalAlignment = HorizontalAlignment.Left,
                VerticalAlignment = VerticalAlignment.Center,
                FontFamily = new FontFamily("/Elast.Client;component/AppResources/Fonts/#Segoe UI Light"),
                FontSize = 14
            };
            boxCount.ValueChanged += boxCount_ValueChanged;

            RadNumericUpDown countInBox = new RadNumericUpDown
            {
                Height = 35,
                Minimum = 1,
                Width = 130,
                Name = "countInBox",
                Margin = new Thickness(7),
                HorizontalAlignment = HorizontalAlignment.Left,
                VerticalAlignment = VerticalAlignment.Center,
                FontFamily = new FontFamily("/Elast.Client;component/AppResources/Fonts/#Segoe UI Light"),
                FontSize = 14
            };
            countInBox.ValueChanged += countInBox_ValueChanged;

            int gridRowsCount = LayoutGrid.RowDefinitions.Count;
            if (gridRowsCount >= 5)
            {
                AddButton.IsEnabled = false;
            }

            LayoutGrid.AddControlToGrid(boxCount, 3, _setRow);
            LayoutGrid.AddControlToGrid(countInBox, 4, _setRow);

            _setRow++;
        }
    }
}

ну і сама вюшка:

<UserControl x:Class="Elast.Client.Views.StoreTypeViews.StoreTypeWareView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation"
             HorizontalAlignment="Center"
             VerticalAlignment="Top">

    <UserControl.Resources>
        <ControlTemplate x:Key="deleteButtonTemplate">
            <Image Margin="0,0,0,0" Source="../../Image/deleteProduct.png" />
        </ControlTemplate>

        <ControlTemplate x:Key="addButtonTemplate">
            <Image Margin="0" Source="../../Image/plus.png"/>
        </ControlTemplate>

        <DataTemplate x:Key="ProductModelListViewItemTemplate">
            <StackPanel Margin="5,3,0,3"
                        VerticalAlignment="Center"
                        Focusable="True"
                        Orientation="Horizontal">
                <telerik:RadButton Command="{Binding RelativeSource={RelativeSource AncestorType=UserControl},
                                                     Path=DataContext.DeleteProductModel}"
                                   CommandParameter="{Binding}"
                                   Template="{StaticResource deleteButtonTemplate}" />
                <TextBlock Margin="5,0,0,0"
                           FontFamily="/Elast.Client;component/AppResources/Fonts/#Segoe UI Light"
                           FontSize="24"
                           Text="{Binding Name}" />
            </StackPanel>
        </DataTemplate>
        <DataTemplate x:Key="FactoryListBoxItemTemplate">
            <StackPanel>
                <TextBlock FontFamily="/Elast.Client;component/AppResources/Fonts/#Segoe UI Light"
                           FontSize="24"
                           Foreground="Black"
                           Text="{Binding FactoryName}" />
            </StackPanel>

        </DataTemplate>

    </UserControl.Resources>

    <Grid x:Name="LayoutGrid">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="150" />
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="Auto" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>


        <TextBlock Grid.Row="0" Margin="7"
                           FontFamily="/Elast.Client;component/AppResources/Fonts/#Segoe UI Light"
                           FontSize="20"
                           Foreground="White"
                           Text="Фабрикa"
                           TextWrapping="Wrap" />
        <telerik:RadComboBox Grid.Row="1"
                                     Width="185"
                                     Height="35"
                                     Margin="14,9,0,10"
                                     FontSize="20"
                                     HorizontalAlignment="Left"
                                     ItemTemplate="{StaticResource FactoryListBoxItemTemplate}"
                                     ItemsSource="{Binding AllFactories}"
                                     SelectedItem="{Binding SelectedFactory,
                                                            Mode=TwoWay,
                                                            UpdateSourceTrigger=PropertyChanged}" />


        <TextBlock Grid.Column="1" Grid.Row="0" Margin="7"
                           FontFamily="/Elast.Client;component/AppResources/Fonts/#Segoe UI Light"
                           FontSize="20"
                           Foreground="White"
                           Text="Тип"
                           TextWrapping="Wrap" />
        <telerik:RadComboBox Grid.Row="1"
                                     Grid.Column="1"
                                     Width="185"
                                     Height="35"
                                     Margin="7"
                                     FontSize="20"
                                     HorizontalAlignment="Left"
                                     FontFamily="/Elast.Client;component/AppResources/Fonts/#Segoe UI Light"
                                     ItemsSource="{Binding FactoryTypeList}"
                                     SelectedItem="{Binding SelectedFactoryType, 
                                                    Mode=TwoWay,
                                                    UpdateSourceTrigger=PropertyChanged}"
                                     DisplayMemberPath="FactoryTypeName"/>

        <TextBlock Margin="7"
                           Grid.Row="0"
                       Grid.Column="2"
                           VerticalAlignment="Center"
                           FontFamily="/Elast.Client;component/AppResources/Fonts/#Segoe UI Light"
                           FontSize="20"
                           Foreground="White"
                           Text="Артикул" />
        <TextBox Width="130"
                 Height="36"
                 Margin="4,9,10,9"
                 Grid.Column="2"
                 Name="Article"
                 Grid.Row="1"
                 VerticalAlignment="Center"
                 FontFamily="/Elast.Client;component/AppResources/Fonts/#Segoe UI Light"
                 FontSize="20"
                 Text="{Binding ArticleProductModel}" />

        <TextBlock Margin="7"
                       Grid.Column="3"
                           Grid.Row="0"
                           VerticalAlignment="Center"
                           FontFamily="/Elast.Client;component/AppResources/Fonts/#Segoe UI Light"
                           FontSize="20"
                           Foreground="White"
                           Text="Ящики" />

        <TextBlock Margin="7"
                       Grid.Column="4"
                           Grid.Row="0"
                           VerticalAlignment="Top"
                           FontFamily="/Elast.Client;component/AppResources/Fonts/#Segoe UI Light"
                           FontSize="20"
                           Foreground="White"
                           Text="Кол-во в ящике" />
        <!--<telerik:RadNumericUpDown Grid.Row="1"
                         Height="35"
                         Width="130"
                         Minimum="1"
                                  Name="countInBox"
                         Margin="7"
                                      Grid.Column="4"
                         HorizontalAlignment="Left"
                         FontFamily="/Elast.Client;component/AppResources/Fonts/#Segoe UI Light"
                         FontSize="14"
                         Value="{Binding CountProductModel,
                                        Mode=TwoWay,
                                        UpdateSourceTrigger=PropertyChanged}" />-->


        <TextBlock Margin="7"
                           Grid.Row="0"
                           Grid.Column="5"
                           VerticalAlignment="Top"
                           FontFamily="/Elast.Client;component/AppResources/Fonts/#Segoe UI Light"
                           FontSize="20"
                           Foreground="White"
                           Text="Кол-во штук" />
        <TextBlock Name="Total"
                         Grid.Row="1"
                         HorizontalAlignment="Center"
                         Foreground="White"
                         Width="50"
                         Grid.Column="5"
                         Height="40"
                         Margin="7"
                         FontFamily="/Elast.Client;component/AppResources/Fonts/#Segoe UI Light"
                         FontSize="24"/>
        <telerik:RadButton     Name="AddModelRadButton"
                               Width="100"
                               Height="35"
                               Grid.Row="1"
                               Grid.Column="6"
                               Margin="7,7,7,10"
                               VerticalAlignment="Bottom"
                               HorizontalAlignment="Left"
                               Command="{Binding AddProductModel}"
                               Content="Добавить"
                               FontSize="16" />

        <telerik:RadButton  Name="AddButton"
                            Grid.Column="1"
                            Grid.Row="2"
                            Click="Add_Click"
                            HorizontalAlignment="Right"
                            Margin="7,17,7,7"
                            Width="25"
                            Height="25"
                            Template="{StaticResource addButtonTemplate}"/>
    </Grid>
</UserControl>

Hanter: код слід брати у теги code, також великий об`єм коду, слід поміщати у тег spoiler

4

Re: Refresh win form WPF

ні, я не зміг це запустити, там дуже багато звязків пропущені. а так як досвіду в впф в мене дуже мало я не зміг то все якось замокати. Доречі поставив телерік щось там - студія начала тупити ппц як, хоча це можливо тільки перший раз після установки.