如何删除在运行时创建的选定文本框
问题描述:
我有一个WPF应用程序有两个按钮 - 添加和删除。在运行时,添加按钮在gui中的特定网格中以编程方式添加文本框,并且文本框名称也将在运行时分配。我想要删除按钮删除运行时从gui生成的选定文本框。我不知道删除文本框的方法,除非我知道文本框的名称,并且我不确定该怎么办。即使有一点指导,我也会感激。我对WPF很陌生,我相信我应该错过一些明显的。如何删除在运行时创建的选定文本框
在此先感谢。
答
这里是一个基本的演示中添加和删除元素/从Grid
:
XAML :
<Window x:Class="TabControl.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TabControl"
Title="MainWindow" Height="300" Width="300"
xmlns:Interact="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
DataContext="{Binding RelativeSource={RelativeSource Mode=Self}}"
>
<ScrollViewer VerticalScrollBarVisibility="Visible">
<StackPanel Orientation="Vertical">
<StackPanel Orientation="Horizontal">
<Button Content="Add New Box" Click="Button_Click" />
<Button Content="Remove Selected Box" PreviewMouseLeftButtonDown="Button_PreviewMouseLeftButtonDown" />
</StackPanel>
<Grid x:Name="mygrid">
</Grid>
</StackPanel>
</ScrollViewer>
活动:
private void Button_Click(object sender, RoutedEventArgs e)
{
var textBox=new TextBox();
mygrid.RowDefinitions.Add(new RowDefinition());
textBox.Name = "textBox" + mygrid.RowDefinitions.Count;
textBox.SetValue(Grid.RowProperty, mygrid.RowDefinitions.Count);
mygrid.Children.Add(textBox);
}
private void Button_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
var focusedElement = Keyboard.FocusedElement;
if (focusedElement is TextBox)
{
mygrid.Children.Remove(focusedElement as UIElement);
}
}
输出
以上是很基本的WPF接近你可以,但是我非常建议你看看MVVM
模式,以便于逻辑分离和灵活性(如在@dotNEt中建议的他的回答)。
答
如果你使用MVVM,(你应该在WPF),你可以这样做:
- 在视图模型,公开公共
ObservableCollection<T>
将包含业务对象(例如User
)您需要显示TextBoxes。 - 在UI中,添加
ItemsControl
并将其绑定到ObservableCollection
。 - 定义
DataTemplate
,将业务对象转换为TextBox并将TextBox属性绑定到业务对象成员。 - 在ViewModel中执行
Add
和Remove
RelayCommands
。 - 用这些命令绑定添加和删除按钮。
这将节省您从繁忙的走可视化树,并找到合适的文本框等
+0
谢谢。我也会尝试这种方法! –
PreviewMouseLeftButtonDown =“Button_PreviewMouseLeftButtonDown” - 这就是我一直在寻找的东西。非常感谢你! –
@IndikaPathirage您的欢迎。随时接受答案... :) –