绑定到属性在CodeBehind中不起作用,但在xaml中起作用

时间:2018-11-14 17:56:18

标签: c# wpf xaml binding

我需要使不同网格中的列相互依赖地移动。我找到了一个好的解决方案:

  1. 在属性中创建值 enter image description here
  2. 在xamlI中创建绑定:
 <Grid.ColumnDefinitions>
    <ColumnDefinition 
        Width="{Binding Source={x:Static properties:Settings.Default}, Path=GridColumnWidth,
        Converter={StaticResource ColumnWidthConverter}, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
        MinWidth="50"></ColumnDefinition>
    <ColumnDefinition Width="Auto"></ColumnDefinition>
    <ColumnDefinition Width="*" MinWidth="50"></ColumnDefinition>
</Grid.ColumnDefinitions>
  1. 并实现转换器:
public class ColumnWidthConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is string str && !str.Equals("*"))
            return new GridLength(double.Parse(str));
        return new GridLength(1, GridUnitType.Star);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is GridLength gridLength)
            return gridLength.Value.ToString(CultureInfo.InvariantCulture);
        return "*";
    }
}

现在,我需要在CodeBehind中执行相同的操作。我这样做:

ColumnDefinition propertyNameColumnDefinition = new ColumnDefinition();
propertyNameColumnDefinition.MinWidth = 50;
BindingOperations.SetBinding(propertyNameColumnDefinition, WidthProperty, CreateBindingForColumnWidth());
ColumnDefinition gridSplitterColumnDefinition = new ColumnDefinition() { Width = GridLength.Auto };
ColumnDefinition propertyValueColumnDefinition = new ColumnDefinition();
propertyValueColumnDefinition.MinWidth = 50;
grid.RowDefinitions.Add(headerRowDefinition);
grid.ColumnDefinitions.Add(propertyNameColumnDefinition);
grid.ColumnDefinitions.Add(gridSplitterColumnDefinition);
grid.ColumnDefinitions.Add(propertyValueColumnDefinition);
.......
private Binding CreateBindingForColumnWidth()
{
    Binding b = new Binding
    {
        Source = mpESKD.Properties.Settings.Default,
        Path = new PropertyPath("GridColumnWidth"),
        Mode = BindingMode.TwoWay,
        UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged,
        Converter = new ColumnWidthConverter()
    };
    return b;
}

在这种情况下,没有任何效果。 我在做什么错了?

1 个答案:

答案 0 :(得分:0)

必须是:

BindingOperations.SetBinding(propertyNameColumnDefinition, ColumnDefinition.WidthProperty, CreateBindingForColumnWidth());

感谢 ASh 的评论