binding to width property in code behind

笑着哭i 提交于 2020-01-20 06:04:05

问题


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.


回答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.



回答2:


You can create the binding relatively easily in Code Behind:

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

_ScaleButton.SetBinding(FrameworkElement.WidthProperty, widthBinding);


来源:https://stackoverflow.com/questions/6022782/binding-to-width-property-in-code-behind

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!