WPF UserControl с ObservableCollection в коде позади не работает - PullRequest
0 голосов
/ 10 апреля 2020

У меня было рабочее решение с viewModel в качестве источника данных, переданных моему UserControl, например:

<UserControl.DataContext>
    <viewModels:PriceViewModel/>
</UserControl.DataContext>

Теперь я пытаюсь достичь того же результата с ObservableCollection в выделенном коде вместо viewModel. Решение компилируется и запускается, но нет элементов в элементе управления ItemsControl. Я не могу найти решения по другим вопросам :( Я хотел бы видеть элементы из public ObservableCollection<Row> Row в моем UserControl.

Код usercontrol:

public partial class TriggerListAdd : UserControl
{
    public TriggerListAdd()
    {
        InitializeComponent();
        Rows = new ObservableCollection<Row>();
        Rows.CollectionChanged += RowCollectionChanged;
        LoadRows();
    }

    public void LoadRows()
    {
        Rows.Add(new Row { Input = "221 331,44" });
        Rows.Add(new Row { Input = "2 331,44" });
        Rows.Add(new Row { Input = "331,44" });
        Rows.Add(new Row { Input = "0,44" });
    }

    //public DependencyProperty RowsProperty = DependencyProperty.Register("Rows", typeof(ObservableCollection<Row>), typeof(TriggerListAdd));
    public ObservableCollection<Row> Rows
    {
        get;
        set;
    }

    private void RowCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        if (e.NewItems != null)
        {
            foreach (var item in e.NewItems)
            {
                ((INotifyPropertyChanged)item).PropertyChanged += RowPropertyChanged;
            }
        }
        if (e.OldItems != null)
        {
            foreach (var item in e.OldItems)
            {
                ((INotifyPropertyChanged)item).PropertyChanged -= RowPropertyChanged;
            }
        }
    }

    private void RowPropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        var s = sender;
        var args = e;
    }

    private void bMain_Click(object sender, RoutedEventArgs e)
    {
        Rows.Add(new Row() { Input = tbMain.Text });
        foreach (var r in Rows)
        {
            MessageBox.Show(r.Input);
        }
    }
}

public class Row : INotifyPropertyChanged
{
    public string Input
    {
        get
        {
            return _input;
        }

        set
        {
            if (_input != value)
            {
                _input = value;
                RaisePropertyChanged("Input");
                RaisePropertyChanged("Output");
            }
        }
    }

    public string Output
    {
        get
        {
            return _input + "  " + _input;
        }

        set
        {
            if (_output != value)
            {
                _output = value;
                RaisePropertyChanged("Output");
            }
        }
    }

    private string _input;
    private string _output;

    public event PropertyChangedEventHandler PropertyChanged;

    private void RaisePropertyChanged(string property)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
    }
}

XAML:

<UserControl x:Class="PriceHumanizerDesktopClient.CustomControl.TriggerListAdd"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         xmlns:local="clr-namespace:PriceHumanizerDesktopClient.CustomControl"
         mc:Ignorable="d" 
         d:DesignHeight="450" d:DesignWidth="800"   
         x:Name="Myself" >
<Grid>
    <StackPanel HorizontalAlignment="Stretch" Margin="0 0 0 0" >
        <StackPanel Orientation="Horizontal" Margin="0 0 0 0" >
            <TextBox x:Name="tbMain" Width = "100" Margin = "3 5 3 5" />
            <Button  x:Name="bMain" Margin = "3 5 3 5" Content="Click me!" Click="bMain_Click"/>
        </StackPanel>
        <ItemsControl ItemsSource = "{Binding Rows, ElementName = Myself }">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation = "Horizontal">

                        <TextBox Text = "{Binding Path = Input, Mode = TwoWay}" 
                            Width = "100" Margin = "3 5 3 5"/>

                        <TextBox Text = "{Binding Path = Output, Mode = OneWay}" 
                            Width = "Auto" Margin = "0 5 3 5"/>

                    </StackPanel>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </StackPanel>
</Grid>
</UserControl>

Мой код почти такой же, как и у модели viewModel. Только привязанные DataContext к ElementName = Myself были изменены в привязках. Можете ли вы увидеть какие-либо заблуждения? Что вы могли бы помочь :)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...