Binding in WPF to element of array specified by property

前端 未结 3 1246
名媛妹妹
名媛妹妹 2020-11-30 01:54

Say I\'ve got some TextBlocks on my UI, something like so:


    

        
3条回答
  •  情歌与酒
    2020-11-30 02:28

    Another alternative is to use MultiBinding with a converter:

    
        
            
                
            
            
            
            
                    
                        
                            
                            
                        
                    
            
        
    
    

    Then in the code-behind, the converter is defined something like this:

    namespace WpfApplication1
    {
        public class FoodIndexConverter : IMultiValueConverter
        {
            public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            {
                if (values == null || values.Length != 2)
                    return null;
    
                int? idx = values[0] as int?;
                object[] food = values[1] as object[];
    
                if (!idx.HasValue || food == null)
                    return null;
    
                return food[idx.Value];
            }
    
            public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
            {
                throw new NotImplementedException();
            }
        }
    }
    

提交回复
热议问题