Binding a Viewbox to a Canvas
I'm trying to bind a Viewbox
to a Canvas
that is created dynamically like so:
<ListBox.ItemTemplate>
<DataTemplate>
<DockPanel>
<Viewbox>
<ContentPresenter Content="{Binding Canvas}"/>
</Viewbox>
</DockPanel>
</DataTemplate>
</ListBox.ItemTemplate>
This works fine as long as the Canvas
doesn't have any children,开发者_开发问答 but as soon at the Canvas
has children it's not shown. What am I missing here?
How do you know it works? A Canvas
is just a Panel
with zero width/height. Even if it has any children, its dimensions are still going to be 0,0. You must explicitly set Width
and Height
to a non-zero value in order for it to appear. Paste the following snippet into XamlPad
or just test in your own app. Now, remove either Width
or Height
and it will vanish.
<Viewbox>
<ContentPresenter>
<ContentPresenter.Content>
<Canvas Background="Red" Width="1" Height="1">
<TextBlock Canvas.Left="10" Canvas.Top="20" Text="123" />
</Canvas>
</ContentPresenter.Content>
</ContentPresenter>
</Viewbox>
Forget I ever asked :-)
I caused an exception when creating the children of canvas, and this in turn caused the canvas to not be shown. I'm sad to say that it's not the first time I have made this mistake, and it's probably not that last time either:
TextBlock tb = new TextBlock();
tb.SetValue(Canvas.LeftProperty, 5);
tb.SetValue(Canvas.TopProperty, 5);
"5" is not a valid value for 'Left' or 'Top'. It should of course be
TextBlock tb = new TextBlock();
tb.SetValue(Canvas.LeftProperty, 5.0);
tb.SetValue(Canvas.TopProperty, 5.0);
And because it was created as part of data binding, no exception dialog was shown. All in all ... DOOOOH :-) :-)
精彩评论