binding to width property in code behind

11,222

Solution 1

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.

Solution 2

You can create the binding relatively easily in Code Behind:

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

_ScaleButton.SetBinding(FrameworkElement.WidthProperty, widthBinding);
Share:
11,222
user296623
Author by

user296623

Updated on June 22, 2022

Comments

  • user296623
    user296623 almost 2 years

    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.

  • H.B.
    H.B. almost 13 years
    Wow, i've never seen anyone use BindingOperations.SetBinding.
  • Botz3000
    Botz3000 almost 13 years
    I believe it doesn't make any difference, as it resolves to that property anyway.
  • Botz3000
    Botz3000 almost 13 years
    @H.B. That's how i learned it and what the instance method uses under the hood. :)