简体   繁体   English

如何在XAML中引用数据绑定控件

[英]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 例如,您想绑定到CanvasWidth属性

    <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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM