2012-08-29 82 views
1

我有一個用戶控件內以下稱爲UserInputOutput如何設置WPF組合框ItemsSource綁定不更新?

<ComboBox Grid.Column="1" Background="White" Visibility="{Binding InputEnumVisibility}"  
      FontSize="{Binding FontSizeValue}" Width="Auto" Padding="10,0,5,0"  
      ItemsSource="{Binding EnumItems}"  
      SelectedIndex="{Binding EnumSelectedIndex}"/>  

我這裏有幾個綁定它除了所有的ItemsSource工作的偉大。這是我的依賴屬性和公共變量。

public ObservableCollection<String> EnumItems 
{ 
    get { return (ObservableCollection<String>)GetValue(EnumItemsProperty); } 
    set { SetValue(EnumItemsProperty, value); } 
} 

public static readonly DependencyProperty EnumItemsProperty = 
    DependencyProperty.Register("EnumItems", typeof(ObservableCollection<string>),typeof(UserInputOutput) 

除ComboBox的ItemSource外,所有綁定都在XAML中設置。這必須在運行時設置。在我的代碼中,我使用以下代碼:

ObservableCollection<string> enumItems = new ObservableCollection<string>(); 
UserInputOutput.getEnumItems(enumItems, enumSelectedIndex, ui.ID, ui.SubmodeID); 
instanceOfUserInputOutput.EnumItems = enumItems; 

我從文件加載XAML後運行此代碼。 instaceOfUserInputOutput.EnumItems包含正確的項目,我將它設置爲enumItems後,但它不顯示在我的程序組合框中。

不知道我在哪裏錯了。有什麼想法嗎?

謝謝!

回答

0

我假設您的ViewModel類(用作綁定源的類)實現INotifyPropertyChanged接口。否則,更新將不起作用。

然後,在你的setter方法,這樣做:

set 
{ 
    // set whatever internal properties you like 
    ... 

    // signal to bound view object which properties need to be refreshed 
    OnPropertyChanged("EnumItems"); 
} 

其中OnProperyChanged方法是這樣的:

protected void OnPropertyChanged(string propertyName) 
{ 
    PropertyChangedEventHandler handler = this.PropertyChanged; 
    if (handler != null) 
    { 
     var e = new PropertyChangedEventArgs(propertyName); 
     handler(this, e); 
    } 
} 

BTW,我不知道爲什麼你需要聲明EnumItems作爲依賴項屬性。將它作爲類字段可以很好地工作,除非您想將其用作綁定的目標(現在它被用作綁定源)。

+0

我不得不使用依賴性屬性,因爲我的UserControl中的元素不能有Name字段。如果我不能使用名稱字段,那麼我不能訪問沒有使用其他方法的ItemsSource。您在代碼中看到的其他依賴屬性完美無缺。 –

+0

另外,我目前沒有實現你提到的接口。我只是繼承了UserControl。 –

+0

@ B-Rad,如果你想通過綁定填充一些控件,你必須實現INotifyPropertyChanged接口,否則更新將不起作用。其他綁定可能會在實例化時設置,並且在對象處於活動狀態時不會更改。 –