基于对象名称的对象属性数据绑定到集合项

时间:2011-02-09 19:42:15

标签: c# wpf silverlight data-binding observablecollection

是否可以实现以下WPF(Silverlight)数据绑定方案?

页面上有许多CustomControl:

<Grid x:Name="grid1">
  ...
  <My:CustCntr x:Name="name1" Property1="{Binding Property1}" />
  <My:CustCntr x:Name="name2" Property1="{Binding Property1}" />
  <My:CustCntr x:Name="name3" Property1="{Binding Property1}" />
  ...
</Grid>

Grid的DataContext是一个ObservableCollection:

grid1.DataContext = myCollection;
...
ObservableCollection<MyEntity> myCollection= new ObservableCollection<MyEntity>();
...

MyEntity类包含属性NameProperty1

 MyEntity me1 = new MyEntity { Name = "name1", Property1 = "5" };      
 MyEntity me2 = new MyEntity { Name = "name2", Property1 = "6" };
 MyEntity me3 = new MyEntity { Name = "name3", Property1 = "7" }; 
 ... 
 myCollection.Add(me1); 
 myCollection.Add(me2);
 myCollection.Add(me3); 
 ...    

我可以在每个CustomControls中为Property1建立数据绑定到myCollection的相应项目,其中CustomControl的Name等于集合的Name字段的值项吗

2 个答案:

答案 0 :(得分:2)

通常情况下,如果要在UI上显示要显示的集合,则使用ItemsControlListBox等,并将ItemsSource设置为Collection。实施例

<ItemsControl Name="itemsControl1"
              ItemsSource="{Binding MyCollection}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <VirtualizingStackPanel/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <My:CustCntr Property1="{Binding Property1}"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

现在每个CustCntr的DataContext都是MyEntity的实例,Binding将在CustCntr.Property1MyEntity.Property1之间设置


那就是说,我不确定你当前实现的原因所以如果你想根据Name创建Bindings我认为你将不得不诉诸代码

Xaml

<Grid Name="grid1" Loaded="Grid_Loaded">
    <My:CustCntr x:Name="name1" />
    <My:CustCntr x:Name="name2" />
    <My:CustCntr x:Name="name3" />
    <!--...-->
</Grid>

代码

public ObservableCollection<MyEntity> MyCollection
{
    get;
    private set;
}

<强>更新
每次在代码中修改集合时,都要调用此方法SetBindings。此外,使用Grid的Loaded事件代替在第一次加载时设置所有绑定。

private void Grid_Loaded(object sender, RoutedEventArgs e)
{
    SetBindings();
}
private void SetBindings()
{
    foreach (UIElement element in grid1.Children)
    {
        if (element is CustCntr)
        {
            CustCntr custCntr = element as CustCntr;
            foreach (MyEntity myEntity in MyCollection)
            {
                if (custCntr.Name == myEntity.Name)
                {
                    Binding property1Binding = new Binding("Property1");
                    property1Binding.Source = myEntity;
                    property1Binding.Mode = BindingMode.TwoWay;
                    custCntr.SetBinding(CustCntr.Property1Property, property1Binding);
                    break;
                }
            }
        }
    }
}

答案 1 :(得分:0)

不,那是不可能的。 但是,您可以使用ItemsControl对象(从中继承多个控件),但可能更难设置设计。不是单个控件,而是每个CustCntr的放置。