Binding objects defined in code-behind

前端 未结 11 1316
难免孤独
难免孤独 2020-11-28 04:29

I have some object that is instantiated in code behind, for instance, the XAML is called window.xaml and within the window.xaml.cs

protected Dictionary

        
11条回答
  •  北荒
    北荒 (楼主)
    2020-11-28 04:55

    Define a converter:

    public class RowIndexConverter : IValueConverter
    {
        public object Convert( object value, Type targetType,
                               object parameter, CultureInfo culture )
        {
            var row = (IDictionary) value;
            var key = (string) parameter;
            return row.Keys.Contains( key ) ? row[ key ] : null;
        }
    
        public object ConvertBack( object value, Type targetType,
                                   object parameter, CultureInfo culture )
        {
            throw new NotImplementedException( );
        }
    }
    

    Bind to a custom definition of a Dictionary. There's lot of overrides that I've omitted, but the indexer is the important one, because it emits the property changed event when the value is changed. This is required for source to target binding.

    public class BindableRow : INotifyPropertyChanged, IDictionary
    {
        private Dictionary _data = new Dictionary( );
    
        public object Dummy   // Provides a dummy property for the column to bind to
        {
            get
            {
                return this;
            }
            set
            {
                var o = value;
            }
        }
    
    
        public object this[ string index ]
        {
            get
            {
                return _data[ index ];
            }
            set
            {
                _data[ index ] = value;
                InvokePropertyChanged( new PropertyChangedEventArgs( "Dummy" ) ); // Trigger update
            }
        }
    
    
    }
    

    In your .xaml file use this converter. First reference it:

    
        
    
    

    Then, for instance, if your dictionary has an entry where the key is "Name", then to bind to it: use

    
    

提交回复
热议问题