C# WPF,列表框中没有显示任何内容
我不知道我做错了什么。我有一个C# WPF,列表框中没有显示任何内容,c#,wpf,xaml,listbox,itemssource,C#,Wpf,Xaml,Listbox,Itemssource,我不知道我做错了什么。我有一个ListBox,它的DataContext和ItemsSource都已设置,但当我运行我的应用程序时,ListBox中没有任何内容。调试时,我获取列表框项的方法的第一行永远不会被命中。以下是我所拥有的: // Constructor in UserControl public TemplateList() { _templates = new Templates(); InitializeComponent(); DataContext =
ListBox
,它的DataContext
和ItemsSource
都已设置,但当我运行我的应用程序时,ListBox中没有任何内容。调试时,我获取列表框
项的方法的第一行永远不会被命中。以下是我所拥有的:
// Constructor in UserControl
public TemplateList()
{
_templates = new Templates();
InitializeComponent();
DataContext = this;
}
// ItemsSource of ListBox
public List<Template> GetTemplates()
{
if (!tryReadTemplatesIfNecessary(ref _templates))
{
return new List<Template>
{
// Template with Name property set:
new Template("No saved templates", null)
};
}
return _templates.ToList();
}
//UserControl中的构造函数
公共样板画家()
{
_模板=新模板();
初始化组件();
DataContext=this;
}
//列表框的项目来源
公共列表GetTemplates()
{
如果需要(!tryreadtemplates(参考模板))
{
返回新列表
{
//已设置名称属性的模板:
新模板(“无保存的模板”,空)
};
}
return_templates.ToList();
}
这是我的XAML:
<ListBox ItemsSource="{Binding Path=GetTemplates}" Grid.Row="1" Grid.Column="1"
Width="400" Height="300" DisplayMemberPath="Name"
SelectedValuePath="Name"/>
在模板
类的实例上,有一个名称
属性,它只是一个字符串
。我只想显示一个模板名称列表。用户不会更改模板
中的任何数据,列表框
只需为只读
模板还有一个Data
属性,我稍后会在这个列表框中显示它,所以我不想让GetTemplates
只返回一个字符串列表——它需要返回一些Template
对象的集合。不能绑定到方法。让它成为一种财产,它就会起作用
最好将列表设置为DataContext,或者创建一个保存列表的ViewModel。这样,您就可以更好地控制列表框绑定到的实例
希望这有帮助 无法绑定到方法。让它成为一种财产,它就会起作用
最好将列表设置为DataContext,或者创建一个保存列表的ViewModel。这样,您就可以更好地控制列表框绑定到的实例
希望这有帮助 当您应该使用属性时,您正在尝试调用绑定中的方法。把它换成一个地方,你就可以走了
public List<Template> MyTemplates {get; private set;}
public TemplateList()
{
InitializeComponent();
SetTemplates();
DataContext = this;
}
// ItemsSource of ListBox
public void SetTemplates()
{
// do stuff to set up the MyTemplates proeprty
MyTemplates = something.ToList();
}
public List MyTemplates{get;private set;}
公共样板画家()
{
初始化组件();
SetTemplates();
DataContext=this;
}
//列表框的项目来源
公共void SetTemplates()
{
//做一些事情来设置MyTemplates项目
MyTemplates=something.ToList();
}
Xaml:
当您应该使用属性时,您正在尝试调用绑定中的方法。把它换成一个地方,你就可以走了
public List<Template> MyTemplates {get; private set;}
public TemplateList()
{
InitializeComponent();
SetTemplates();
DataContext = this;
}
// ItemsSource of ListBox
public void SetTemplates()
{
// do stuff to set up the MyTemplates proeprty
MyTemplates = something.ToList();
}
public List MyTemplates{get;private set;}
公共样板画家()
{
初始化组件();
SetTemplates();
DataContext=this;
}
//列表框的项目来源
公共void SetTemplates()
{
//做一些事情来设置MyTemplates项目
MyTemplates=something.ToList();
}
Xaml:
这更干净!我将我的GetTemplates
方法设置为私有,并在构造函数中设置DataContext=GetTemplates()
。然后我在XAML中将ItemsSource
设置为列表
属性,我的模板
类已经有了--谢谢!顺便说一句,如果您确实希望从Xaml调用方法,请查看ObjectDataProvider。Bea Stollnitz有一个很好的博客:这更干净!我将我的GetTemplates
方法设置为私有,并在构造函数中设置DataContext=GetTemplates()
。然后我在XAML中将ItemsSource
设置为列表
属性,我的模板
类已经有了--谢谢!顺便说一句,如果您确实希望从Xaml调用方法,请查看ObjectDataProvider。Bea Stollnitz有一个很好的博客: