![](/img/trans.png)
[英]ComboBox ItemsSource binding doesn't update with Observable Collection Add
[英]How come WPF ComboBox ItemsSource Binding doesn't update when set?
我在名為UserInputOutput
的用戶控件中包含以下內容:
<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,但它並不在我的計划組合框中顯示出來。
不知道我在哪里錯了。 有什么想法嗎?
謝謝!
我假設您的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);
}
}
順便說一句,我不知道為什么需要將EnumItems聲明為依賴項屬性。 除非您想將其用作綁定目標(現在將其用作綁定源),否則將其用作類字段會很好地工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.