[英]Creating Text boxes issue?
我已經發布了一個先前的問題,但是沒有什么幫助,所以我嘗試開始對其進行編碼,然后自己查找更多內容,而我陷入了某些代碼中。 我正在嘗試關注MVVM
我創建了一個名為Standard
的類,它看起來像這樣:
namespace MVVModel
{
public class Standard
{
string _title;
string _question;
public string Title
{
get { return _title; }
set { _title = value; }
}
public string Question
{
get { return _question; }
set { _question = value; }
}
}
}
然后,我創建了如下所示的ViewModel
類:
namespace MVVModel
{
class ViewModel
{
ObservableCollection<Standard> _title = new ObservableCollection<Standard>();
ObservableCollection<Standard> _question = new ObservableCollection<Standard>();
public ViewModel()
{
}
public ObservableCollection<Standard> Title
{
get
{
return _title;
}
set
{
_title = value;
}
}
public ObservableCollection<Standard> Question
{
get
{
return _question;
}
set
{
_question = value;
}
}
}
}
這是我的XAML:
<Grid>
<Button x:Name="btnTitle" Content="Title" HorizontalAlignment="Left" Margin="691,22,0,0" VerticalAlignment="Top" Width="75"/>
<Button x:Name="btnQuestion" Content="Question" HorizontalAlignment="Left" Margin="797,22,0,0" VerticalAlignment="Top" Width="75" Command="{Binding AddTitle}"/>
<ItemsControl ItemsSource="{Binding Question}" Margin="0,86,0,0">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBox />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
我只想動態創建一個文本框,但什么也沒顯示,有什么幫助嗎?
我在先前的回答中提到了有關實現INotifyPropertyChanged的問題。
為什么您再次需要在viewModel中收集問題和標題,這在Standard類中已經存在。
您在主ViewModel中需要一個Standard類的集合。 如果我理解正確,那就是我從您的問題中得到的。
這是INotifyPropertyChanged的實現
public class Standard : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
// Create the OnPropertyChanged method to raise the event
protected void NotifyOfPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
protected void NotifyOfPropertyChanged<TProperty>(Expression<Func<TProperty> property)
{
NotifyOfPropertyChanged(property.GetMemberInfo().Name);
}
string _title;
ObservableCollection<string> _questions;
public string Title
{
get { return _title; }
set {
_title = value;
NotifyOfPropertyChanged(()=>Title);
}
}
public ObservableCollection<string> Questions
{
get { return _questions; }
set {
_questions = value;
NotifyOfPropertyChanged(()=>Questions);
}
}
}
您必須按照幾個步驟來完成此任務。
首先,您需要將Standard
的集合綁定到Grid
,以代替Question
。
其次,您需要將上一類的屬性綁定到文本框。
例如:
<DataTemplate>
<TextBox Text="{Binding Question"} />
</DataTemplate>
編輯:
我想提及這篇文章以幫助您:
http://www.codeproject.com/Articles/165368/WPF-MVVM-Quick-Start-Tutorial
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.