WPF绑定以编程方式

时间:2011-08-08 20:41:18

标签: c# wpf xaml data-binding

我试图将这个xaml绑定转换为它的C#对应物有各种原因:

<ListView x:Name="eventListView" Grid.Column="0" Grid.Row="1" Background="LightGray" BorderThickness="0">
    <local:EventCell x:Name="cell" Width="{Binding ActualWidth, Converter={StaticResource ListViewWidthConverter}, ElementName=eventListView, Mode=OneWay}"/>
</ListView>

我已经阅读了很多有类似问题的问题并想出了这段代码:

Binding b = new Binding();
b.Source = eventListView;
b.Path = new PropertyPath(cell.Width);
b.Converter = new ListViewWidthConverter();
b.Mode = BindingMode.OneWay;
cell.SetBinding(ListView.ActualWidthProperty, b);

但C#代码无法编译,我很遗憾为什么。

2 个答案:

答案 0 :(得分:21)

PropertyPath的构造函数中cell.Width获取值,您要么EventCell.ActualWidthProperty获取DP字段(如果它是DP),或者使用字符串{{ 1}}。

当像这样翻译XAML时,只需在Binding构造函数中设置路径,该构造函数与XAML中使用的构造函数相同(因为路径不合格):

"ActualWidth"

(如果您的绑定要转换回XAML,那将类似于Binding b = new Binding("ActualWidth"); ,请注意{Binding Path=123.4, ...}属性是合格的,因为您没有使用构造函数来设置它

编辑:此外需要在Path上设置绑定,当然,您无法设置EventCell.WidthProperty,看来您的逻辑已被反转......

答案 1 :(得分:0)

我相信你需要让ActualWidthProperty抛出一个NotifyPropertyChanged事件。否则,绑定将不知道在属性更改时更新。每当我完成绑定时,我总是必须实现INotifyPropertyChanged

您可以尝试扩展列表视图类,然后在width属性上实现它。我在这里给出了类似的答案:WPF Toolkit DataGrid column resize event

相关问题