我试图在XAML中填充自定义字符串数组,但收到错误.我将一个ComboBox子类化,并添加了一个我想用自定义值填充的字符串[]:
public class MyComboBox : ComboBox
{
public string[] MyProperty { get { return (string[])GetValue(MyPropertyProperty); } set { SetValue(MyPropertyProperty, value); } }
public static readonly DependencyProperty MyPropertyProperty = DependencyProperty.Register("MyProperty", typeof(string[]), typeof(MyComboBox));
}
Run Code Online (Sandbox Code Playgroud)
我的XAML如下:
<Window x:Class="Samples.CustomArrayProperty"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Samples"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
Title="CustomArrayProperty" Height="300" Width="300">
<Grid>
<local:MyComboBox Height="20">
<local:MyComboBox.MyProperty>
<sys:String>Monday</sys:String>
<sys:String>Wednesday</sys:String>
<sys:String>Friday</sys:String>
</local:MyComboBox.MyProperty>
</local:MyComboBox>
</Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)
当我运行它时,我得到错误:"'星期一'不是属性'MyProperty'的有效值.".
我究竟做错了什么?
Kri*_*is 8
您可以使用x:Array在XAML中创建数组,您仍然需要将其用作Liz的答案之类的资源.
<Window.Resources>
<x:Array Type="sys:String" x:Key="days">
<sys:String>Monday</sys:String>
<sys:String>Wednesday</sys:String>
<sys:String>Friday</sys:String>
</x:Array>
</Window.Resources>
Run Code Online (Sandbox Code Playgroud)
<local:MyComboBox Height="23" MyProperty="{StaticResource days}" />
Run Code Online (Sandbox Code Playgroud)
除了您在这里所做的之外,还有其他原因对 ComboBox 进行子类化吗?
因为如果想法只是向组合框提供字符串列表,那么请查看“将集合或数组添加到 wpf 资源字典”
尽可能让组合框自行处理会更好 - 通过使用 ItemsSource 属性。因此,我们在链接示例中所做的是提供一个包含字符串列表的“资源”,然后将此资源传递给 ItemsSource,如下所示:
<ComboBox ItemsSource="{StaticResource stringList}" />
Run Code Online (Sandbox Code Playgroud)
定义一个这样的类型:
public class StringList : List<string> { }
Run Code Online (Sandbox Code Playgroud)
然后创建静态资源
<Window.Resources>
<local:StringList x:Key="stringList">
<sys:String>Monday</sys:String>
<sys:String>Wednesday</sys:String>
<sys:String>Friday</sys:String>
</local:StringList >
</Window.Resources>
Run Code Online (Sandbox Code Playgroud)
我希望这有帮助。
编辑:您还可以更改 DependencyProperty 以使用 StringList 而不是 String[],那么您的依赖属性也将起作用。
<local:MyComboBox MyProperty="{StaticResource stringList}" Height="23" />
Run Code Online (Sandbox Code Playgroud)
然后是依赖属性:
public static readonly DependencyProperty MyPropertyProperty = DependencyProperty.Register("MyProperty",typeof(StringList),typeof(MyComboBox),new FrameworkPropertyMetadata(null, listChangedCallBack));
static void listChangedCallBack(DependencyObject property, DependencyPropertyChangedEventArgs args)
{
ComboBox combo = (ComboBox)property;
combo.ItemsSource= (IEnumerable)args.NewValue;
}
Run Code Online (Sandbox Code Playgroud)
那么这将有效地完成与直接绑定到 ItemsSource 相同的事情。但如果我理解正确的话,最重要的是让 Dependency 属性发挥作用。