WPF 02

news2024/11/25 0:48:11

Grid容器

分行和分列

<Grid>
        <Grid.RowDefinitions>
            <!--2*:此行是下面一行的两倍-->
            <RowDefinition Height="2*"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <Border Background="blue"/>
        <Border Grid.Row="1" Background="red"/>
        <Border Grid.Column="1" Background="yellow"/>
        <Border Grid.Row="1" Grid.Column="1"  Background="green"/>
    </Grid>

跨行和跨列

<!--跨行和跨列-->
        <Border Grid.ColumnSpan="2" Grid.RowSpan="2" Background="blue"/>

stackPanel:默认垂直排列

局部容器,一般修饰部分空间的元素排布

<StackPanel>
//<StackPanel Orientation="Horizontal">
    <Button Height="50" Width="100"/>
    <Button Height="50" Width="100"/>
    <Button Height="50" Width="100"/>
    <Button Height="50" Width="100"/>
    <Button Height="50" Width="100"/>
</StackPanel>

WrapPanel :默认水平排序且换行

<WrapPanel Grid.Row="1">
    <Button Height="50" Width="100"/>
    <Button Height="50" Width="100"/>
    <Button Height="50" Width="100"/>
    <Button Height="50" Width="100"/>
    <Button Height="50" Width="100"/>
</WrapPanel>

WrapPanel可以自动换行

DockPanel:默认最后一个元素填充剩余所有空间

<DockPanel>
    <Button Height="50" Width="100"/>
    <Button Height="50" Width="100"/>
    <Button Height="50" Width="100"/>
    <Button Height="50" Width="100"/>
    <Button Height="50" Width="100"/>
</DockPanel>

取消最后一个元素填充剩余所有空间:

<DockPanel LastChildFill="False">

DockPanel可以停靠

<DockPanel LastChildFill="False"> 
    <Button Height="50" Width="100" DockPanel.Dock="Bottom"/>
    <Button Height="50" Width="100" DockPanel.Dock="Left"/>
    <Button Height="50" Width="100" DockPanel.Dock="Right"/>
    <Button Height="50" Width="100" DockPanel.Dock="Top"/>
    <Button Height="50" Width="100" DockPanel.Dock="Bottom"/>
</DockPanel>

UniformGrid: 在有限的空间内根据控件均分剩余空间

<UniformGrid Rows="3" Columns="3">
    <Button/>
    <Button/>
    <Button/>
    <Button/>
    <Button/>
    <Button/>
    <Button/>
    <Button/>
    <Button/>
</UniformGrid>

ctrl+k+d:自动格式化代码

课程案例1

模块划分代码:

<Window x:Class="WpfDay01.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:WpfDay01"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="50"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <Border Background="#7378DB"/>
        <Grid Grid.Row="1">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="200"/>
                <ColumnDefinition/>
            </Grid.ColumnDefinitions>
            <Border Margin="5" Background="blue"/>
            <Grid Grid.Column="1">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition/>
                    <ColumnDefinition/>
                    <ColumnDefinition/>
                    <ColumnDefinition/>
                    <ColumnDefinition/>
                </Grid.ColumnDefinitions>
                <Grid.RowDefinitions>
                    <RowDefinition/>
                    <RowDefinition/>
                    <RowDefinition/>
                </Grid.RowDefinitions>
                <Border Margin="5" Background="#7378DB"/>
                <Border Margin="5" Grid.Column="1" Background="#4598CE"/>
                <Border Margin="5" Grid.Column="2"  Background="#E080CE"/>
                <Border Margin="5" Grid.Column="3" Background="#50B9B8"/>
                <Border Margin="5" Grid.Column="4" Background="#E07A7D"/>
                <Border Margin="5"  Grid.Row="1" Grid.ColumnSpan="3" Background="green"/>
                <Border Margin="5"  Grid.Row="1" Grid.Column="3" Grid.ColumnSpan="2" Background="Yellow"/>
                <Border Margin="5"  Grid.Row="2" Grid.ColumnSpan="3" Background="red"/>
                <Border Margin="5"  Grid.Row="3" Grid.Column="3" Grid.ColumnSpan="2" Background="Blue"/>

            </Grid>
        </Grid>
    </Grid>
</Window>

练习案例1

