WPF绑定以编程方式

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

   

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

 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#代码无法编译,我很遗憾为什么。

PropertyPath的构造函数中, cell.Width获取值,您希望EventCell.ActualWidthProperty获取DP字段(如果它是DP),或使用字符串"ActualWidth"

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

 Binding b = new Binding("ActualWidth"); 

(如果你的绑定被翻译回XAML,它将类似于{Binding Path=123.4, ...} ,请注意Path属性是合格的,因为你没有使用构造函数来设置它)

编辑:还需要在EventCell.WidthProperty上设置EventCell.WidthProperty ,当然,你不能设置ActualWidth ,看来你的逻辑被颠倒了……

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

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