![](/img/trans.png)
[英]Binding in ItemsControl not bubbling to the item from ItemsSource
[英]How to get a Binding to other Class than ItemsSource from within ItemsControl?
我有一个类ShapeGrid,它包含大小等基本信息,并包含一个Shape列表。 在Shapes中打印出每个对象时如何从ShapeGrid获取ShapeSize属性?
public class ShapeGrid
{
public List<Shape> Shapes { get; set; }
public int GridSize { get; private set; }
public double ShapeSize { get; private set; }
}
public class Shape
{
public Brush Color { get; set; }
public int Id { get; set; }
}
在使用ContentControl时,我可以获取容器类,但是如果不逐一编写它们,我将无法查看所有形状的列表。
<ContentControl Content="{Binding ShapeGrid}" Grid.Row="2" Grid.Column="2">
<ContentControl.ContentTemplate>
<DataTemplate>
<WrapPanel>
<Rectangle Fill="{Binding Shapes[0].Color}" Height="{Binding ShapeSize}" Width="{Binding ShapeSize}" />
</WrapPanel>
</DataTemplate>
</ContentControl.ContentTemplate>
</ContentControl>
使用ItemsSource时,我将无法访问容器值。
<ItemsControl ItemsSource="{Binding ShapeGrid.Shapes}" Grid.Row="2" Grid.Column="2">
<ItemsControl.ItemTemplate>
<DataTemplate>
<WrapPanel>
<Rectangle Fill="{Binding Color}" Height="20" Width="20" />
//this is what I want to
//<Rectangle Fill="{Binding Color}" Height="{Binding ShapeGrid.ShapeSize}" Width="{Binding ShapeGrid.ShapeSize}" />
</WrapPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
我需要ShapeGerid中的ShapeSize和Shape中的Color,两者都在Rectangle标签中。 有没有办法做到这一点?
编辑:我可以将ShapeSize属性放在每个单独的Shape中,但想象它是否是任何类型的外部值,如windowSize等。
我不确定在模板中没有ContentPresenter的情况下使用ContentControl的目的是什么(允许您将Rectangle作为内容而不是模板放置,并且还允许您直接使用绑定。
但假设这是故意的:问题是您丢失了模板中的上下文。 您可以使用的是绑定代理,它允许您绑定模板中父对象的对象。 您可以在此处找到它的示例实现: https : //thomaslevesque.com/2011/03/21/wpf-how-to-bind-to-data-when-the-datacontext-is-not-inherited/
然后你可以做这样的事情(未经测试):
<ContentControl x:name="MyContentControl" Content="{Binding ShapeGrid}" Grid.Row="2" Grid.Column="2">
<ContentControl.Resources>
<local:BindingProxy x:Key="shapeProxy" Data="{Binding ShapeGrid}" />
</ContentControl.Resources>
<ContentControl.ContentTemplate>
<DataTemplate>
<WrapPanel>
<Rectangle Fill="{Binding Shapes[0].Color}" Height="{StaticResource shapeProxy, Path=Data.ShapeSize}" Width="{StaticResource shapeProxy, Path=Data.ShapeSize}" />
</WrapPanel>
</DataTemplate>
</ContentControl.ContentTemplate>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.