<!--<Window x:Class="WpfDay01.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:WpfDay01"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="50"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <Border Background="#7378DB"/>
        <Grid Grid.Row="1">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="200"/>
                <ColumnDefinition/>
            </Grid.ColumnDefinitions>
            <Border Margin="5" Background="blue"/>
            <Grid Grid.Column="1">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition/>
                    <ColumnDefinition/>
                    <ColumnDefinition/>
                    <ColumnDefinition/>
                    <ColumnDefinition/>
                </Grid.ColumnDefinitions>
                <Grid.RowDefinitions>
                    <RowDefinition/>
                    <RowDefinition/>
                    <RowDefinition/>
                </Grid.RowDefinitions>
                <Border Margin="5" Background="#7378DB"/>
                <Border Margin="5" Grid.Column="1" Background="#4598CE"/>
                <Border Margin="5" Grid.Column="2"  Background="#E080CE"/>
                <Border Margin="5" Grid.Column="3" Background="#50B9B8"/>
                <Border Margin="5" Grid.Column="4" Background="#E07A7D"/>
                <Border Margin="5"  Grid.Row="1" Grid.ColumnSpan="3" Background="green"/>
                <Border Margin="5"  Grid.Row="1" Grid.Column="3" Grid.ColumnSpan="2" Background="Yellow"/>
                <Border Margin="5"  Grid.Row="2" Grid.ColumnSpan="3" Background="red"/>
                <Border Margin="5"  Grid.Row="3" Grid.Column="3" Grid.ColumnSpan="2" Background="Blue"/>

            </Grid>
        </Grid>
    </Grid>
</Window>-->
<Window x:Class="WpfDay01.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:WpfDay01"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="50"/>
            <RowDefinition Height="100"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <Border Background="LightCyan"/>
        <Grid Grid.Row="1">
            <Grid.ColumnDefinitions>
                <ColumnDefinition/>
                <ColumnDefinition/>
                <ColumnDefinition/>
                <ColumnDefinition/>
                <ColumnDefinition/>
            </Grid.ColumnDefinitions>
            <Border Margin="5" Background="#219AFB"/>
            <Border Margin="5" Grid.Column="1" Background="#64B522"/>
            <Border Margin="5" Grid.Column="2" Background="#FF9F00"/>
            <Border Margin="5" Grid.Column="3" Background="#50B9B8"/>
            <Border Margin="5" Grid.Column="4" Background="#E07A7D"/>
        </Grid>
        <Grid Grid.Row="2">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="0.667*"/>
                <ColumnDefinition/>
            </Grid.ColumnDefinitions>
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition/>
                    <RowDefinition/>
                    <RowDefinition/>
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition/>
                    <ColumnDefinition/>
                </Grid.ColumnDefinitions>
                <Border Margin="5" Grid.ColumnSpan="2" Background="blue"/>
                <Border Margin="5" Grid.Row="1" Background="red"/>
                <Border Margin="5" Grid.Row="1" Grid.Column="1" Background="yellow"/>
                <Border Margin="5" Grid.Row="2" Background="pink"/>
                <Border Margin="5" Grid.Row="2" Grid.Column="1" Background="green"/>
            </Grid>
            <Grid Grid.Column="1">
                <Grid.RowDefinitions>
                    <RowDefinition Height="1.5*"/>
                    <RowDefinition/>
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition/>
                    <ColumnDefinition/>
                </Grid.ColumnDefinitions>
                <Border Margin="5" Background="AntiqueWhite"/>
                <Border Margin="5" Grid.Column="1" Background="Gray"/>
                <Border Margin="5" Grid.Row="1" Grid.ColumnSpan="2" Background="SaddleBrown"/>
            </Grid>
        </Grid>
    </Grid>
</Window>

样式的使用方法

<Window x:Class="WpfDay01.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:WpfDay01"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.Resources>
        <Style x:Key="BaseButtonStyle" TargetType="Button">
            <Setter Property="Foreground" Value="White"/>
            <Setter Property="Background" Value="Blue"/>
        </Style>
        <Style x:Key="ButtonStyle" TargetType="Button" BasedOn="{StaticResource BaseButtonStyle}">
            <Setter Property="Content" Value="text"/>
        </Style>
    </Window.Resources>
    <Grid>
        <StackPanel>
            <Button Content="button1" Background="Red" Style="{StaticResource ButtonStyle}"/>
            <Button Content="button2" Style="{StaticResource ButtonStyle}"/>
            <Button Content="button3" Style="{StaticResource ButtonStyle}"/>
        </StackPanel>
    </Grid>
</Window>

数据模板

案例1

MainWindow.xaml

<Window x:Class="WpfDay01.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:WpfDay01"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    
    <Grid>
        <ListBox x:Name="list">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <Border Width="10" Height="10" Background="{Binding Code}"/>
                        <TextBlock Margin="10, 0" Text="{Binding Name}"/>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
            
        </ListBox>
    </Grid>
</Window>

MainWindow.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfDay01
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            List<Color> test = new List<Color>();
            test.Add(new Color() { Code= "#FF69B4", Name= "热情的粉红" });
            test.Add(new Color() { Code= "#C71585", Name= "适中的紫罗兰红色" });
            test.Add(new Color() { Code= "#DA70D6", Name= "兰花的紫色" });
            list.ItemsSource = test;
        }
    }
    public class Color
    {
        public string Code { get; set; }
        public string Name { get; set; }
    }
}

案例2

MainWindow.xaml

<Window x:Class="WpfDay01.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:WpfDay01"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <DataGrid x:Name="grid"
                  AutoGenerateColumns="False"
                  CanUserAddRows="False">
            <DataGrid.Columns>
                <DataGridTextColumn Binding="{Binding Code}" Header="Code"/>
                <DataGridTextColumn Binding="{Binding Name}" Header="Name"/>

                <DataGridTemplateColumn Header="操作">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <StackPanel Orientation="Horizontal">
                                <Border Width="10" Height="10" Background="{Binding Code}"/>
                                <TextBlock Margin="10 0" Text="{Binding Name}"/>
                            </StackPanel>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                    
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>

MainWindow.xaml.cs

namespace WpfDay01
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {

            InitializeComponent();
            List<Color> test = new List<Color>();
            test.Add(new Color() { Code= "#FF69B4", Name= "热情的粉红" });
            test.Add(new Color() { Code= "#C71585", Name= "适中的紫罗兰红色" });
            test.Add(new Color() { Code= "#DA70D6", Name= "兰花的紫色" });
            grid.ItemsSource = test;
        }
    }
    public class Color
    {
        public string Code { get; set; }
        public string Name { get; set; }
    }
}

修改dataTemplete

<DataTemplate>
    <!--<StackPanel Orientation="Horizontal">
        <Border Width="10" Height="10" Background="{Binding Code}"/>
        <TextBlock Margin="10 0" Text="{Binding Name}"/>
    </StackPanel>-->
    <StackPanel Orientation="Horizontal">
        <Button Content="添加"/>
        <Button Content="修改"/>
        <Button Content="删除"/>
    </StackPanel>
</DataTemplate>

绑定方法

双向数据绑定关系

<Window x:Class="WpfDay01.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:WpfDay01"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <StackPanel>
            <Slider x:Name="slider" Margin="5"/>
            <TextBox Text="{Binding ElementName=slider, Path=Value}" Margin="5"/>
            <TextBox Text="{Binding ElementName=slider, Path=Value}" Margin="5"/>
            <TextBox Text="{Binding ElementName=slider, Path=Value}" Margin="5"/>
        </StackPanel>
    </Grid>
</Window>

绑定模式

<StackPanel>
      <Slider x:Name="slider" Margin="5"/>
      <TextBox Text="{Binding ElementName=slider, Path=Value, Mode=OneTime}" Margin="5"/>
      <TextBox Text="{Binding ElementName=slider, Path=Value, Mode=OneWay}" Margin="5"/>
      <TextBox Text="{Binding ElementName=slider, Path=Value, Mode=OneWayToSource}" Margin="5"/>
      <TextBox Text="{Binding ElementName=slider, Path=Value, Mode=TwoWay}" Margin="5"/>
  </StackPanel>

TextBox数据绑定

MainWindow.xaml

<Window x:Class="WpfDay01.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:WpfDay01"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <StackPanel>
            <TextBox Text="{Binding Name}" Margin="5"/>
        </StackPanel>
    </Grid>
</Window>

创建类test

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WpfDay01
{
    class Test
    {
        public string Name { get; set; }
    }
}

MainWindow.xaml.cs

namespace WpfDay01
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new Test()
            {
                Name = "张三"
            };
        }
    }
    public class Color
    {
        public string Code { get; set; }
        public string Name { get; set; }
    }
}

ICommand使用方法

业务逻辑代码:MainViewModel.cs

