无法将项目添加到Observable Collection(或未刷新UI)

时间:2018-12-03 15:29:36

标签: c# wpf

我有一个菜鸟问题。如标题所示,我对可观察的集合有疑问。 我正在尝试填充通过TextBox传递值的集合,然后将其添加到可观察的集合中。当我按下按钮“ 添加Ciudad ”时,将显示一个用于插入新值的文本框和一个用于保存新值的按钮。 该值已成功添加到负责该操作的方法(“ 添加输入城市”),但是UI从未显示新项目。 顺便说一句,在“ Load Ciudades ”中手动添加的第一个值显示正确。

我看到了一些相关问题,但仍然无法解决问题。

我怀疑我没有正确添加项目。对于更多的麻烦,我完全是C#:D的菜鸟。 这是代码,因此您可以判断:

城市模型:

public class Ciudad : INotifyPropertyChanged
{
    private string nombre;

    public String Nombre
    {
        get { return nombre; }

        set {
                nombre = value;
                RaisePropertyChanged("Nombre");
                RaisePropertyChanged("Ciudades"); //Dunno if this one is necesary.
            }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void RaisePropertyChanged(string property)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(property));
        }
    }
}

城市视图模型:

public ObservableCollection<Ciudad> Ciudades { get; } = new ObservableCollection<Ciudad>();

    public void LoadCiudades()
    {
        Ciudades.Add(new Ciudad { Nombre = "Random city" });
    }

    public void AddInputCity(string new_city)
    {
        Ciudades.Add(new Ciudad { Nombre = new_city });
    }

城市视图:

<Grid>
    <DataGrid ItemsSource = "{ Binding Path = Ciudades, UpdateSourceTrigger=PropertyChanged }" Name="DGrid">

    </DataGrid>
    <Button Click="Button_Click" Height="30" Width="150" Margin="0,250,0,0">Add Ciudad</Button></Grid>

城市景观cs

TextBox iTextBox;

    public CiudadesView()
    {
        InitializeComponent();
    }

    private void Add_Input_Text()
    {
        TextBox iText = new TextBox
        {
            Name = "iText",
            Width = 250,
            Margin = new Thickness(100)
        };

        Button saveBtn = new Button()
        {
            Content = "Save"
        };
        saveBtn.Click += new RoutedEventHandler(Button_Save_Click);

        sPanel.Children.Add(iText);
        sPanel.Children.Add(saveBtn);
        iTextBox = iText;
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        Add_Input_Text();
    }

    private void Button_Save_Click(object sender, RoutedEventArgs e)
    {
        string ciudadNuevoNombre = iTextBox.Text;
        CiudadesViewModel viewModel = new CiudadesViewModel();
        viewModel.AddInputCity(ciudadNuevoNombre);
    }

有什么想法或建议吗? 谢谢你们! :)

2 个答案:

答案 0 :(得分:1)

请确保您在AddInputCity事件处理程序中调用现有视图模型实例的Button_Click方法,例如:

private void Button_Click(object sender, RoutedEventArgs e)
{
    var viewModel = DataContext as YourViewModelClass;
    if (viewModel != null)
        viewModel.AddInputCity("new...");
}

答案 1 :(得分:1)

您尚未向我们显示您的点击代码和其他几项内容,例如view和viewmodel之间的关系。 我建议您也看看绑定命令,而不是单击处理程序。 本文旨在向读者介绍MVVM,它使用以下命令将项目添加到绑定的observablecollection中: https://social.technet.microsoft.com/wiki/contents/articles/32164.wpf-mvvm-step-by-step-2.aspx