2011-03-23 232 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