UI代码:MainWindow.xaml

实现ICommand中的接口:MyCommand.cs

将View与ViewModel挂钩:MainWindow.xaml.cs

MyCommand.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace WpfDay01
{
    public class MyCommand : ICommand
    {
        Action executeAction;
        Func<bool> canExecuteAction;
        public MyCommand(Action action,Func<bool> canExcuteAction)
        {
            executeAction = action;
            canExecuteAction = canExcuteAction;
        }
        public event EventHandler CanExecuteChanged;

        public bool CanExecute(object parameter)
        {
            return canExecuteAction();
        }

        public void Execute(object parameter)
        {
            executeAction();
        }
    }
}

MainViewModel.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace WpfDay01
{
    public class MainViewModel
    {
        public MainViewModel()
        {
            ShowCommand = new MyCommand(Show,canExcuteAction);
            ShowCommand2 = new MyCommand(show2, canExcuteAction2);
        }
        private string myname="a";
        public string MyName
        {
            get { return myname; }
            set { myname = value; }
        }

        private bool canExcuteAction()
        {
            if (string.IsNullOrEmpty(MyName))
                return false;
            return true;
        }
        private bool canExcuteAction2()
        {   
            return true;
        }
        public MyCommand ShowCommand { get; set; }
        public MyCommand ShowCommand2 { get; set; }
        public void Show()
        {
            MessageBox.Show("点击了按钮!");
        }
        public void show2()
        {
            MyName = "b";
            MessageBox.Show(MyName);
        }
    }
}

MainWindow.xaml

<Window x:Class="WpfDay01.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:WpfDay01"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <StackPanel>
        <TextBox Text="{Binding MyName}"></TextBox>
        <Button Width="100" Height="100" Content="Button" Command="{Binding ShowCommand}"/>
        <Button Width="100" Height="100" Content="Button" Command="{Binding ShowCommand2}"/>
    </StackPanel>
</Window>

MainWindow.xaml.cs

DataContext:连接View与ViewModel挂钩。

public partial class MainWindow : Window
    {
        public MainWindow()
        {

            InitializeComponent();
            this.DataContext = new MainViewModel();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("hhhh");
        }
    }

更新UI界面:INotifyPropertyChanged

业务逻辑代码:MainViewModel.cs

UI代码:MainWindow.xaml

实现ICommand中的接口:MyCommand.cs

将View与ViewModel挂钩:MainWindow.xaml.cs

INotifyPropertyChanged更新界面:ViewModelBase.cs

ViewModelBase.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace WpfDay01
{
    class ViewModelBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        public void OnPropertyChanged([CallerMemberName]string propertyName="")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

MyCommand.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace WpfDay01
{
    class MyCommand : ICommand
    {
        Action executeAction;
        public MyCommand(Action action)
        {
            executeAction = action;     
        }
        public event EventHandler CanExecuteChanged;

        public bool CanExecute(object parameter)
        {
            return true;
        }
        public void Execute(object parameter)
        {
            executeAction();
        }
    }
}

MainViewModel.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace WpfDay01
{
    class MainViewModel: ViewModelBase
    {
        public MainViewModel()
        {
            MyName = "Hello";
            ShowCommand = new MyCommand(Show);
            ShowCommand2 = new MyCommand(show2);
        }

        private string myname;
        public string MyName
        {
            get { return myname; }
            set { 
                myname = value;
                OnPropertyChanged();
                }
        }

        private string myTitle;
        public string MyTitle
        {
            get { return myTitle; }
            set { myTitle = value; OnPropertyChanged(); }
        }


        public MyCommand ShowCommand { get; set; }
        public MyCommand ShowCommand2 { get; set; }
        
        public void Show()
        {
            MyName = "点击了按钮";
            MyTitle = "myTitle";
            MessageBox.Show("点击了按钮!");
        }
        public void show2()
        {
            MyName = "b";
            MyTitle = "myTitle2";
            MessageBox.Show(MyName);
        }
    }
}

MainWindow.xaml

<Window x:Class="WpfDay01.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:WpfDay01"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <StackPanel>
        <TextBox Text="{Binding MyName}"></TextBox>
				<TextBox Text="{Binding MyTitle}"></TextBox>
        <Button Width="100" Height="100" Content="Button" Command="{Binding ShowCommand}"/>
        <Button Width="100" Height="100" Content="Button" Command="{Binding ShowCommand2}"/>
    </StackPanel>
</Window>

MainWindow.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfDay01
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new MainViewModel();
        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("hhhh");
        }
    }
}

