【发布时间】:2019-04-03 19:15:46
【问题描述】:
我有一个绑定到 List<class> 的组合框,其中包含多个类别值。
我使用Binding Path="Name" 显示项目并使用INotifyPropertyChanged。
当我将 Insert() 项目插入 ViewModel 中的 List<Example> Example_Items 时,List 会更新为插入正确索引的项目,但 ComboBox 不会更新显示。
组合框
<ComboBox x:Name="cboExample"
ItemsSource="{Binding Example_Items, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
SelectedIndex="{Binding Example_SelectedIndex, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
SelectedValue="{Binding Example_SelectedItem, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
SelectedValuePath="Name"
Style="{DynamicResource ComboBoxCategoryStyle}"
ItemContainerStyle="{DynamicResource ComboBoxCategoryStyleItem}"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Width="75"
Height="22"
Margin="56,0,0,0"
SelectionChanged="cboExample_SelectionChanged"
>
<ComboBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Margin="0 -7 0 0"/>
</ItemsPanelTemplate>
</ComboBox.ItemsPanel>
<ComboBox.ItemTemplate>
<DataTemplate>
<Grid Width="93">
<TextBlock DataContext="{Binding}">
<TextBlock.Text>
<Binding Path="Name"/>
</TextBlock.Text>
</TextBlock>
</Grid>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
视图模型
public class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged = delegate { };
private void OnPropertyChanged(string prop)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(prop));
}
}
...
// Items Source
public class Example
{
public string Name { get; set; }
public bool Category { get; set; }
}
public List<Example> _Example_Items = new List<Example>()
{
new Example() { Name = "Category 1", Category = true },
new Example() { Name = "Item 1", Category = false },
new Example() { Name = "Item 2", Category = false },
new Example() { Name = "Category 2", Category = true },
new Example() { Name = "Item 3", Category = false },
new Example() { Name = "Item 4", Category = false },
};
public List<Example> Example_Items
{
get { return _Example_Items; }
set
{
_Example_Items = value;
OnPropertyChanged("Example_Items");
}
}
修改组合框项目源
// New Items
List<string> newItemsList = new List<string>()
{
"New Item 5",
"New Item 6",
"New Item 7",
}
// Add New Items to Example Items Source
for (var i = 0; i < newItemsList.Count; i++)
{
vm.Example_Items.Insert(5, new ViewModel.Example() { Name = newItemsList[i], Category = false });
}
【问题讨论】: