[英]Programmatically adding items to usercontrol
我的 MainWindow.xaml 从 MyClass.cs 获取它的数据上下文,并从 MyView.xaml 中的 usercontrol 获取它的视图,如下所示
<Window.DataContext>
<ViewModel:MyClass/>
</Window.DataContext>
<View:MyView/>
用户控件具有网格、堆栈面板和一个按钮,如下所示
<Grid x:Name="MainGrid" Height="300" Width="502">
<StackPanel x:Name="MainStackPanel" Height="200" Width="400"/>
<Button x:Name="NewButton" Command="{Binding CommandAddNewButton}" Content="new item" Height="25" Width="55" Margin="224,177,223,98"/>
</Grid>
从 MyClass 我尝试通过按下“新项目”按钮以编程方式将按钮和文本框添加到堆栈面板,如下所示
public ICommand CommandAddNewButton
{ get { return new MyCommand(AddNewButton); } }
private void AddNewButton()
{
var newButton = new Button
{
Name = "Button" + _itemNbr,
Content = "-",
FontSize = 10,
Height = 20,
Width = 15,
Background = new SolidColorBrush(Colors.Beige),
HorizontalContentAlignment = HorizontalAlignment.Center,
VerticalContentAlignment = VerticalAlignment.Center,
Margin = new Thickness(10, 10, 10, 10)
};
var newTextBox = new TextBox
{
Name = "TextBox" + _itemNbr,
Height = 20,
Width = 70,
FontSize = 10,
HorizontalContentAlignment = HorizontalAlignment.Right,
VerticalContentAlignment = VerticalAlignment.Center
};
MainStackPanel.Children.Add(newButton);
MainStackPanel.Children.Add(newTextBox);
}
按下按钮后会创建一个新按钮和文本框,但它们不显示。 我该如何解决? 感谢所有帮助。
<UserControl x:Class="WpfApp1.View.MyView"
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"
xmlns:ViewModel="clr-namespace:WpfApp1.ViewModel"
xmlns:View="clr-namespace:WpfApp1.View">
<Grid x:Name="MainGrid" Height="300" Width="502">
<StackPanel x:Name="MainStackPanel" Height="200" Width="400"/>
<Button x:Name="NewButton" Command="{Binding CommandAddNewButton}" Content="new item" Height="25" Width="55" Margin="224,177,223,98"/>
</Grid>
</UserControl>
我认为您正在将您的 View(Myview) 继承到您的 viewmodel(Myclass)。 以便您访问 stackpanel 的不同实例。 您可以做的一种方法是将 stackpanel 作为参数传递给视图模型。
在 Xml 中:
<Button x:Name="NewButton" Command="{Binding CommandAddNewButton}" CommandParameter="{Binding ElementName=MainStackPanel}" Content="new item" Height="25" Width="55" Margin="224,177,223,98"/>
在视图模型中:
private void AddNewButton(object obj)
{
var MainStackPanel= obj as StackPanel;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.