c# - WPF ComboBox 不会更改所选项目

标签 c# wpf wpf-controls binding

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

[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>

[窗口代码隐藏文件]

    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 是 Category 对象吗?在我看来,您需要绑定(bind) ComboBox 的 SelectedItem 属性。 例如:

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

关于c# - WPF ComboBox 不会更改所选项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3993033/

相关文章:

c# - 具有外键错误复合键的 Entity Framework

c# - 使用 Visual Studio 2013 远程调试在 Linux 上运行的 C# mono 应用程序的最佳方法

c# - TabControl 未找到 TabControl 项的数据模板

c# - Gridview 的 Jquery 和更新面板不起作用

c# - 如何在不添加对类库的引用的情况下访问另一个类库中的 View 模型和项目模型

c# - Task.Run 阻塞主线程(卡住的 UI)

c# - 在基于 MVVM 的应用程序中管理分层对象状态的最佳方法/方法是什么?

c# - 异步图像加载到列表框中

WPF 网页浏览器 : How to set element click event?

wpf - FlowLayoutPanel 的 WPF 等效项是什么?