[英]WPF custom control databinding
我是WPF中自定义控件开发的新手,但是我尝试开发一个用于正在开发的应用程序中的控件。 此控件是一个自动完成的文本框。 在此控件中,我有一个DependencyProprety
,其中包含可能的条目的列表,以便人们在输入文本时可以选择
public static readonly DependencyProperty ItemsSourceProperty = DependencyProperty.Register("ItemsSource",typeof (IList<object>),typeof (AutoCompleteTextBox),new PropertyMetadata(null));
public IList<object> ItemsSource
{
get { return (IList<object>) GetValue(ItemsSourceProperty); }
set
{
SetValue(ItemsSourceProperty, value);
RaiseOnPropertyChanged("ItemsSource");
}
}
我在用户控件中使用此控件,并将此控件与viewmodel中的属性相关联
<CustomControls:AutoCompleteTextBox Height="23" Width="200"
VerticalAlignment="Center" Text="{Binding Path=ArticleName, Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged}" ItemsSource="{Binding Path=Articles,
Mode=OneWay, UpdateSourceTrigger=PropertyChanged}">
</CustomControls:AutoCompleteTextBox>
我有一个在用户控件负载上分配给用户控件负载的数据上下文的视图模型
protected virtual void Window_Loaded(object sender, RoutedEventArgs e)
{
if (!DesignerProperties.GetIsInDesignMode(this))
{
this.DataContext = viewModel;
SetLabels();
}
}
当我尝试在用户输入一些文本后在列表中进行搜索时,此视图模型具有带有值的属性Articles
,但控件的ItemsSource
属性为null。 创建控件时是否错过了任何特殊步骤,因此请使用mvvm模式。
我希望以一种可以理解的方式解释问题。 任何帮助/提示都将受到欢迎。
这里有两个问题:
首先,您的dependency属性是将该属性的“默认”值定义为null。 您可以通过更改元数据以指定新集合来更改此设置:
public static readonly DependencyProperty ItemsSourceProperty = DependencyProperty.Register("ItemsSource",typeof (IList<object>),typeof (AutoCompleteTextBox),
new PropertyMetadata(new List<object>));
其次,在使用依赖项属性时,设置器不能包含任何逻辑。 您应该将属性设置为:
public IList<object> ItemsSource
{
get { return (IList<object>) GetValue(ItemsSourceProperty); }
set { SetValue(ItemsSourceProperty, value); }
}
这是因为绑定器实际上不会调用绑定器-仅在使用代码时才调用。 但是,由于该类是DependencyObject且这是一个DP,因此不需要引发属性更改的事件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.