我的 MainWindow 中有两个 UserControl,而 UserControl2 有 2 个 Listbox、Texbox 和 Button。当我在 TextBox 中写一些文本并按下 Button 时,它应该添加到 ListBox。有人可以帮我写代码吗,我是 WPF 和 MVVM 的新手
这是我的 XAML 代码
<Window x:Class="Wpf_MVVM.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Wpf_MVVM"
Title="Voxer" Background="SlateGray" Height="420" Width="550">
<Grid>
<local:UserControl1 HorizontalAlignment="Left" VerticalAlignment="Top"/>
<local:UserControl2 HorizontalAlignment="Left" VerticalAlignment="Top" Margin="150,29,0,0"/>
</Grid>
这是我的 UserControl1.Xaml 代码
<UserControl x:Class="Wpf_MVVM.UserControl1"
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"
Height="Auto" Width="Auto">
<Grid>
<ListBox HorizontalAlignment="Left" Height="310" VerticalAlignment="Top" Width="150" Margin="0,40,0,0">
<ListBoxItem>Name 1</ListBoxItem>
<ListBoxItem>Name 2</ListBoxItem>
<ListBoxItem>Name 3</ListBoxItem>
<ListBoxItem>Name 4</ListBoxItem>
<ListBoxItem>Name 5</ListBoxItem>
<ListBoxItem>Name 6</ListBoxItem>
</ListBox>
<Label Content="Conversations" HorizontalAlignment="Left" VerticalAlignment="Top" Height="40" Width="150" FontSize="20" Background="SkyBlue"/>
<Button Content="Create New Chat" Height="30" HorizontalAlignment="Left" Margin="0,350,0,0" VerticalAlignment="Top" Width="150"/>
</Grid>
这是我的 UserControl2.Xaml 代码
<UserControl x:Class="Wpf_MVVM.UserControl2"
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"
Height="Auto" Width="390">
<Grid>
<ListBox Name="listbox1" HorizontalAlignment="Left" Height="310" VerticalAlignment="Top" Width="180" Margin="10,0,0,0"/>
<ListBox Name="listbox2" HorizontalAlignment="Left" Height="310" Margin="200,0,0,0" VerticalAlignment="Top" Width="180"/>
<TextBox Name="tb1" HorizontalAlignment="Left" Height="40" Margin="200,310,0,0" TextWrapping="NoWrap" Text="" VerticalAlignment="Top" Width="130"/>
<TextBox Name="tb2" Height="40" TextWrapping="NoWrap" Text="" Margin="10,310,245,0"/>
<Button Command="{Binding ButtonCommand}" Name="btn1" Content="Send" Height="40" HorizontalAlignment="Left" Margin="330,310,0,0" VerticalAlignment="Top" Width="50" />
<Button Command="{Binding SendControlCommand}" Name="btn2" Content="Send" Height="40" Margin="145,310,200,0"/>
</Grid>