代码之家  ›  专栏  ›  技术社区  ›  kmacmahon

silverlight4重写dataformautogenerate以插入绑定到转换器的组合框

  •  4
  • kmacmahon  · 技术社区  · 15 年前

    我创建了一个自定义属性,它修饰了我的MetaDataClass,如下所示:

    [Lookup(Lookup.Products)]
    public Guid ProductId
    

    我正在检查我的CustomAttribute,这很有效。

    在我的CustomDataForm中给出了这段代码(为了简洁起见删除了标准注释),下一步是什么来覆盖字段生成并将绑定的组合框放置在它的位置?

    public class CustomDataForm : DataForm
    {
        private Dictionary<string, DataField> fields = new Dictionary<string, DataField>();
    
        public Dictionary<string, DataField> Fields
        {
            get { return this.fields; }
        }
    
        protected override void OnAutoGeneratingField(DataFormAutoGeneratingFieldEventArgs e)
        {
            PropertyInfo propertyInfo = this.CurrentItem.GetType().GetProperty(e.PropertyName);
    
            foreach (Attribute attribute in propertyInfo.GetCustomAttributes(true))
            {
                LookupFieldAttribute lookupFieldAttribute = attribute as LookupFieldAttribute;
                if (lookupFieldAttribute != null)
                {                    
                    //   Create a combo box.
                    //   Bind it to my Lookup IEnumerable
                    //   Set the selected item to my Field's Value
                    //   Set the binding two way
                }
            }
            this.fields[e.PropertyName] = e.Field;
            base.OnAutoGeneratingField(e);
        }
    }
    

    谢谢

    if (lookupFieldAttribute != null)
    {
        ComboBox comboBox = new ComboBox();
        Binding newBinding = e.Field.Content.GetBindingExpression(TextBox.TextProperty).ParentBinding.CreateCopy();
        newBinding.Mode = BindingMode.TwoWay;
        newBinding.Converter = new LookupConverter(lookupRepository);
        newBinding.ConverterParameter = lookupFieldAttribute.Lookup.ToString();
        comboBox.SetBinding(ComboBox.SelectedItemProperty,newBinding);
        comboBox.ItemsSource = lookupRepository.GetLookup(lookupFieldAttribute.Lookup);                    
        e.Field.Content = comboBox;                    
    }
    
    1 回复  |  直到 14 年前
        1
  •  4
  •   Michael Myers KitsuneYMG    14 年前

    我找到了解决办法。

    if (lookupFieldAttribute != null)
    {
        ComboBox comboBox = new ComboBox();
        Binding newBinding = e.Field.Content.GetBindingExpression(TextBox.TextProperty).ParentBinding.CreateCopy();
        var itemsSource = lookupRepository.GetLookup(lookupFieldAttribute.Lookup);
        var itemsSourceBinding = new Binding { Source = itemsSource };
        comboBox.SetBinding(ItemsControl.ItemsSourceProperty, itemsSourceBinding);
        newBinding.Mode = BindingMode.TwoWay;
        newBinding.Converter = new LookupConverter(lookupRepository);
        newBinding.ConverterParameter = lookupFieldAttribute.Lookup.ToString();
        comboBox.SetBinding(ComboBox.SelectedItemProperty,newBinding);
        e.Field.Content = comboBox;                    
    }