【问题标题】:WPF Binding ProgrammaticallyWPF 以编程方式绑定
【发布时间】:2011-10-22 17:30:00
【问题描述】:

出于各种原因,我正在尝试将此 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# 代码无法编译,我不知道为什么。

【问题讨论】:

  • 为什么代码不能编译?什么错误?

标签: c# wpf xaml data-binding


【解决方案1】:

在PropertyPath 的构造函数中,cell.Width 获取值,如果是 DP,您要么希望 EventCell.ActualWidthProperty 获取 DP 字段,要么使用字符串 "ActualWidth"。

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

Binding b = new Binding("ActualWidth");

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

编辑:另外需要在EventCell.WidthProperty上设置绑定当然不能设置ActualWidth,看来你的逻辑倒过来了……

【讨论】:

  • 仍然给我一个未处理的 XamlParseException。与 b.Path = new PropertyPath(EventCell.WidthProperty);或 b.Path = new PropertyPath("ActualWidth");
  • @xvpower:查看我的编辑(PropertyPath(EventCell.WidthProperty) 是错误的,应该是PropertyPath(EventCell.ActualWidthProperty))
【解决方案2】:

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

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

【讨论】:

  • ActualWidth 可能已经是控件的 DependencyProperty。
  • 啊,原来是这样。在这种情况下,您不需要实现属性更改事件
  • WPF 绑定处理 DependencyProperties 的方式与处理 INotifyPropertyChanged 的​​方式不同(更有效)。因此,如果有 DP,请使用它
猜你喜欢
  • 2016-10-24
  • 2011-05-08
  • 1970-01-01
  • 1970-01-01
  • 2014-04-18
  • 2021-09-06
  • 1970-01-01
  • 2011-02-01
  • 1970-01-01
相关资源
最近更新 更多