WPF contextMenu 有一个关于更新 UI 的奇怪问题!
基本上,我创建了一个名为 World 的分层列表。此列表包含国家,每个国家都包含城市。我将此列表绑定到标签 contextMenu。
我创建了一个按钮,用于删除该列表中的一个城市。
这里的代码
`
<Window.Resources>
<HierarchicalDataTemplate DataType="{x:Type local:Country}" ItemsSource="{Binding Path=ListCity}">
<TextBlock Text="{Binding Path=NameCountry}"/>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="{x:Type local:City}">
<TextBlock Text="{Binding Path=NameCity}"/>
</HierarchicalDataTemplate>
</Window.Resources>
<Grid>
<Button x:Name="btnDelete_London" Click="btnDelete_London_Click" VerticalAlignment="Top">Del London</Button>
<Label x:Name="label_World" Content="WORLD" VerticalAlignment="Bottom" HorizontalAlignment="Center" Background="Aqua"/>
</Grid>
`后面的代码
public class Country
{
public string NameCountry { get; set; }
public List<City> ListCity { get; set; }
}
public class City
{
public string NameCity { get; set; }
}
public partial class MainWindow : Window
{
List<Country> World = new List<Country>();
Country USA = new Country();
Country UK = new Country();
City NY = new City();
City LA = new City();
City LD = new City();
public MainWindow()
{
InitializeComponent();
USA.NameCountry = "United-Sates";
UK.NameCountry = "United Kingdom";
NY.NameCity = "New-York";
LA.NameCity = "Los Angeles";
LD.NameCity = "London";
USA.ListCity = new List<City>();
USA.ListCity.Add(NY);
USA.ListCity.Add(LA);
UK.ListCity = new List<City>();
UK.ListCity.Add(LD);
World.Add(USA);
World.Add(UK);
this.label_World.ContextMenu= new ContextMenu();
this.label_World.ContextMenu.ItemsSource = World;
}
private void btnDelete_London_Click(object sender, RoutedEventArgs e)
{
bool finded = false;
foreach (Country country in World)
{
foreach (City city in country.ListCity)
{
if (city.NameCity == "London")
{
country.ListCity.Remove(city);
finded = true;
break;
}
}
if(finded ) break;
}
CollectionViewSource.GetDefaultView(label_World.ContextMenu.ItemsSource).Refresh();
}
}
如果在开始时单击按钮,然后右键单击标签,contextMenu 将与更新的数据一起显示(即删除了伦敦)
UI更新的问题出现在开始时您首先右键单击使contextMenu显示的标签。然后单击窗口中的某处使 contextMenu 消失。然后,如果您单击按钮,伦敦城市将被删除。现在,当您右键单击标签时,contextMenu 会出现 Country Item 而不是他们的城市 Subitems