WPF 对象获取属性列表
我搜索了谷歌,找不到特定问题的任何答案。
我的表单中有一个列表框,其中有一些自定义对象。
foreach (Fixture fixture in FixtureLibrary)
{
if (fixture.ModelName == "")
{
//Nothing
}
else
{
lbxLibrary.Items.Add(fixture);
}
}
在列表框中,我想看到 ModelName 属性。我可以通过更改以下内容来做到这一点:
lbxLibrary.Items.Add(fixture.ModelName);
但我需要能够在运行时从列表中选择一个对象,因此这种方法对我不起作用。
任何人有任何想法,我发现的只是 winforms,但这并没有真正帮助我,因为我正在使用 WPF。
干杯伙计们
迈克。
I've searched google and cannot find any answers to the particular problem.
I have a listbox in my form which has got some custom objects in them.
foreach (Fixture fixture in FixtureLibrary)
{
if (fixture.ModelName == "")
{
//Nothing
}
else
{
lbxLibrary.Items.Add(fixture);
}
}
In the listbox I would like to see the ModelName property. I can do this by changing the following:
lbxLibrary.Items.Add(fixture.ModelName);
But I need to be able to select an object at runtime from the list, so this approach wont work for me.
Anybody got any ideas, all I've found is for winforms but that doesn't really help me as I'm using WPF.
Cheers chaps
Mike.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该这样做:
创建一个具有这些属性的 ViewModel 类,它应该在 UI 和业务逻辑之间进行调解。将 ViewModel 指定为用户控件/窗口的 DataContext。
文件:FixtureViewModel.cs
FixtureUserControl.cs
然后只需在 ViewModel 代码中的某处分配您的 Fixture 列表。
然后您可以在 WPF 中对其进行数据绑定。创建一个像这样的 DataTemplate 并将其放入您的 UserControls 资源或 ResourceLibrary 中:
注意 DataType 属性。您可能需要为您的 Fixture 对象定义命名空间。
然后像这样对列表进行数据绑定:
然后,如果确实需要,您可以随时从 ViewModel 甚至 UserControl 中的任何位置访问 SelectedFixture 对象。
You should do it like this:
Create a ViewModel class with these properties, it should mediate between the UI and your business logic. Assign the ViewModel as the DataContext of your UserControl/Window.
File: FixtureViewModel.cs
FixtureUserControl.cs
Then just assign your list of Fixtures somewhere in your ViewModel-Code.
You can then databind it in WPF. Create a DataTemplate like this and put it in your UserControls Resources or a ResourceLibrary:
Notice the DataType attribute. You probably need to define the namespace for your Fixture object.
And databind your list like this:
Then you can always access the SelectedFixture Object from anywhere in the ViewModel or even the UserControl, if you really need to.
在
ListBox
中,将DisplayMemberPath
设置为Fixture
对象中的ModelName
属性,如下所示:In the
ListBox
, setDisplayMemberPath
to be theModelName
property from yourFixture
object, like this: