gpt4 book ai didi

c# - WPF 以编程方式绑定(bind)

转载 作者:IT王子 更新时间:2023-10-29 04:49:26 25 4
gpt4 key购买 nike

出于各种原因,我正在尝试将此 xaml 绑定(bind)转换为其对应的 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# 代码无法编译,我完全不知道为什么。

最佳答案

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

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

Binding b = new Binding("ActualWidth");

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

编辑: 还需要在 EventCell.WidthProperty 上设置绑定(bind),当然,您不能设置 ActualWidth,看来您的逻辑颠倒了...

关于c# - WPF 以编程方式绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6988273/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com