[英]Object property databinding to a collection item based on a Name of an object
是否可以實現以下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
類具有Name
和Property1
。
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);
...
我可以建立數據綁定的Property1
在我的每個CustomControls的到的MyCollection的的相應項目Name
的CustomControl的相等的值Name
的集合項目的領域?
通常,在具有要在UI上顯示的Collection的情況下,您要做的是使用ItemsControl
, ListBox
等,並將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
的實例,並且將在CustCntr.Property1
和MyEntity.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;
}
}
}
}
}
不,那是不可能的。 但是,您可以使用ItemsControl對象(有多個控件繼承自它),但是可能更難設置設計。 對於單個控件,否,但對於每個CustCntr的位置,否。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.