以编程方式将项添加到usercontrol

时间:2016-05-27 11:03:38

标签: c# wpf xaml

我的MainWindow.xaml从MyClass.cs获取它的datacontext,并从MyView.xaml中的usercontrol查看,如下所示

  <Window.DataContext>
     <ViewModel:MyClass/>
  </Window.DataContext>

  <View:MyView/>

usercontrol有grid,stackpanel和一个按钮,如下所示

<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>

1 个答案:

答案 0 :(得分:0)

我认为您将View(Myview)继承到viewmodel(Myclass)。这样您就可以访问另一个stackpanel实例。您可以做的一种方法是将stackpanel作为参数传递给视图模型。

在Xaml中:

 <Button x:Name="NewButton" Command="{Binding CommandAddNewButton}"  CommandParameter="{Binding ElementName=MainStackPanel}"  Content="new item" Height="25" Width="55" Margin="224,177,223,98"/>

在ViewModel中:

private void AddNewButton(object obj)
{
    var MainStackPanel= obj as StackPanel;
}