binding to width property in code behind
Asked Answered
A

2

6

I have a situation where I need to create View box with one button. The xaml for this is as below: Please observe Width property of viewbox. The Width should be increased/decreased according to a slider bar(moving to right increases it, to left decreases it). As listed below I know how to do it in xaml and it works fine. But my requirement is to be able to create viewbox in code behind and assign it the properties.

 <WrapPanel x:Name="_wrpImageButtons" Grid.IsSharedSizeScope="True"
           ScrollViewer.CanContentScroll="True" d:LayoutOverrides="Height" 
           Margin="5">
    <Viewbox x:Name="_ScaleButton" 
             Width="{Binding Value, ElementName=ZoomSlider}" Stretch="Fill">
         <CustomButton:_uscVCARSImagesButton x:Name="_btnImage1"/>
    </Viewbox>
 </WrapPanel>

Thanks.

Atom answered 16/5, 2011 at 20:14 Comment(0)
S
8

This should do what you want:

Viewbox x = new Viewbox();
Binding bnd = new Binding("Value") { ElementName = "ZoomSlider"};
BindingOperations.SetBinding(x, Viewbox.WidthProperty, bnd);
// ... Code to insert the Viewbox into the WrapPanel etc.
Superpatriot answered 16/5, 2011 at 20:33 Comment(3)
Wow, i've never seen anyone use BindingOperations.SetBinding.Castilian
I believe it doesn't make any difference, as it resolves to that property anyway.Superpatriot
@H.B. That's how i learned it and what the instance method uses under the hood. :)Superpatriot
H
4

You can create the binding relatively easily in Code Behind:

var widthBinding = new Binding("Value") { ElementName = "ZoomSlider" };

_ScaleButton.SetBinding(FrameworkElement.WidthProperty, widthBinding);
Hydropathy answered 16/5, 2011 at 20:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.