绑定到集合中的各个元素(Binding to individual elements in a collection)

编程入门 行业动态 更新时间:2024-10-10 11:26:06
绑定到集合中的各个元素(Binding to individual elements in a collection)

我对MVVM很新,所以忍受。 我有一个视图模型类,其公共属性实现如下:

public List<float> Length { get; set; }

在我的视图的XAML中,我有几个文本框,每个文本框都绑定到此长度列表中的特定元素:

<TextBox Text="{Binding Length[0], Converter=DimensionConverter}" /> <TextBox Text="{Binding Length[2], Converter=DimensionConverter}" /> <TextBox Text="{Binding Length[4], Converter=DimensionConverter}" />

DimensionConverter是一个IValueConverter派生类,它将值格式化为尺寸(即480.0英寸在屏幕上的文本框中变为40'0“),然后再返回(即对于一个字符串需要35'0”,并为此生成420.0英寸资源)

我的问题:我需要能够验证List中的每个值,因为它在关联的TextBox中已更改。 对于某些人,我可能需要根据输入的值修改List中的其他值(即更改Length [0]处的float将更改Length [4]处的值并更新屏幕)。

有没有办法重新处理属性以允许索引器? 或者,我是否需要为列表中的每个项目创建单独的属性(这真的使List不必要)? 本质上,因为我已经拥有了float的集合,所以我希望能够编写MVVM代码来验证每个项目的修改。

思考? (并且,提前谢谢)

I am fairly new to MVVM, so bear with. I have a view model class that has a public property implemented as so:

public List<float> Length { get; set; }

In my XAML for the view, I have several text boxes, with each one bound to a specific element in this Length list:

<TextBox Text="{Binding Length[0], Converter=DimensionConverter}" /> <TextBox Text="{Binding Length[2], Converter=DimensionConverter}" /> <TextBox Text="{Binding Length[4], Converter=DimensionConverter}" />

The DimensionConverter is a IValueConverter derived class that formats the values like a dimension (i.e. 480.0 inches becomes 40'0" in the text box on screen), and back again (i.e. takes 35'0" for a string and yield 420.0 inches for the source)

My issue: I need to be able to validate each value in the List as it is changed in the associated TextBox. For some, I may need to modify other values in the List depending on the entered value (i.e. change the float at Length[0] will change the value at Length[4] and update the screen).

Is there any way to re-work the property to allow for an indexer? Or, do I need to create individual properties for each item in the List (which really makes the List unnecessary)? Essentially, since I already have the collection of float, I was hoping to be able to write MVVM code to validate each item as it is modified.

Thoughts? (and, thanks in advance)

最满意答案

您可以使用ObservableCollection<float>而不是List<float> ,并处理CollectionChanged事件以检测用户何时更改值。

You can use an ObservableCollection<float> instead of a List<float>, and handle the CollectionChanged event to detect when the user changes a value.

更多推荐

本文发布于:2023-08-04 17:07:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1419187.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:绑定   元素   Binding   collection   elements

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!