我正在尝试制作一个 WPF UI,用户可以在其中编辑查询来搜索数据库。查询是根据消费者从组合框中选择的内容创建的像这样 https://i.stack.imgur.com/5ih0p.png他可以创建任意数量的过滤器,只要他点击添加新条件按钮。
我将组合框模板创建为用户控件,如下所示:
用户控制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);
}
一切正常。
我的问题:
如何通过单击删除用户控件子项删除过滤器 用户控制模板中存在的按钮 https://i.stack.imgur.com/jiYG6.png.
我试过这个:
StackPanel.Children.Remove(..);
从我的主窗口中删除子项,但如何知道用户单击了哪个子项。
尝试这个:
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);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)