Reputation: 119
I found incorrect piece of code in my work yesterday. I was adding 2 different types of Texboxes
to the same list. When I change one of the names of the properties they now don't appear in the StackPanel
.
Let me show you, This is my working property, when I Click a button it adds a title Textbox
to the Stackpanel
:
ObservableCollection<string> _title = new ObservableCollection<string>();
public ObservableCollection<string> Title
{
get { return _title; }
set
{
_title = value;
OnPropertyChanged(() => Title);
}
}
This works perfectly, when I click a button it adds the title Texbox
to the StackPanel
. When I try and do it for a question Textbox
it wont work:
ObservableCollection<string> _questions = new ObservableCollection<string>();
public ObservableCollection<string> Questions
{
get { return _questions; }
set
{
_questions = value;
OnPropertyChanged(() => Questions);
}
}
I don't understand why it wont add as I have debugged the code for both the title and the question and they do exactly the same?
Does anyone know the error that I am making in my code?
EDIT:
public ViewModel()
{
this.AddQuestionCommand = new RelayCommand(new Action<object>((o) => OnAddQuestion()));
this.AddTitleCommand = new RelayCommand(new Action<object>((o) => OnAddTitle()));
}
private void OnAddQuestion()
{
this.Questions.Add("Question...");
}
private void OnAddTitle()
{
this.Title.Add("Title...");
}
<ListView x:Name="QuestionList" ItemsSource="{Binding Question}" ItemTemplate="{DynamicResource Template}">
<ListView.ItemContainerStyle>
<Style>
<Setter Property="FrameworkElement.Margin" Value="40,20,0,0"/>
</Style>
</ListView.ItemContainerStyle>
<ListView.Resources>
<DataTemplate x:Key="Template">
<TextBox Text="{Binding .}" Width="200" HorizontalAlignment="Left"/>
</DataTemplate>
</ListView.Resources>
</ListView>
EDIT 2:
ViewModel _viewModel = new ViewModel();
public MainWindow()
{
InitializeComponent();
base.DataContext = _viewModel;
}
Upvotes: 0
Views: 87
Reputation: 298
Your property is 'Questions' not 'Question' - it's probably the problem source
Upvotes: 1
Reputation: 69959
Your error is clearly not in the code that you have shown here. Apart from the names, the two code examples are the same. So if one is working and the other is not, then something else is broken somewhere else. This also stands for the code in your first edit. You just need to look at the two full examples (including the XAML) and see what is different.
Please read through the How to create a Minimal, Complete, Valid Example page from the Help Center, which should help you to provide better code examples. Often, following these guidelines can lead to you solving your own problems as well.
Upvotes: 1