[英]How to reference a databound control in XAML
I'm creating Canvas
objects programmatically in my codebehind and adding them to a ListBox.Items
. 我将在我的代码背后以编程方式创建
Canvas
对象,并将其添加到ListBox.Items
。 Now I want to create a DataTemplate
for my ListBox
that displays those Canvas
objects with a border and highlights. 现在,我想为我的
ListBox
创建一个DataTemplate
,以显示带有边框和高光的那些Canvas
对象。
Prior to this I was using Images
in my ListBox
instead of Canvases
, and was able to bind to a BitmapImage
as the Image.Source
property and this worked: 在此之前,我在
ListBox
使用Images
而不是Canvases
,并且能够将BitmapImage
绑定为Image.Source
属性,并且可以工作:
<ListBox Name="LayoutListBox">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border Margin="20,0" BorderBrush="Black" BorderThickness="2" Width="195" Height="195">
<Grid>
<Image Source="{Binding}" Stretch="Uniform" />
// ...Some overlays and such
</Grid>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ListBox>
But now that the ListBox.Items
is using Canvas
objects, I can't figure out how to reference them from the XAML. 但是,既然
ListBox.Items
使用的是Canvas
对象,我现在不知道如何从XAML引用它们。
<ListBox Name="LayoutListBox">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border Margin="20,0" BorderBrush="Black" BorderThickness="2" Width="195" Height="195">
<Grid>
----HOW DO I REFERENCE MY CANVAS FROM HERE?-----
// ...Some overlays and such
</Grid>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ListBox>
Got it, ContentPresenter
is what I needed. 知道了,
ContentPresenter
是我所需要的。
<ListBox Name="LayoutListBox">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border Margin="20,0" BorderBrush="Black" BorderThickness="2" Width="195" Height="195">
<Grid>
<ContentPresenter Content="{Binding}"/>
// ...Some overlays and such
</Grid>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ListBox>
Do binding in your Canvas
like this. 像这样在
Canvas
绑定。 eg, You want to bind to the Width
property of the Canvas
例如,您想绑定到
Canvas
的Width
属性
<ListBox>
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Canvas Width="{Binding RelativeSource={RelativeSource AncestorType=ListBox},Path=Items}"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.