如何将 POCO 对象绑定到 WPF GUI?

发布于 2024-12-21 05:49:34 字数 467 浏览 2 评论 0原文

我在一个简单的 WPF 应用程序中有三张图片。汽车、飞机和火车。

当我单击其中任何一个时,我会加载一个适当的“交通”对象,该对象具有交通名称、图片文件路径和其他字符串属性。一个简单的 POCO 对象。

如何在 XAML 中声明某种模板,以便我可以将该 POCO 对象作为数据源应用并将属性 X 放入元素 Foo 内?

这是我的简单 XAML:

<StackPanel>
    <TextBlock>Car</TextBlock>
    <TextBlock>Slow</TextBlock>
    <TextBlock>4 Wheels</TextBlock>
</StackPanel>

因此这里的属性将是我提供的 POCO 的模板持有者。

我如何提供此数据上下文?

I have three pictures in a simple WPF application. A car, a plane and a train.

When I click on either of them, I load an appropriate "transportation" object that has the name of the transportation, a picture file path, and other string properties. A simple POCO object.

How do I declare a template of sorts, in XAML, so I can then apply that POCO object as it's data source and put property X inside of element Foo?

Here is my simple XAML:

<StackPanel>
    <TextBlock>Car</TextBlock>
    <TextBlock>Slow</TextBlock>
    <TextBlock>4 Wheels</TextBlock>
</StackPanel>

So the properties here would be template holders for the POCO I provide.

How do I provide this data context?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

甩你一脸翔 2024-12-28 05:49:34
<StackPanel x:Name="transportPanel">
    <TextBlock Text="{Binding Name}" />
    <TextBlock Text="{Binding Speed}" />
    <TextBlock Text="{Binding Components}" />
</StackPanel>

在代码中,您可以设置数据上下文:

transportPanel.DataContext = myCarObject;

WPF 只能绑定到属性,而不是字段,因此在设计 POCO 时请记住这一点。

<StackPanel x:Name="transportPanel">
    <TextBlock Text="{Binding Name}" />
    <TextBlock Text="{Binding Speed}" />
    <TextBlock Text="{Binding Components}" />
</StackPanel>

And in code, you set the data context:

transportPanel.DataContext = myCarObject;

WPF can only bind to properties, not to fields, so keep that in mind when designing your POCOs.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文