如何创建一个← 在XAML中的控件?
要创建一个在XAML中的控件,您需要遵循以下步骤:
以下是一个简单的示例代码:
XAML代码:
<Window x:Class="WpfApp1.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:WpfApp1"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
xmlns:mah="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
WindowTransitionsEnabled="False"
mc:Ignorable="d"
Title="MainWindow"
Height="450"
Width="800"
WindowStartupLocation="CenterScreen"
Loaded="Window_Loaded"
Style="{StaticResource DefaultWindow}">
<Window.DataContext>
<local:MainWindowViewModel />
</Window.DataContext>
<Window.Resources>
<local:StringToEnumConverter x:Key="StringToEnumConverter"/>
</Window.Resources>
<mah:MetroWindow.RightWindowCommands>
<mah:WindowCommands>
<Button x:Name="cmdMinimize"
Style="{StaticResource WindowMinimizeButton}" />
<Button x:Name="cmdMaximize"
Style="{StaticResource WindowMaximizeButton}" />
<Button x:Name="cmdExit"
Style="{StaticResource WindowExitButton}" />
</mah:WindowCommands>
</mah:MetroWindow.RightWindowCommands>
<StackPanel x:Name="stackPanel"
Orientation="Horizontal">
<TextBlock x:Name="txtStatus"
Text="{Binding Status}"
FontSize="24"
FontFamily="Arial"
Margin="80,5,0,0"
TextWrapping="Wrap" />
<StackPanel Orientation="Vertical">
<Button x:Name="cmdTest"
Content="Test"
Margin="5"
FontSize="20"
FontFamily="Arial" />
<Button x:Name="cmdStop"
Content="Stop"
Margin="5"
FontSize="20"
FontFamily="Arial" />
<Button x:Name="cmdStart"
Content="Start"
Margin="5"
FontSize="20"
FontFamily="Arial" />
</StackPanel>
</StackPanel>
</Window>
C#代码:
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
namespace WpfApp1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new MainWindowViewModel();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
var converter = new StringToEnumConverter();
var enumValues = Enum.GetValues(typeof(Status));
var allStatus = enumValues.Cast<Status>().ToList();
comboBoxStatus.ItemsSource = allStatus;
comboBoxStatus.SelectedItem = Status.Idle;
}
private void cmdTest_Click(object sender, RoutedEventArgs e)
{
var viewModel = (MainWindowViewModel)DataContext;
viewModel.Status = (Status)comboBoxStatus.SelectedItem
领取专属 10元无门槛券
手把手带您无忧上云