【问题标题】:binding to width property in code behind在后面的代码中绑定到宽度属性
【发布时间】:2011-08-26 17:43:16
【问题描述】:

我有一种情况,我需要用一个按钮创建视图框。用于此的 xaml 如下: 请观察 viewbox 的 Width 属性。宽度应根据滑块增加/减少(向右移动增加它,向左移动减少它)。如下所示,我知道如何在 xaml 中执行此操作,并且效果很好。但我的要求是能够在后面的代码中创建视图框并为其分配属性。

 <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>

谢谢。

【问题讨论】:

    标签: wpf binding code-behind


    【解决方案1】:

    您可以在后面的代码中相对轻松地创建绑定:

    var widthBinding = new Binding("Value") { ElementName = "ZoomSlider" };
    
    _ScaleButton.SetBinding(FrameworkElement.WidthProperty, widthBinding);
    

    【讨论】:

      【解决方案2】:

      这应该做你想做的:

      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.
      

      【讨论】:

      • 哇,我从没见过有人用BindingOperations.SetBinding
      • 我相信它没有任何区别,因为它无论如何都会解析为该属性。
      • @H.B.这就是我学习它的方式以及实例方法在后台使用的方式。 :)
      猜你喜欢
      • 2011-02-25
      • 2013-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-07
      • 2011-04-10
      相关资源
      最近更新 更多