WPF绑定以编程方式自定义组合框

编程入门 行业动态 更新时间:2024-10-25 18:24:17
本文介绍了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绑定以编程方式自定义组合框

本文发布于:2023-11-28 07:35:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1641496.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组合   自定义   绑定   方式   WPF

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!