2010-10-22 64 views
2

我是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."); 
    } 
} 

需要你的幫助。這讓我瘋狂!

謝謝!

回答

3

我希望我能正確理解你的問題。你的DataContext是一個Category對象嗎?聽起來像你需要綁定ComboBox的SelectedItem屬性。 如:

<ComboBox Grid.Column="1" x:Name="motherCategoryComboBox" Margin="0,6,12,1" 
IsSynchronizedWithCurrentItem="True" SelectedItem="{Binding MotherCategory , Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"> 
+0

我沒有設置DataContext,我將列表直接傳遞給ComboBox的ItemSource屬性。 – Alaor 2010-10-22 10:46:14

+0

對不起,我接受了你的回答,但我發現行爲的起源更加模糊。我覆蓋了類別的Equals方法,然後它在組合框中造成奇怪的事情。 – Alaor 2010-10-22 22:26:42

+0

而ps:我想要自殺。 – Alaor 2010-10-22 22:27:21

0

這不是你的情況,但因爲它發生在我身上,我在這裏發佈此,以幫助在這個問題上誰可能絆倒別人......

comboBoxSelectionChangeCommitted()事件處理程序我添加了以下行:

combobox.Text = combobox.Text.Trim(); 

它沒有什麼復位selectedIndexselectedText性質,並沒有讓他們更改爲新的值,由於鍵盤或鼠標我NPUT。

+0

如果你這樣做,在你真正選擇它的時候,是不是會影響下拉菜單中顯示的結果? – vapcguy 2017-03-01 17:34:32