我有一个奇怪的问题,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就会与更新的数据一起出现(即伦敦已删除)
首次右键单击显示contextMenu的标签时,会出现UI更新的问题。然后单击窗口中的某个位置以使contextMenu消失。然后,如果您单击按钮,伦敦城市将被删除。现在,当您右键单击标签时,contextMenu将显示国家/地区项目,但不会显示其城市子项目
答案 0 :(得分:1)
看起来您正在将ContextMenu ItemsSource设置为World的副本,而不是将其绑定到您后面的代码中创建的World实例。
要将其设置为绑定,请在构造函数中使用此代码:
this.label_World.ContextMenu = new ContextMenu();
Binding worldBinding = new Binding();
worldBinding.Source = World;
this.label_World.ContextMenu.SetBinding(ContextMenu.ItemsSourceProperty, worldBinding);
这将设置绑定,但默认情况下List<T>
在对象更改时不会通知UI。将List<T>
替换为System.Collections.ObjectModel.ObservableCollection<T>
,然后就可以摆脱界限
CollectionViewSource.GetDefaultView(label_World.ContextMenu.ItemsSource).Refresh();
删除伦敦时,因为只要World对象发生变化,它就会自动更新上下文菜单。