2011-03-23 238 views
0

我是WPF中自定义控件开发的新手,但我尝试开发一个在我正在开发的应用程序中使用的控件。此控件是一个自动完成文本框。在这种控制中,我有一个DependencyProprety有可能的条目列表,这样一个人可以从在输入文本WPF自定义控件数据绑定

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"); 
      } 
     } 

我使用该控件在用户控件和该控件的属性在视图模型

关联选择
<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(); 
      } 
     } 

此视图模型具有的DataContext的一个视图模型属性Articles与值但该控件的ItemsSource属性为空,当我尝试在用户输入一些文本后在列表中搜索。 当我创建控件时,是否有任何特殊的步骤让我使用mvvm模式。

我希望以一种可以理解的方式解释问题。任何帮助/提示将受到欢迎。

回答

1

这里有两个问题:

首先,你依赖属性定义这个属性为空“默认”值。您可以通过更改元数据来指定新集合:

public static readonly DependencyProperty ItemsSourceProperty = DependencyProperty.Register("ItemsSource",typeof (IList<object>),typeof (AutoCompleteTextBox), 
    new PropertyMetadata(new List<object>)); 

其次,使用依赖项属性时,setter不能包含任何逻辑。你应该让你的属性设置为:

public IList<object> ItemsSource 
    { 
     get { return (IList<object>) GetValue(ItemsSourceProperty); } 
     set { SetValue(ItemsSourceProperty, value); } 
    } 

这是因为制定者实际上不获取由绑定系统,称为 - 只有当你使用的代码。但是,由于该类是一个DependencyObject,并且这是一个DP,所以不需要引发属性更改的事件。

+0

感谢您的回复,我纠正了两个问题。 – 2011-03-23 17:34:41

+0

现在viewmodel中的属性被调用,但当我调用'wordMatches = ItemsSource.Where(x => x.ToString().ToLower()。StartsWith(Text.ToLower(),StringComparison.InvariantCulture)) .Select x => new KeyValuePair (x.ToString(),x))。ToList();'ItemsSource仍然为null – 2011-03-23 17:36:21