MvvmLight框架

使用MvvmLight框架后不需要自定义MyCommand和ViewModelBase,直接调用即可。

MainViewModel.cs

using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace WpfDay02
{
    class MainViewModel: ViewModelBase
    {
        public MainViewModel()
        {
            MyName = "hello!";
            ShowCommand = new RelayCommand(Show);
        }
        public RelayCommand ShowCommand { get; }
        private string myName;
        public string MyName
        {
            get { return myName; }
            set { myName = value; RaisePropertyChanged(); }
        }
        public void Show()
        {
            MyName = "按下了按钮!";
            MessageBox.Show("按下了按钮!");
        }
    }
}

MainWindow.xaml

<Window x:Class="WpfDay02.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:WpfDay02"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <TextBox Text="{Binding MyName}"></TextBox>
        <Button Height="100" Width="100" Content="btn" Command="{Binding ShowCommand}"></Button>
    </Grid>
</Window>

MainWindow.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfDay02
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new MainViewModel();
        }
    }
}
将某个控件的内容关联到另外控件上(泛型的使用)

MainViewModel.cs

using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace WpfDay02
{
    class MainViewModel: ViewModelBase
    {
        public MainViewModel()
        {
            MyName = "hello!";
            ShowCommand = new RelayCommand<string>(Show);
        }
        public RelayCommand<string> ShowCommand { get; }
        private string myName;

        public string MyName
        {
            get { return myName; }
            set { myName = value; RaisePropertyChanged(); }
        }
        public void Show(string content)
        {
            MyName = "按下了按钮!";
            MessageBox.Show(content);
        }
    }
}

MainWindow.xaml

<Window x:Class="WpfDay02.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:WpfDay02"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <StackPanel>
            <TextBox Text="{Binding MyName}" Height="40" Margin="10"></TextBox>
            <TextBox x:Name="txtInput" Height="40" Margin="10"></TextBox>
            <Button Height="100" Width="100" Content="btn" Command="{Binding ShowCommand}"
                CommandParameter="{Binding ElementName=txtInput, Path=Text}"></Button>
        </StackPanel>
    </Grid>
</Window>

将textBox中的内容通过button按钮显示到messageBox中。

使用Messenger注册接收消息

修改部分:MainWindow.xaml.cs和MainViewModel.cs

MainWindow.xaml.cs

using GalaSoft.MvvmLight.Messaging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfDay02
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new MainViewModel();
            //注册一个接收string类型参数的消息,地址是Token1
            Messenger.Default.Register<string>(this, "Token1", Show);
        }
        void Show(string value)
        {
            MessageBox.Show(value);
        }
    }
}

MainViewModel.cs

using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace WpfDay02
{
    class MainViewModel: ViewModelBase
    {
        public MainViewModel()
        {
            MyName = "hello!";
            ShowCommand = new RelayCommand<string>(Show);
        }
        public RelayCommand<string> ShowCommand { get; }
        private string myName;
        public string MyName
        {
            get { return myName; }
            set { myName = value; RaisePropertyChanged(); }
        }
        public void Show(string content)
        {
            MyName = "按下了按钮!";
            //MessageBox.Show(content);
            //给Token1的地址发送一个string类型的值 content
            Messenger.Default.Send(content, "Token1");
        }
    }
}

效果与上面案例相同

CommunityToolkit.Mvvm框架

MainViewModel.cs

using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace WpfDay02
{
    class MainViewModel: ObservableObject 
    {
        public MainViewModel()
        {
            MyName = "hello!";
            ShowCommand = new RelayCommand<string>(Show);
        }
        public RelayCommand<string> ShowCommand { get; }
        private string myName;

        public string MyName
        {
            get { return myName; }
            set { myName = value; OnPropertyChanged(); }
        }
        public void Show(string content)
        {
            MyName = "按下了按钮!";
            //MessageBox.Show(content);
            WeakReferenceMessenger.Default.Send(content, "Token1");           
        }
    }
}

MainWindow.xaml.cs

using CommunityToolkit.Mvvm.Messaging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using Sysatem.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfDay02
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new MainViewModel();

            WeakReferenceMessenger.Default.Register<string, string>(this, "Token1", (s, e)=>
            {
                MessageBox.Show(e);
            });
        } 
    }
}

MainWindow.xaml

<Window x:Class="WpfDay02.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:WpfDay02"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <StackPanel>
            <TextBox Text="{Binding MyName}" Height="40" Margin="10"></TextBox>
            <TextBox x:Name="txtInput" Height="40" Margin="10"></TextBox>
            <Button Height="100" Width="100" Content="btn" Command="{Binding ShowCommand}"
                CommandParameter="{Binding ElementName=txtInput, Path=Text}"></Button>
        </StackPanel>   
    </Grid>
</Window>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1053922.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

[管理与领导-107]:IT人看清职场中的隐性规则 - 4 - 职场话术:其实是同一个意思,只是换一种了说法,效果不同,小心被套路

目录 前言&#xff1a; 一、套路和核心思想 1.1 核心思想 1.2 基本原则&#xff1a;让听话者舒服 二、消极变积极的说法 》 自足当下&#xff0c;展望未来 三、委婉拒绝 四、不想接受某项任务 五、正面、让人舒服的表达方式 六、其他 七、职场话术128条&#xff1a;…

ssm+vue的4S店预约保养管理系统(有报告)。Javaee项目,ssm vue前后端分离项目。

演示视频&#xff1a; ssmvue的4S店预约保养管理系统&#xff08;有报告&#xff09;。Javaee项目&#xff0c;ssm vue前后端分离项目。 项目介绍&#xff1a; 采用M&#xff08;model&#xff09;V&#xff08;view&#xff09;C&#xff08;controller&#xff09;三层体系结…

淘宝/天猫获得淘宝商品详情API(含测试示例)

taobao.item_get 调用说明 公共参数 名称类型必须描述keyString是调用key&#xff08;必须以GET方式拼接在URL中进入测试&#xff09;secretString是调用密钥api_nameString是API接口名称&#xff08;包括在请求地址中&#xff09;[item_search,item_get,item_search_shop等]c…

智能文字识别技术——AI赋能古彝文保护

前言 人工智能在古彝文古籍保护方面具有巨大的潜力和意义。通过数字化、自动化和智能化的手段&#xff0c;可以更好地保护和传承古彝文的文化遗产&#xff0c;促进彝族文化的传承和发展。 文章目录 前言一、古彝文是什么&#xff1f;1.1古彝文的背景1.2古彝文古籍保护背景 二、…

支持向量机SVM:从数学原理到实际应用

目录 一、引言背景SVM算法的重要性 二、SVM基础线性分类器简介什么是支持向量&#xff1f;超平面和决策边界SVM的目标函数 三、数学背景和优化拉格朗日乘子法&#xff08;Lagrange Multipliers&#xff09;KKT条件核技巧&#xff08;Kernel Trick&#xff09;双重问题和主问题&…

竞赛 基于设深度学习的人脸性别年龄识别系统

文章目录 0 前言1 课题描述2 实现效果3 算法实现原理3.1 数据集3.2 深度学习识别算法3.3 特征提取主干网络3.4 总体实现流程 4 具体实现4.1 预训练数据格式4.2 部分实现代码 5 最后 0 前言 &#x1f525; 优质竞赛项目系列&#xff0c;今天要分享的是 基于深度学习机器视觉的…

windows server 2019 、win11安装docker desktop

Docker Desktop Docker Desktop是可以部署在windows运行docker的应用服务&#xff0c;其基于windos的Hyper-V服务和WSL2内核在windos上创建一个子系统(linux)&#xff0c;从而实现其在windows上运行docker。 前提条件 WSL 查看wsl是否安装 我们可以直接在 cmd 或 powershe…

软件过程的介绍

软件过程概述 软件的诞生和生命周期是一个过程&#xff0c;我们总体上称这个过程为软件过程。软件过程是为了开发出软件产品&#xff0c;或者是为了完成软件工程项目而需要完成的有关软件工程的活动&#xff0c;每一项活动又可以分为一系列的工程任务。任何一个软件开发组织&a…

在2023年使用Unity2021从Built-in升级到Urp可行么

因为最近在做WEbgl平台&#xff0c;所以某些不可抗力原因&#xff0c;需要使用Unity2021开发&#xff0c;又由于不可明说原因&#xff0c;想用Urp&#xff0c;怎么办&#xff1f; 目录 创建RenderAsset 关联Asset 暴力转换&#xff08;Menu->Edit&#xff09; 单个文件…

