简体   繁体   中英

WPF Custom control and binding property

I'm working on a custom ListView. In this scope I want to define a custom GridViewColumn that has a CellBinding property which is itself a BindingBase.

This property is defined like this:

public class GridViewColumn : System.Windows.Controls.GridViewColumn
{
    public static readonly DependencyProperty CellBindingProperty = DependencyProperty.RegisterAttached( "CellBinding", typeof( BindingBase ), typeof( GridViewColumn ),
            new PropertyMetadata( null, new PropertyChangedCallback( OnCellBindingChanged ) ) );

    public BindingBase CellBinding
    {
        get => (BindingBase)this.GetValue( CellBindingProperty );
        set => this.SetValue( CellBindingProperty, value );
    }...

All works fine in the xaml editor and this property seems to be recognized correctly:

     <wpfTools:GridViewColumn Header="Titre2" SortProperty="B" CellAlignement="Right" CellBinding="{Binding B}"/>

But when I want to use this property at runtime, the result of column.CellBinding is always null. Please, why?

CellBinding should not be a dependency property if it is supposed to be set to a BindingBase .

You should implement it as a CLR property and then implement your GridViewColumn class to apply the binding to the generated cell element as required:

public class GridViewColumn : System.Windows.Controls.GridViewColumn
{
    private BindingBase _cellBinding;
    public BindingBase CellBinding
    {
        get => _cellBinding;
        set => _cellBinding = value;
    }
    //...
}

Getting the value of a depenendency property evaluates the binding which is not what you want with a BindingBase property.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM