WPF绑定以编程方式

xvp*_*wer 18 c# data-binding wpf xaml

我试图将这个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>
Run Code Online (Sandbox Code Playgroud)

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

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);
Run Code Online (Sandbox Code Playgroud)

但是C#代码不能编译,我很遗憾为什么.

H.B*_*.B. 21

在的构造函数PropertyPathcell.Width得到值,你要么希望EventCell.ActualWidthProperty得到DP-场,如果它是一个DP,或使用字符串"ActualWidth".

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

Binding b = new Binding("ActualWidth");
Run Code Online (Sandbox Code Playgroud)

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

编辑:还需要设置绑定EventCell.WidthProperty当然,你不能设置ActualWidth,似乎你的逻辑被颠倒了...