贪心找性质+dp表示+矩阵表示+线段树维护:CF573D

比较套路的题目 首先肯定贪心一波&#xff0c;两个都排序后尽量相连。我一开始猜最多跨1&#xff0c;但其实最多跨2&#xff0c;考虑3个人的情况&#xff1a; 我们发现第3个人没了&#xff0c;所以可以出现跨2的情况 然后直接上dp&#xff0c;由 i − 1 , i − 2 , i − 3 i…

maven无法下载时的解决方法——笔记

右键项目然后点击创建setting.xml&#xff08;因为现在创建了&#xff0c;所以没显示了&#xff0c;可以直接点击打开setting.xml&#xff09; 然后添加 <mirror><id>nexus-aliyun</id><mirrorOf>*,!jeecg,!jeecg-snapshots</mirrorOf><name…

stm32 - GPIO

stm32 - GPIO GPIO结构图GPIO原理图输入上拉/下拉/浮空施密特触发器片上外设 输出推挽/开漏/关闭输出方式 GPIO88种模式复用输出 GPIO寄存器端口配置寄存器_CRL端口输入数据寄存器_IDR端口输出数据寄存器_ODR端口位设置/清除寄存器_BSRR端口位清除寄存器_BRR端口配置锁定寄存器…

《Jetpack Compose从入门到实战》 第二章 了解常用UI组件

目录 常用的基础组件文字组件图片组件按钮组件选择器组件对话框组件进度条组件 常用的布局组件布局Scaffold脚手架 列表 书附代码 Google的图标库 常用的基础组件 文字组件 Composable fun TestText() {Column(modifier Modifier.verticalScroll(state rememberScrollState…

ESP32官方MPU6050组件介绍

前言 &#xff08;1&#xff09;因为我需要使用MPU6050的组件&#xff0c;但是又需要在这条I2C总线上挂载多个设备&#xff0c;所以我本人打算自己对官方的MPU6050的组件进行微调。建立一个I2C总线&#xff0c;设备依赖于这个总线挂载。 &#xff08;2&#xff09;既然要做移植…

list(链表)

文章目录 功能迭代器的分类sort函数&#xff08;排序&#xff09;merage&#xff08;归并&#xff09;unique(去重&#xff09;removesplice&#xff08;转移&#xff09; 功能 这里没有“[]"的实现&#xff1b;原因&#xff1a;实现较麻烦&#xff1b;这里使用迭代器来实…

vue3基础语法

2020年9月18日发布 2022年2月7日称为默认版本&#xff0c;意味vue3是现在也是未来 Ant Design Pc端组件库 Element Plus Pc端组件库 Vant 移动端 VueUse 基于composition 组合式api的常用函数集合 vue3中文文档&#xff1a;https://cn.vuejs.org/guide/introduction.html…

pandas_datareader读取yahoo金融数据超时问题timeout解决方案

在《Python金融数据挖掘》一书中&#xff0c;学习到网络数据源这一章节&#xff0c;利用书中的方法安装了pandas_datareader包&#xff0c;但在获取雅虎数据&#xff08;get_data_yahoo&#xff09;时会出现以下问题&#xff1a; 经过仔细分析和尝试&#xff0c;排除了yahoo受中…

2023年中国智能电视柜产量、需求量、市场规模及行业价格走势[图]

电视柜是随着电视机的发展和普及而演变出的家具种类&#xff0c;其主要作用是承载电视机&#xff0c;又称视听柜&#xff0c;随着生活水平的提高&#xff0c;与电视机相配套的电器设备也成为电视柜的收纳对象。 随着智能家具的发展&#xff0c;智能电视机柜的造型和风格都是有了…

2023/10/1 -- ARM

今日任务&#xff1a;select实现服务器并发 ser.c&#xff1a; #include <myhead.h>#define ERR_MSG(msg) do{\printf("%d\n",__LINE__);\perror(msg);\ }while(0)#define PORT 8888#define IP "192.168.1.5"int main(int argc, const char *argv[…

Java中DateTimeFormatter的使用方法和案例

&#x1f514;简介 在Java中,DateTimeFormatter类用于格式化和解析日期时间对象。它是日期时间格式化的强大而灵活的工具。 &#x1f514;作用 &#x1f335;1.本地化时间 本地化时间指根据指定的语言环境显示时间 1.1.创建DateTimeFormatter时指定Locale DateTimeFormatt…