MKII
MKII

Reputation: 911

How to use Binding in code?

I have been trying to create a Data Binding so that a WrapPanel automatically resizes horizontally to match it's container (a StackPanel) when the window is resized, to no success.

I started to search how to do it, and at I arrived to this

    Binding SomeBinding = new Binding ();
    SomeBinding.Source = SomeEntry;
    SomeBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
    SomeBinding.Path = new PropertyPath ("Width");
    SomeBinding.Mode = BindingMode.OneWay;
    SomeStackPanel.SetBinding (StackPanel.WidthProperty, SomeBinding);

But it doesn't do anything when the window is resized. I looked at examples, but I don't really see the issue. Can someone explain what is wrong with the above snippet?

Upvotes: 1

Views: 79

Answers (2)

almulo
almulo

Reputation: 4978

You've said you want your WrapPanel to resize horizontally inside the StackPanel. That's possible depending on what your StackPanel's Orientation is.

If your StackPanel's Orientation is Vertical, then its just a matter of setting HorizontalAlignment="Stretch" on your WrapPanel.

<StackPanel Orientation="Vertical">
    <WrapPanel HorizontalAlignment="Stretch" />
</StackPanel>

Or since you're doing it programmatically, for what it seems...

var wrapPanel = new WrapPanel();
myStackPanel.Children.Add(wrapPanel);
wrapPanel.HorizontalAlignment = HorizontalAlignment.Stretch;

If your StackPanel's Orientation is Horizontal, then there's no way you're gonna be able to make your WrapPanel resize correctly in that direction.

Upvotes: 1

wezten
wezten

Reputation: 2296

StackPanel do not expand to the size of their containers - they are the size of their contents. So if the WrapPanel is linked to StackPanel.Width, nothing will happen as the window grows.

You are probably looking for something else instead of a StackPanel - try to use a Grid.

Upvotes: 3

Related Questions