WPF - 删除"用户控件"来自StackPanel的孩子

时间:2017-08-15 13:10:30

标签: c# wpf xaml

我正在尝试创建一个WPF UI,用户可以在其中编辑查询以搜索数据库。根据消费者从组合框Like This中选择的内容创建查询,只要他点击添加新条件按钮,他就可以创建尽可能多的过滤器。

我将组合框模板创建为用户控件,如下所示:

用户控制XAML:

<StackPanel Orientation="Horizontal" >
        <Button
                Name="DeleteFilter" 
                HorizontalAlignment="Left"
                Margin="5"
                Content="-"
            Click="DeleteFilter_OnClick">
        </Button>
        <ComboBox 
                Text="Property"
                x:Name="Property"
                Width="100"
                DataContext="{StaticResource SomeViewModel}"
                ItemsSource="{Binding Properties}"
                DisplayMemberPath="Name"
             SelectionChanged="Property_OnSelectionChanged"/>
        <ComboBox 
            Text="PropertyOperator"
            x:Name="Operator"
            ItemsSource="{Binding Operators}"
            DisplayMemberPath="Name"
            SelectionChanged="Operator_OnSelectionChanged">
        </ComboBox>
        <TextBox 
                x:Name="Value"
                Text="Value"
                TextAlignment="Center"
                Width="100"
                Margin="5"/>
</StackPanel>

每当用户点击添加新条件按钮时,我都会调用此事件:

private void AddFilterButton_OnClick(object sender, RoutedEventArgs e)
    {
        var conditionUserControl = new ConditionUserControl();
        StackPanel.Children.Add(conditionUserControl);
    }

一切正常。

我的问题:

如何从单击 DeleteFilter button that exists in the User Control template删除用户控制子项。

我试过了:

StackPanel.Children.Remove(..);

从我的MainWindow中删除子项,但如何知道用户点击了哪个孩子。

2 个答案:

答案 0 :(得分:2)

试试这个:

private void DeleteFilter_OnClick(object sender, RoutedEventArgs e)
{
    Button btn = sender as Button;
    var conditionUserControl = FindParent<ConditionUserControl>(btn);
    if (conditionUserControl != null)
    {
        var sp = FindParent<StackPanel>(conditionUserControl);
        if (sp != null)
            sp.Children.Remove(conditionUserControl);
    }
}


private static T FindParent<T>(DependencyObject dependencyObject) where T : DependencyObject
{
    var parent = VisualTreeHelper.GetParent(dependencyObject);

    if (parent == null) return null;

    var parentT = parent as T;
    return parentT ?? FindParent<T>(parent);
}

答案 1 :(得分:0)

@ mm8答案的另一个答案是:

更新AddFilterButton_OnClick:

我这样做了,功能正常:

private void AddAndFilterButton_OnClick(object sender, RoutedEventArgs e)
    {
        var conditionUserControl = new ConditionUserControl();

        StackPanel.Children.Add(conditionUserControl);

        conditionUserControl.DeleteFilter.Click += (o, args) => StackPanel.Children.Remove(conditionUserControl);
    }