以编程方式绑定 WPF [英] WPF Binding Programmatically

查看:30
本文介绍了以编程方式绑定 WPF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于各种原因,我正在尝试将此 xaml 绑定转换为它的 C# 对应项:

I am attempting to convert this xaml binding to it's C# counterpart for various reasons:

<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>

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

I've read a lot of questions already that had similar problems and came up with this code:

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# 代码无法编译,我很不明白为什么.

But the C# code won't compile, I am pretty lost as to why.

推荐答案

PropertyPath的构造函数中cell.Width得到值,你要么想要EventCell.ActualWidthProperty 获取 DP 字段,如果它是 DP,或者使用字符串,"ActualWidth".

In the constructor of the PropertyPath the cell.Width gets the value, you either want EventCell.ActualWidthProperty to get the DP-field if it is a DP, or use the string, "ActualWidth".

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

When translating XAML like this, just set the path in the Binding constructor which is the same constructor used in XAML (as the path is not qualified):

Binding b = new Binding("ActualWidth");

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

(If your binding were to be translated back to XAML it would be something like {Binding Path=123.4, ...}, note that the Path property is qualified as you did not use the constructor to set it)

当然也需要在EventCell.WidthProperty上设置绑定,你不能设置ActualWidth,看来你的逻辑颠倒了...

Also the binding needs to be set on the EventCell.WidthProperty of course, you cannot set the ActualWidth, it seems your logic was inverted...

这篇关于以编程方式绑定 WPF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