[英]WPF - Remove a “User Control” Child from a StackPanel
我正在嘗試制作一個WPF UI,用戶可以在其中編輯查詢以搜索數據庫。 根據消費者從“ 像這樣 ”組合框中選擇的內容來創建查詢,只要他單擊“ 添加新條件”按鈕,他就可以創建任意數量的過濾器。
我創建了comboboxes模板作為用戶控件,如下所示:
用戶控件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 按鈕刪除用戶控件子級。
我嘗試了這個:
StackPanel.Children.Remove(..);
從我的MainWindow中刪除該子項,但是如何知道用戶單擊了哪個子項。
嘗試這個:
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);
}
@ 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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.