我有一個奇怪的問題與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