WPF ComboBox不会更改所选项目

Ala*_*aor 2 c# wpf binding wpf-controls

我是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; }
}
Run Code Online (Sandbox Code Playgroud)

[ComboBox 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>
Run Code Online (Sandbox Code Playgroud)

[窗口代码隐藏文件]

    public CategoryWindow()
    {
        InitializeComponent();

        db = new JaspeContext();
        categorieslist = db.Categories.ToList();

        motherCategoryComboBox.ItemsSource = categorieslist;

        Title = "Add category";
    }
Run Code Online (Sandbox Code Playgroud)

[转换器]

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.");
    }
}
Run Code Online (Sandbox Code Playgroud)

需要你的帮助。这让我发疯!

谢谢!!

laz*_*azo 5

希望我能正确理解您的问题。您的DataContext是Category对象吗?在我看来,您需要绑定SelectedItemComboBox 的属性。例如:

<ComboBox Grid.Column="1" x:Name="motherCategoryComboBox" Margin="0,6,12,1"
IsSynchronizedWithCurrentItem="True" SelectedItem="{Binding MotherCategory , Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
Run Code Online (Sandbox Code Playgroud)