[英]UWP Combo Box values dynamically generates text boxes
我有一個用整數填充的組合框。 如果我選擇三個,我想在它旁邊顯示 3 個文本框。 如果我選擇 2,我想顯示 2。在文本框中我寫示例編號:123、943、1e4 等。簡單的字符串。
文件.xaml
<ComboBox ItemsSource="{x:Bind ViewModel.SamplesCountList, Mode=OneTime}"
SelectedItem="{x:Bind ViewModel.SamplesCount, Mode=TwoWay}" />
<ItemsControl ItemsSource="{x:Bind Path=ViewModel.SamplesCollection, Mode=TwoWay}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBox Text="{Binding Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
我使用 MVVM Light。 我有一個 ViewModel,它有一個來自業務層的 Model。 SamplesCollection
鏈接到ItemsControl
。 如果我更新可觀察列表,它會動態生成文本框。 哪個好。
視圖模型.cs
public class MyModelViewModel : ObservableRecipient
{
private MyModelModel _myModelModel = new MyModelModel();
public MyModelModel MyModelModel
{
get { return _myModelModel; }
set { SetProperty(ref _myModelModel, value); }
}
public ObservableCollection<string> SamplesCollection { get; set; } = new ObservableCollection<string>();
public CreateFile() {
// Take _myModelModel and create text file based on its fields
}
}
在其他部分,我只是將我的業務 model 直接與 xaml 中的文本框鏈接起來。 像這樣ItemsSource="{x:Bind Path=MyViewModel.MyModel.Id, Mode=TwoWay}
我無法使用此動態 ItemsControl<->ComboBox 執行此操作,因為它沒有檢測到創建文本框的更改,因為ItemsSource="{x:Bind Path=MyViewModel.MyModel.SamplesCollectionModel}
, SamplesCollectionModel
是業務層中的List<string>
。
問題:我是否應該在需要處理時將可觀察的 SamplesCollection.ToList() 分配給我的 _myModel,或者我可以將我的業務 model 與 xaml 代碼鏈接起來,以某種方式擺脫這個額外的可觀察集合字段? 這里的最佳做法是什么?
我建議您在 ViewModel 中完成工作,而不是嘗試更改業務 model。 這是因為您使用的是 MVVM 模式,而 model 層應該只保留您的業務數據。
有關更多信息,請查看: 數據綁定和 MVVM 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.