【发布时间】:2011-07-12 18:17:04
【问题描述】:
下面的代码与第二个组合框存在性能问题...当我更改第一个组合框然后打开第二个组合框时它很好。但是,如果我第二次更改第一个组合框并尝试打开 第二个组合框有很多性能问题....
公共部分类 MainWindow :窗口, INotifyPropertyChanged {
public MainWindow()
{
InitializeComponent();
Books = new List<Book>();
Books.Add(new Book("Abc"));
Books.Add(new Book("Cde"));
Books.Add(new Book("Xyz"));
Books.Add(new Book("Min"));
this.DataContext = this;
SelectedBook = Books[0];
}
Book _selctedBook;
public Book SelectedBook
{
get { return _selctedBook; }
set
{
_selctedBook = value;
raiseChange("SelectedBook");
}
}
List<Book> _books = new List<Book>();
public List<Book> Books { get { return _books; } set { _books = value; raiseChange("Books"); } }
void raiseChange(string name)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
public event PropertyChangedEventHandler PropertyChanged;
}
public class Book : INotifyPropertyChanged
{
public string Name { get; set; }
public ObservableCollection<BookType> BookTypes { get; set; }
BookType _selectedBookType;
public BookType SelectedBookType { get { return _selectedBookType; } set { _selectedBookType = value; raiseChange("SelectedBookType"); } }
public Book(string name)
{
Name = name;
BookTypes = new ObservableCollection<BookType>();
if (name == "Abc")
BookTypes.Add(BookType.Action);
BookTypes.Add(BookType.Comedy);
BookTypes.Add(BookType.Drama);
BookTypes.Add(BookType.Friction);
BookTypes.Add(BookType.Thriller);
SelectedBookType = BookTypes[0];
}
void raiseChange(string name)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
public event PropertyChangedEventHandler PropertyChanged;
}
public enum BookType
{
Friction,
Drama,
Action,
Thriller,
Comedy,
}
<Grid>
<Grid.Resources>
<DataTemplate x:Key="ItemTemplate2">
<StackPanel>
<TextBlock Text="{Binding .}"/>
</StackPanel>
</DataTemplate>
</Grid.Resources>
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<ComboBox Height="23" Name="comboBox1" Grid.Row="0"
SelectedItem="{Binding SelectedBook,Mode=TwoWay}"
ItemsSource="{Binding Books}"
DisplayMemberPath="Name"
Width="386" />
<ComboBox Height="23" Name="comboBox2" Grid.Row="1" DataContext="{Binding SelectedItem, ElementName=comboBox1}"
ItemsSource="{Binding BookTypes}" SelectedItem="{Binding SelectedBookType,Mode=TwoWay}"
Width="386" ItemTemplate="{DynamicResource ItemTemplate2}">
</ComboBox>
</Grid>
【问题讨论】:
-
+1 表示有一些很好的示例代码的问题,但是您的示例代码在我的机器上运行良好,完全没有任何性能问题。
-
运行应用程序,将组合框 1 项更改为 xyz.open 组合框 2。现在再次将组合框 1 更改为 Abc 并尝试打开组合框 2 ...注意在下拉菜单打开
-
它对我来说很好用。也许我们的环境有些不同?我正在使用 VS2010 Ultimate、.Net Framework 4.0 和 Windows XP SP3。
-
是实际代码还是您删除了不必要的代码,这可能是访问任何资源(如网络、数据库或任何文件)等真正的问题?
-
我检查了代码,你做的例子没有性能问题。那只能意味着您没有对自己的代码进行正确的抽象。我同意 Akash 的观点,即数据检索可能是罪魁祸首,而您在示例中绕过了这一点。
标签: wpf