我有一个奇怪的问题与WPF contextMenu方面更新UI!WPF ContextMenu失去它的子项目
基本上我创建了一个名为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消失。然后,如果你点击按钮伦敦城市获取删除。现在,当你右键单击标签时,contextMenu会显示国家项目,但不会显示其城市子项目
非常感谢你真的Rachel 它现在与observableCollection,而不是通用列表工作! – 2010-08-20 08:26:06