WPF控件(绑定到视图模型上的列表的属性)想要在Xaml中定义列表

我一直在使用WPF UI控件。

我定义了一个依赖项属性,它是一个字符串列表。

这将按预期与视图模型上的列表属性绑定。

我想做的是可以选择在XAML中定义列表,而不是绑定到视图模型上的列表。

<local:MyControl MyList = "one,two,three">

控件上的MyList属性。

public static readonly DependencyProperty MyListProperty =
            DependencyProperty.Register("MyList",typeof(List<string>),typeof(MyControl));
qqcoboo 回答:WPF控件(绑定到视图模型上的列表的属性)想要在Xaml中定义列表

为了支持从包含逗号分隔元素的字符串中初始化列表,例如

MyList="one,two,three"

您将注册自定义TypeConverter

请注意,下面的代码使用IList<string>作为属性类型,这为可分配给该属性的类型提供了更大的灵活性,从而简化了TypeConverter的实现(返回string[])。

>
public partial class MyControl : UserControl
{
    public static readonly DependencyProperty MyListProperty =
        DependencyProperty.Register(
            nameof(MyList),typeof(IList<string>),typeof(MyControl));

    [TypeConverter(typeof(StringListConverter))]
    public IList<string> MyList
    {
        get { return (IList<string>)GetValue(MyListProperty); }
        set { SetValue(MyListProperty,value); }
    }
}

public class StringListConverter : TypeConverter
{
    public override bool CanConvertFrom(
        ITypeDescriptorContext context,Type sourceType)
    {
        return sourceType == typeof(string);
    }

    public override object ConvertFrom(
        ITypeDescriptorContext context,CultureInfo culture,object value)
    {
        return ((string)value).Split(
            new char[] { ',',' ' },StringSplitOptions.RemoveEmptyEntries);
    }
}
本文链接:https://www.f2er.com/3149734.html

大家都在问