1.XAML部分
<Window x:Class="WpfApp2022062901.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp2022062901"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<!--<Window.Resources>
<TextBlock x:Key="Res1" Text="海上生明月" />
<TextBlock x:Key="Res2" Text="海上生明月" />
</Window.Resources>
<StackPanel>
<Button Margin="5,5,5,0" Content="{StaticResource Res1}" />
<Button Margin="5,5,5,0" Content="{DynamicResource Res2}" />
<Button Margin="5,5,5,0" Content="Update" Click="UpdateRes_Click" />
</StackPanel>-->
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="24" />
<RowDefinition Height="4" />
<RowDefinition Height="24" />
<RowDefinition Height="4" />
<RowDefinition Height="24" />
<RowDefinition Height="4" />
<!--最后一个*是用于瓜分剩余空间部分,而对于其他高度部分则使用具体高度数字部分来写-->
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<!--TextBlock其实就是一个文本显示框类似于Winform里面的label-->
<TextBlock Grid.Row="0" Text="Name:" VerticalAlignment="Center" HorizontalAlignment="Left" />
<!--TextBox其实就是一个文本输入框-->
<TextBox Grid.Row="0" Name="NameTextBox" Margin="60,0,0,0" />
<Button Grid.Row="2" Content="New Teacher" Command="New" CommandParameter="Teacher" />
<Button Grid.Row="4" Content="New Student" Command="New" CommandParameter="Student" />
<ListBox Grid.Row="6" Name="NewItemListBox" Height="117" VerticalAlignment="Bottom" />
</Grid>
<Window.CommandBindings>
<!--Command对应事件名,方便对应的按钮绑定-->
<CommandBinding Command="New" CanExecute="CommandBinding_CanExecute" Executed="CommandBinding_Executed" />
</Window.CommandBindings>
</Window>
2.CS部分
private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
//用this.NameTextBox.Text来调出本界面下的控件元素属性部分
if (string.IsNullOrEmpty(this.NameTextBox.Text) == true) e.CanExecute = false;
else e.CanExecute = true;
}
/// <summary>
/// --对应业务部分执行完毕
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
string name = this.NameTextBox.Text;
//按钮部分传入的参数部分可作为信息录入,也可作为对应参数判断项
if (e.Parameter.ToString() == "Teacher")
{
this.NewItemListBox.Items.Add(string.Format("New Teacher: {0}, 学而不厌,诲人不倦。", name));
}
else if (e.Parameter.ToString() == "Student")
{
this.NewItemListBox.Items.Add(string.Format("New Student: {0},好好学习,天天向上。", name));
}
}
本文介绍了如何在WPF中使用XAML创建窗口,并展示了如何动态绑定资源和处理按钮点击事件。通过实例演示了`{DynamicResource}

1万+

被折叠的 条评论
为什么被折叠?



