我是 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/