我希望my previous question的答案可以帮助我解决这个问题,但事实并非如此。最初的情况几乎相同:
<TreeView ItemsSource="{Binding Groups}" Name="tvGroups" AllowDrop="True">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Participants}">
<StackPanel Orientation="Horizontal" Drop="tvDrop" Tag="{Binding .}">
<TextBlock Text="{Binding Name}" />
<Button Tag="{Binding .}" Click="Button_Click_2">
<Image Source="Resources/cross.png" />
</Button>
</StackPanel>
<HierarchicalDataTemplate.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" >
<TextBlock Text="{Binding Alias}" />
<Button Tag="{Binding .}" Name="btnDeleteParticipants" Click="btnParticipants_Click" >
<Image Source="Resources/cross.png" />
</Button>
</StackPanel>
</DataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
private void btnParticipants_Click(object sender, RoutedEventArgs e)//Probanten aus Gruppe entfernen
{
Participant p = ((sender as Button).Tag as Participant);
if (p == null) return;
//TODO: Raus bekommen in welcher Gruppe ich löschen will
}
我想通过点击按钮(btnDeleteParticipants)从Participant p
中删除Group
。我试过这样的事情:
Control c = sender as Control;
while (!(c is TreeViewItem))
c = (c.Parent) as Control;
但这不起作用(不要问为什么,我不确定)。我可以通过检查Group
是否包含Participant
(绑定到btnDeleteParticipants.Tag
)找到Group
,但这样就不允许参与者进入多个组。
那么,任何想法如何获得正确的Groups = new ObservableCollection<Group>();
Participants = new ObservableCollection<Participant>();
?
修改:
{{1}}
答案 0 :(得分:1)
群组和参与者ObservableCollection对象吗?
尝试使用:
static TObject FindVisualParent<TObject>(UIElement child) where TObject : UIElement
{
if (child == null)
{
return null;
}
UIElement parent = VisualTreeHelper.GetParent(child) as UIElement;
while (parent != null)
{
TObject found = parent as TObject;
if (found != null)
{
return found;
}
else
{
parent = VisualTreeHelper.GetParent(parent) as UIElement;
}
}
return null;
}
另外,尝试使用DataContext获取参与者并将Tag设置为TemplatedParent。
<Button Tag="{Binding RelativeSource={RelativeSource TemplatedParent}}" />
然后点击
private void btnParticipants_Click(object sender, RoutedEventArgs e)
{
var button = sender as Button;
var p = button.DataContext as Participant;
if (p == null) return;
var t= FindVisualParent<TreeViewItem>(button); // get the Participants TreeViewItem
if (t == null) return;
var groupTreeItem = FindVisualParent<TreeViewItem>(t); // get the groups TreeViewItem
if (groupTreeItem == null) return;
var group = groupTreeItem.DataContext as Group;
group.Participants.Remove(p);
}