绑定WPF中datatemplate中列表的项目 [英] Binding items of a list in datatemplate in WPF

查看:329
本文介绍了绑定WPF中datatemplate中列表的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力学习WPF。 DataContext设置为ViewModel。在Itemscontrol中,我得到一个列表< string>名为 MYLIST。默认情况下,datatemplate的datacontext将为string。所以我将TextBlock的datacontext修改为Viemodel以访问绑定为Width的属性MyWidth。实际上,MyWidth的值的数量等于列表MyList中的元素的数量.MyWidth也是一个列表。现在我不知道如何获得MyWidth的所有值。

感谢你好帮帮我吧。我很感激你们。



我尝试过的事情:



Hi, I am trying to learn WPF. The DataContext is set to ViewModel. In Itemscontrol I am getting a list<string> named"MyList". By default the datacontext of datatemplate would be string. So I modified the datacontext of TextBlock to Viemodel to access the property MyWidth which is binded to "Width". Actually the number of values of "MyWidth" is equal to number of elements in the list "MyList".MyWidth is also a list.Now I do not know how I can get all the values of MyWidth.
Cold you please help me out. I will be grateful to you guys.

What I have tried:

<ItemsControl ItemsSource="{Binding MyList}">
                   <ItemsControl.ItemsPanel>
                       <ItemsPanelTemplate>
                           <StackPanel Name="horizontalLabels" Orientation="Horizontal"  />

                       </ItemsPanelTemplate>
                   </ItemsControl.ItemsPanel>
                   <ItemsControl.ItemTemplate>
                       <DataTemplate>

                           <TextBlock     Text="{Binding}"

                                         Width="{Binding DataContext.LabelWidth, RelativeSource={RelativeSource AncestorType=ItemsControl},UpdateSourceTrigger=PropertyChanged}"
                                          Background="Red" Height="30"  FontSize="12"

                                           >
                           </TextBlock>

                       </DataTemplate>
                   </ItemsControl.ItemTemplate>
               </ItemsControl>







public void AddLabels(double parameters)
        { MyList.Add("dummy");
MyWidth.Add(30);
MyList.Add("dummy2");
MyWidth.Add(60);}

推荐答案

为你的字符串和宽度创建一个类。



用该类的实例加载一个集合(List<>或ObserveableCollection<>)。 br />


将ItemSource设置为此集合。



将TextBlockText和Width绑定到新字符串和宽度类的相应属性。



(您目前正在尝试使用Width不计算)。
Create a class for your "string" and "width".

Load a collection (List<> or ObserveableCollection<>) with instances of that class.

Set the ItemSource to this collection.

Bind the TextBlock "Text" and "Width" to the corresponding properties of the new "string and width" class.

(What you're currently trying to do with Width "does not compute").


这篇关于绑定WPF中datatemplate中列表的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