WPF绑定以编程方式自定义组合框 [英] WPF binding programmatiically custom combobox

查看:90
本文介绍了WPF绑定以编程方式自定义组合框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个自定义组合框以在wpf中使用.在xaml中执行此操作无效.如果我将其设置为用户控件,则可以执行此操作,但是我正尝试从combobox本身继承.

然后,我尝试以编程方式这样做:

I''m trying to create a custom combobox to use in wpf. Doing it in xaml didn''t work. I can do it if I make it a user control but I''m trying to inherit from combobox itself.

I then tried doing it programmatically like this:

using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;

public class customcombobox:ComboBox
{
    public customcombobox()
    {
        Binding binding = new Binding();
        binding.Source = somefunction(); //returns a list
        binding.Converter = new Converter(); //converts the data
        this.SetBinding(ComboBox.ItemsSourceProperty, binding);
    }
}



我在xaml中收到一个错误消息,告诉我无法创建实例.



I get an error in the xaml telling me I cannot create an instance.

推荐答案

问题是您正在尝试在控件初始化之前对其进行修改. .要使其正常工作,您要做的就是让构造函数从基类继承:

The problem is that you''re attempting to modify the control before it has been initialized. To get it to work all you have to do is have the constructor inherit from the base class:

public customcombobox() : base()
{
    Binding binding = new Binding();
    binding.Source = somefunction(); //returns a list
    binding.Converter = new Converter(); //converts the data
    this.SetBinding(ComboBox.ItemsSourceProperty, binding);
}


我发现了我的问题.不需要让构造函数从它说是多余的基础上继承.问题出在我的转换器上.我在代码的其他地方使用了相同的转换器,但是在xaml中使用它时,它不会作为列表发送,而是发送列表中的每个项目,然后进行转换并返回.

在这种情况下,转换器实际上将其作为列表发送.我需要让转换器检查它是否为列表并返回转换后的列表.

我在这里寻找答案. 使用转换器在ListView中聚合列表 [< ^ ]

我的代码最终是这样的.

I figured out my problem. Didn''t need to have the constructor inherit from the base it said it was redundant. The problem was actually in my converter. I use the same converter elsewhere in my code but when using it in the xaml it doesn''t send it as a list it sends each individual item in the list and converts and returns.

In this case the converter actually sends it in as a list. I needed to have the converter check if it was a list and return a converted list.

I looked here to work out my answer. Using converters to aggregate a list in a ListView[^]

My code ended up being something like this.

Type ValueType = value.GetType();
if (ValueType.Name == typeof(List<>).Name) // Check if we're dealing with a list
{
    List<String> dummy= new List<string>();  //create a new list to return
    foreach (var item in (IList)value //iterate through the list
    {
        //calling a function to convert data and add it to the list
        dummy.Add(somefunction((ItemType)item));
    }
    //return the new list
    return dummy;
}


这篇关于WPF绑定以编程方式自定义组合框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