我正在尝试将我的一个用户控件中的DependancyProperty
绑定到Grid
中Column
的Width
属性。
我的代码类似于这样:
<Grid x:Name="MyGridName">
<Grid.ColumnDefinitions>
<ColumnDefinition x:Name="TitleSection" Width="100" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>...</Grid.RowDefinitions>
<GridSplitter x:Name="MyGridSplitter" Grid.Row="0" Grid.Column="0" ... />
</Grid>
在一个独立的Usercontrol中,我定义了以下的
DependancyProperty
。public static readonly DependencyProperty TitleWidthProperty = DependencyProperty.Register("TitleWidth", typeof(int), typeof(MyUserControl));
public int TitleWidth
{
get { return (int)base.GetValue(TitleWidthProperty); }
set { base.SetValue(TitleWidthProperty, value); }
}
我正在编写代码创建用户控件实例,因此我有一个类似于以下绑定语句:
MyUserControl Cntrl = new MyUserControl(/* Construction Params */);
BindingOperations.SetBinding(Cntrl , MyUserControl.AnotherProperty, new Binding { ElementName = "objZoomSlider", Path = new PropertyPath("Value"), Mode = BindingMode.OneWay });
BindingOperations.SetBinding(Cntrl , MyUserControl.TitleWidthProperty, new Binding { ElementName = "TitleSection", Path = new PropertyPath("ActualWidth"), Mode = BindingMode.OneWay });
/* Other operations on Cntrl */
第一个定义的绑定非常有效,虽然它是绑定到实际的UIElement(在这种情况下是Slider),但是对“TitleSection”进行的绑定(这是在Grid中定义的ColumnDefinition)失败了。在代码中设置断点并在“TitleSection”上进行监视会返回预期的对象。
我开始怀疑x:Name'd ColumnDefinition不能被绑定。有人能建议我如何能够绑定到网格中第一列的可变宽度吗?
编辑#1 - 回答评论
数据绑定“失败”的意思是,在
TitleWidth
属性的setter上设置断点,并使用GridSplitter控件调整第一列的大小时,断点永远不会命中。此外,当DependancyProperty TitleWidth
更改时,我希望执行的代码也没有被执行。用户控件在
Window_Loaded
函数中创建并添加到Grid中的Stackpanel中。我希望在构建Usercontrols时,Grid已经被渲染出来。当它们正在构建/绑定发生之前,肯定可以监视到x:Name'd元素TitleSection
并且其值为100
。编辑#2 - 可能与此有关?
我一直在 MSDN 页面上查找 Grid ColumnDefinition 文档,并发现了 GridLength(),但我不知道如何在绑定表达式中使用它。我无法在绑定代码中使用相关的 GridLengthConverter 作为转换器,因为它不是从 IValueConverter 派生的。
我正在考虑以某种方式绑定到 Grid 对象中一个单元格的 ActualWidth 属性。这似乎不如绑定到列定义干净,但目前我无法让其正常工作。