我是WPF的新手,所以它可能是一些非常基本的東西,我忘了做,但我看不到它是什麼。WPF組合框不會改變選定的項目
我有一個窗口顯示一些數據的組合框,我希望用戶在此組合框中選擇一個類別。它正在部分工作。窗口顯示組合框,從沒有選擇開始,然後用戶選擇一個項目,並設置它,但如果用戶嘗試更改爲其他項目,則無效,它會保留原始選定項目。
這裏是我的代碼:
[類別類]
public class Category {
public long CategoryId { get; set; }
public string Name { get; set; }
public Category MotherCategory { get; set; }
public ICollection<Category> Categories { get; set; }
public int Align { get; set; }
}
[組合框XAML]
<ComboBox Grid.Column="1" x:Name="motherCategoryComboBox" Margin="0,6,12,1"
IsSynchronizedWithCurrentItem="True">
<ComboBox.Resources>
<converter:LeftMarginConverter x:Key="LeftMarginConverter" />
</ComboBox.Resources>
<ComboBox.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Path=Categories}">
<TextBlock Text="{Binding Path=Name}" Margin="{Binding Path=Align, Converter={StaticResource LeftMarginConverter}}" />
</HierarchicalDataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
[窗口代碼隱藏文件]
public CategoryWindow()
{
InitializeComponent();
db = new JaspeContext();
categorieslist = db.Categories.ToList();
motherCategoryComboBox.ItemsSource = categorieslist;
Title = "Add category";
}
[轉換器]
public class LeftMarginConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
double leftMargin = double.Parse(value.ToString());
if (leftMargin != 1)
leftMargin = leftMargin * 9;
return new Thickness(leftMargin, 0, 0, 0);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new Exception("The method or operation is not implemented.");
}
}
需要你的幫助。這讓我瘋狂!
謝謝!
我沒有設置DataContext,我將列表直接傳遞給ComboBox的ItemSource屬性。 –
Alaor
2010-10-22 10:46:14
對不起,我接受了你的回答,但我發現行爲的起源更加模糊。我覆蓋了類別的Equals方法,然後它在組合框中造成奇怪的事情。 – Alaor 2010-10-22 22:26:42
而ps:我想要自殺。 – Alaor 2010-10-22 22:27:21