我是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.");
}
}
需要你的帮助。这让我发疯了!
谢谢!
答案 0 :(得分:4)
我希望我能正确理解你的问题。您的DataContext是Category对象吗?听起来像你需要绑定ComboBox的SelectedItem
属性。
E.g:
<ComboBox Grid.Column="1" x:Name="motherCategoryComboBox" Margin="0,6,12,1"
IsSynchronizedWithCurrentItem="True" SelectedItem="{Binding MotherCategory , Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
答案 1 :(得分:0)
这不是你的情况,但是因为它发生在我身上,我在这里发布这个,以帮助其他可能偶然发现这个问题的人......
在comboBox
SelectionChangeCommitted()
事件处理程序中,我添加了以下行:
combobox.Text = combobox.Text.Trim();
它所做的是重置selectedIndex
和selectedText
属性,并且由于键盘或鼠标输入而不允许它们更改为新值。