【发布时间】:2021-05-23 07:52:37
【问题描述】:
我最近开始学习 C#,但遇到了一个问题。我在 WPF 中生成的复选框中显示一组关键字,我想根据来自 TXT 文件的输入检查来检查元素 (IsChecked)。 如果当前从不同列表框中选择的元素与读取的模型类(来自 txt 文件)匹配,则将选中的键设置为 true。
我正在 WPF 中生成一个复选框,以列出我的应用从 txt 文件中读取的一组关键字。 txt 文件每行包含以下项目: -ID -钥匙 -一对 -描述
WPF 代码:
<ListView ItemsSource="{Binding XAMLModelKeywords}" SelectedItem="{Binding XAMLModelKeyword}" Margin="5" x:Name="listofallkeys" Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="2" >
<ListView.ItemTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding XAMLAssignedKeys}" Content="{Binding Key}"/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
C#:
public ModelTemplates XAMLModelTemplate { get; set; }
public ModelKeywords XAMLModelKeyword { get; set; }
public List<bool> XAMLAssignedKeys { get; set; }
public string XAMLKeyword { get; set; }
public ViewModelMain()
{
//This creates a new instance of ObservableCollection above
XAMLModelTemplates = new ObservableCollection<ModelTemplates>();
XAMLModelKeywords = new ObservableCollection<ModelKeywords>();
XAMLAssignedKeys = new List<bool>();
Refresh();
}
public void Refresh()
{
XAMLModelTemplates.Clear();
foreach (ModelTemplates tpl in ReadInput.ReadTemplateDirectory(Path))
{
XAMLModelTemplates.Add(tpl);
}
//Selecting the first item from the returned list
XAMLModelTemplate = XAMLModelTemplates.FirstOrDefault();
XAMLModelKeywords.Clear();
foreach (ModelKeywords tpl in ReadInput.ReadKeywordsFile(KeyWordsPath))
{
XAMLModelKeywords.Add(tpl);
}
XAMLModelKeyword = XAMLModelKeywords.FirstOrDefault();
XAMLAssignedKeys.Clear();
foreach (ModelKeywords tpl in XAMLModelKeywords)
{
XAMLAssignedKeys.Add(ReadInput.CheckPairedtemplates(tpl, XAMLModelTemplate));
}
型号关键字:
public class ModelKeywords
{
public int Id { get; set; }
public string Key { get; set; }
public List<string> PairedTemplates { get; set; }
public string Description { get; set; }
}
模型模板:
public class ModelTemplates
{
//path to a template
public int Id { get; set; }
public string TemplatePath { get; set; }
public string TemplateName { get; set; }
public ExcelRange TemplateRange { get; set; }
}
读取关键字文件: 返回模板模型列表(模板文件名、路径)并将其显示在列表框中。
读取关键字文件: 返回关键字模型列表(id、key、pair、desc),然后将其显示在生成的列表框中。
检查配对模板: 根据当前选择的模板模型匹配关键字模型对(字符串列表)返回布尔列表。
TLDR: 我有一个布尔值列表( XAMLAssignedKeys ),我想将它与 WPF 中生成的复选框相匹配,但是生成是基于项目模板发生的,我不确定如何将布尔值列表中的一个元素链接到复选框“IsChecked”属性。
非常感谢您的建议。
【问题讨论】:
-
您的代码不完整。 ModelKeywords的内容是什么?
-
您好!这是一个简单的模型类。以下是内容:` public class ModelKeywords { public int Id { get;放; } 公共字符串密钥 { 获取;放; } public List
PairedTemplates { get;放; } 公共字符串描述 { 获取;放; } } ` -
我建议您自己完善您的问题,添加该类。此外,您的类实现了 INotifyPropertyChanged?它是 WPF MVVM 模式的基础。
-
在我的问题中添加了模型。我会调查这个 INotifyPropertyChanged。