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

查看:66
本文介绍了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时,只需在Binding构造函数中设置路径即可,该构造函数用于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天全站免登陆