【发布时间】:2018-06-28 06:18:24
【问题描述】:
我有一个简单的用户控件,其中包含一个文本框和一个按钮。 我希望单击该按钮将创建一个新的用户控件,该控件将位于单击其按钮的那个之后(下方)。
例如:
这是用户控件的代码:
<UserControl x:Class="LearnWPF.MyUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height=".9*"/>
<RowDefinition Height=".1*"/>
</Grid.RowDefinitions>
<TextBox ></TextBox>
<Button Grid.Row="1" Content="Create New UserControl" FontSize="20"/>
</Grid>
这是主窗口:
<Window x:Class="LearnWPF.MyWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:myUserControl="clr-namespace:LearnWPF"
Title="MainWindow" Height="450" Width="800">
<StackPanel>
<myUserControl:MyUserControl />
</StackPanel>
</Window>
按照here 的建议,我确实成功地将新的“myUserControls”添加到主窗口中的 StackPanel。这个实现的两个主要问题是:
- 我无法确定我是从哪个“myUserControl”获得事件的。
- 即使我知道单击了哪个按钮以及在何处创建新的 UserControl,我也不知道如何在 StackPanel 中间插入(可能是 需要不同的面板吗?)
此外,此解决方案使用了代码。有没有办法在 MVVM 中完成所有这些操作?
【问题讨论】:
-
在您后面的代码中应该将您的 usecontrol 作为子级添加到父级,例如 yourStackpanelName.Children.Add(yourChildUsercontrol);
-
在 MVVM 中你可以玩可见性
-
但如果我这样做 StackpanelName.Children.Add(yourChildUsercontrol);它总是会添加到堆栈面板的 END 中。我想在单击其按钮的对象之后添加。
-
我认为您需要页面而不是用户控件。你能分享一下你真正想要什么的问题描述吗
-
正如我在我的问题中所写:“我希望单击该按钮将创建一个新的用户控件,该控件将位于单击其按钮的那个之后(下方)。”
标签: c# wpf mvvm user-controls