如何实现需要来自viewmodel的数据的WPF ValueConverter?

发布于 2024-10-19 09:55:38 字数 482 浏览 5 评论 0原文

我正在编写一个具有视图模型和显示的用户控件的应用程序 来自此视图模型的数据。视图模型包含一个实体“约会”,并且那些 约会有一个属性“UserName”。

当我显示约会时,我想使用值转换器来获取颜色 用户(取决于“UserName”),但颜色不包含在实体“Appointment”中,因此我想创建一个使用视图模型中的实体“User”的值转换器。

在转换器内使用视图模型中的另一个实体的最佳方法是什么?

是否可以从用户控件访问视图模型?我尝试将转换器放置在我的视图模型类中,但是我可以从用户控件访问此类吗?

我发现以下可能性可能有效:

  1. 调整视图模型,使每个约会也包含颜色。但我不想这样做,因为我不想弄乱视图模型。

  2. 从启动时也包含视图模型的类中设置转换器参数。 (这有效吗?)

  3. 使用 x:Reference 将转换器参数数据绑定到编译时未知的视图模型。(这可能吗?)

i am writing an application that has a viewmodel and a usercontrol that displays
data from this viewmodel. The viewmodel contains an entity "Appointment", and those
appointments have a property "UserName".

When I display the appointments, I want to use a value-converter to get a color for
the user (depending on "UserName"), but the colors are not contained in the entity "Appointment", so I wanted to create a value-converter that uses the entity "User" from the viewmodel.

What is the best way to use another entity from the viewmodel inside the converter?

Is it possible to access the viewmodel from the usercontrol? I tried to place the converter inside my viewmodel-class, but can I access this class from the usercontrol?

I figured out that the following possibilities might work:

  1. Adjust the viewmodel so that each appointment also contains the color. But I don't want to do this because I don't want to mess with the viewmodel.

  2. Set the converter-parameter from the class that also contains the viewmodel at startup. (Does this work?)

  3. Use x:Reference to databind the converter parameter to the viewmodel that is unknown at compile-time.(Is this possible?)

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

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

发布评论

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

评论(2

梦回旧景 2024-10-26 09:55:38

转换器参数是要走的路。

为什么视图模型在编译时未知?
无论如何,编译时不会检查绑定。

如果将 UserControl.DataContext 设置为 Appointment 的实例,则您应该能够将参数设置为 {Binding UserName} 或 {Binding Appointment.UserName},具体取决于您在 UserControl 上设置为 DataContext 的内容。

Converter parameter is the way to go.

Why is the viewmodel unknown at compile time?
Bindings are not compile time checked anyway.

Is the UserControl.DataContext being set to an instance of Appointment, you should be able to set the parameter to {Binding UserName} or {Binding Appointment.UserName} depending on exactly what you are setting as the DataContext on the UserControl.

☆獨立☆ 2024-10-26 09:55:38

我建议你重新审视一下你是否不愿意修改视图模型。拥有视图模型的首要目的是让视图所需的一切都可以在一个地方找到。提出复杂的值转换器来防止修改视图模型是一种越做越难以维护的方法。

I would suggest that you re-examine your reluctance to modify the view model. The purpose of having a view model in the first place is so that everything that the view needs can be found in one place. Coming up with elaborate value converters to prevent modifying the view model is an approach that gets increasingly unmaintainable the more you do it.

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