wpf

■ 布局

<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"
        mc:Ignorable="d"
        Title="MainWindow" Height="600" Width="1000">
    <Grid>
        <!-- 
            容器1
            Gird 类似div
        -->
        <Grid.RowDefinitions>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
        </Grid.RowDefinitions>

        <Grid.ColumnDefinitions>
            <ColumnDefinition></ColumnDefinition>
            <ColumnDefinition></ColumnDefinition>
        </Grid.ColumnDefinitions>

        <Border Background="blue"></Border>
        <Border Grid.Row="1" Background="yellow"></Border>
        <Border Grid.Column="1" Background="red"></Border>
        <Border Grid.Row="1" Grid.Column="1" Background="green"></Border>

        <!-- 
            容器2
            类似float,超出隐藏 Horizontal:水平排列  Vertical:垂直排列 默认水平排列
        -->
        <StackPanel Orientation="Vertical">
            <Button Width="100" Height="40"></Button>
            <Button Width="100" Height="40"></Button>
            <Button Width="100" Height="40"></Button>
            <Button Width="100" Height="40"></Button>
            <Button Width="100" Height="40"></Button>
            <Button Width="100" Height="40"></Button>
        </StackPanel>

        <!-- 
            容器3
            类似float,超出换行 Horizontal:水平排列  Vertical:垂直排列  默认水平排列
        -->
        <WrapPanel Grid.Row="1">
            <Button Width="100" Height="40"></Button>
            <Button Width="100" Height="40"></Button>
            <Button Width="100" Height="40"></Button>
            <Button Width="100" Height="40"></Button>
            <Button Width="100" Height="40"></Button>
            <Button Width="100" Height="40"></Button>
        </WrapPanel>

        <!-- 
            容器4
            最后一个元素填充剩余空间并在剩余空间居中
            1. LastChildFill:最后一个元素是否填充剩余空间:false  true 
            2. DockPanel.Dock:控制元素的方向
        -->
        <DockPanel Grid.Column="1" LastChildFill="False">
            <Button Width="100" Height="40" DockPanel.Dock="Top"></Button>
            <Button Width="100" Height="40" DockPanel.Dock="Bottom"></Button>
            <Button Width="100" Height="40" DockPanel.Dock="Left"></Button>
            <Button Width="100" Height="40" DockPanel.Dock="Right"></Button>
        </DockPanel>

        <!-- 强制3行3列 瓜分元素 -->
        <UniformGrid Grid.Row="1" Grid.Column="1" Columns="3" Rows="3">
            <Button></Button>
            <Button></Button>
            <Button></Button>

            <Button></Button>
            <Button></Button>
            <Button></Button>

            <Button></Button>
            <Button></Button>
            <Button></Button>
        </UniformGrid>
        
    </Grid>

</Window>
View Code
<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"
        mc:Ignorable="d"
        Title="MainWindow" Height="600" Width="1000">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="100" ></RowDefinition>
            <RowDefinition></RowDefinition>
        </Grid.RowDefinitions>
        <Border Background="#7671D8"></Border>

        <Grid Grid.Row="1">

            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="200"></ColumnDefinition>
                <ColumnDefinition></ColumnDefinition>
            </Grid.ColumnDefinitions>
            <Border Background="Blue"/>

            <Grid Grid.Column="1">

                <Grid.ColumnDefinitions>
                    <ColumnDefinition />
                    <ColumnDefinition />
                    <ColumnDefinition />
                    <ColumnDefinition />
                    <ColumnDefinition />
                </Grid.ColumnDefinitions>

                <!-- Height="0.8*" 表示元素高度为其他列的8/10 -->
                <Grid.RowDefinitions>
                    <RowDefinition Height="0.8*"/>
                    <RowDefinition/>
                    <RowDefinition/>
                    <RowDefinition/>
                    <RowDefinition/>
                </Grid.RowDefinitions>
                <Border Margin="5" Grid.Column="0" Background="black"></Border>
                <Border Margin="5" Grid.Column="1" Background="#4c9ecd"></Border>
                <Border Margin="5" Grid.Column="2" Background="#5ac4b6"></Border>
                <Border Margin="5" Grid.Column="3" Background="red"></Border>
                <Border Margin="5" Grid.Column="4" Background="yellow"></Border>

                <Border Background="red" Grid.ColumnSpan="3" Grid.Row="1" Margin="5"></Border>
                <Border Background="Yellow" Grid.ColumnSpan="2" Grid.Row="1" Margin="5" Grid.Column="3"></Border>
                <Border Background="Blue" Grid.ColumnSpan="3" Grid.Row="2" Margin="5"></Border>
                <Border Background="Green" Grid.ColumnSpan="2" Grid.Row="2" Margin="5" Grid.Column="3"></Border>

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

</Window>
View Code

■ 样式

<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"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.Resources>
        <Style x:Key="BaseButtonStyle" TargetType="Button">
            <Setter Property="FontSize" Value="18"></Setter>
            <Setter Property="Foreground" Value="red"></Setter>
            <Setter Property="Background" Value="Yellow"></Setter>
        </Style>
        <!--{StaticResource BaseButtonStyle} 继承 x:key="BaseButtonStyle"的属性-->
        <Style x:Key="ButtonStyle" TargetType="Button" BasedOn="{StaticResource BaseButtonStyle}">
            <Setter Property="Content" Value="Button111"></Setter>
        </Style>
    </Window.Resources>
    <!--{StaticResource ButtonStyle} 继承 x:key="ButtonStyle"的属性-->
    <Grid>
        <StackPanel>
            <Button Style="{StaticResource ButtonStyle}">Button1</Button>
            <Button Style="{StaticResource ButtonStyle}">Button2</Button>
            <Button Style="{StaticResource ButtonStyle}">Button3</Button>
        </StackPanel>

    </Grid>

</Window>
View Code

■ 数据模板

<Window x:Class="WpfApp2.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:WpfApp2"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <!-- 
            1.AutoGenerateColumns 自动生成列,取消后不会自动生成多余的一列   
            2.CanUserAddRows 自动生成行,取消后不会自动生成多余的一行
        -->
        <DataGrid x:Name="grid" AutoGenerateColumns="False" CanUserAddRows="False">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Code" Binding="{Binding Code}"></DataGridTextColumn>
                <DataGridTextColumn Header="Name" Binding="{Binding Name}"></DataGridTextColumn>
                <DataGridTemplateColumn Header="操作">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <StackPanel Orientation="Horizontal">
                                <Button Content="保存"></Button>
                                <Button Content="取消"></Button>
                                <Button Content="删除"></Button>
                            </StackPanel>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>
        
        <!--<ListBox x:Name="list" >
            
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <ListBoxItem>
                        <StackPanel Orientation="Horizontal">
                            <Border Width="10" Height="10" Background="{Binding Code}"></Border>
                            <TextBlock Margin="10,0" Text="{Binding Name}"></TextBlock>
                        </StackPanel>
                    </ListBoxItem>
                </DataTemplate>
            </ListBox.ItemTemplate>
            
        </ListBox>-->
        
        
    </Grid>
</Window>
View Code

■ WPF控件绑定

xaml

<Window x:Class="WpfApp2.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:WpfApp2"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <!--
            控件与控件之间的绑定 
            1.path = value 显示的数据为value
            2.mode =  
                Default             默认,双向绑定
                OneTime             只绑定最初数据,之后的绑定数据无效
                OneWay              不允许当前控件改变绑定的控件的value,只允许绑定控件改变当前控件的value   单向绑定
                OneWayToSource      和OneWay相反
                TwoWay              双向绑定
        -->
        <!--<StackPanel>
            <Slider x:Name="Slider" Margin="5"></Slider>
            <TextBox x:Name="TextBox1" Text="{Binding ElementName=Slider,Path=Value,Mode=OneWayToSource}" Margin="5" Height="30"></TextBox>
            <TextBox x:Name="TextBox2" Text="{Binding ElementName=Slider,Path=Value}" Margin="5" Height="30"></TextBox>
            <TextBox x:Name="TextBox3" Text="{Binding ElementName=Slider,Path=Value}" Margin="5" Height="30"></TextBox>
        </StackPanel>-->
        
        <!-- 
            控件与属性之间的绑定
        -->
        <StackPanel>
            <TextBox x:Name="TextBox" Text="{Binding Name}" Margin="5" Height="30"></TextBox>
        </StackPanel>
    </Grid>
</Window>
View Code

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 WpfApp2
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new Test() { Name = "李四" };
        }
        public class Test
        {
            public string Name { get; set; }
        }
    }
    

}
View Code

 

■ HttpWebApi

Model:  Nuget管理引入 RRQMSocket.RPC.WebApi

using RRQMCore;
using RRQMSocket.RPC.WebApi;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace PublicModule
{
    class HttpWeb
    {
        private readonly string ApiUri = ConfigurationManager.AppSettings["ApiUri"];

        private dynamic result;

        public dynamic Run(string action,Dictionary<string, string> param)
        {
            var client = CreateWebApiClient();
            try
            {
                result = client.Invoke<dynamic>("POST:" + ApiUri + action, null, param);
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return result;
        }

        private static WebApiClient CreateWebApiClient()
        {
            WebApiClient client = new WebApiClient();
            client.Setup("112.16.230.8:82");
            client.Connect();
            Console.WriteLine("连接成功");
            return client;
        }
    }
}
View Code

ViewModel

using Caliburn.Micro;
using PublicModule;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace SystemManage.UserManage.ViewModels
{
    public class UserViewModel : Screen
    {
        private List<UserEnt> _users;
        public List<UserEnt> UserList
        {
            get { return _users; }
            set
            {
                _users = value;
                NotifyOfPropertyChange(nameof(UserList));
            }
        }


        public UserViewModel()
        {

        }

        public void Search(string name, int sex,int age) {
            Dictionary<string, string> param = new Dictionary<string, string>();
            param.Add("name", name);
            param.Add("sex", sex.ToString());
            param.Add("age", age.ToString());

            var HttpWeb = new HttpWeb();
            dynamic result = HttpWeb.Run(action: "CreateUser", param: param);
            //MessageBox.Show(result["code"].ToString());
            MessageBox.Show(result["data"]["age"].ToString());
        }

        //public async void Search(string name, int sex)
        //{
        //    Dictionary<string, string> param = new Dictionary<string, string>();
        //    param.Add("name", name);
        //    param.Add("sex", sex.ToString());
        //    List<UserEnt> list = await HttpClientHelper.TryGetAsync<List<UserEnt>>("User/GetUserList", param);
        //    UserList = list;
        //}
    }
}
View Code

 

■ PassWord绑定数据

 PasswordBoxHelper.cs

using System.Windows;
using System.Windows.Controls;

namespace Admins.Helper
{
    /// <summary>
    /// 为PasswordBox控件的Password增加绑定功能
    /// </summary>
    public class PasswordBoxHelper
    {
        public static readonly DependencyProperty PasswordProperty =
            DependencyProperty.RegisterAttached("Password",
            typeof(string), typeof(PasswordBoxHelper),
            new FrameworkPropertyMetadata(string.Empty, OnPasswordPropertyChanged));
        public static readonly DependencyProperty AttachProperty =
            DependencyProperty.RegisterAttached("Attach",
            typeof(bool), typeof(PasswordBoxHelper), new PropertyMetadata(false, Attach));
        private static readonly DependencyProperty IsUpdatingProperty =
           DependencyProperty.RegisterAttached("IsUpdating", typeof(bool),
           typeof(PasswordBoxHelper));

        public static void SetAttach(DependencyObject dp, bool value)
        {
            dp.SetValue(AttachProperty, value);
        }
        public static bool GetAttach(DependencyObject dp)
        {
            return (bool)dp.GetValue(AttachProperty);
        }
        public static string GetPassword(DependencyObject dp)
        {
            return (string)dp.GetValue(PasswordProperty);
        }
        public static void SetPassword(DependencyObject dp, string value)
        {
            dp.SetValue(PasswordProperty, value);
        }
        private static bool GetIsUpdating(DependencyObject dp)
        {
            return (bool)dp.GetValue(IsUpdatingProperty);
        }
        private static void SetIsUpdating(DependencyObject dp, bool value)
        {
            dp.SetValue(IsUpdatingProperty, value);
        }
        private static void OnPasswordPropertyChanged(DependencyObject sender,
            DependencyPropertyChangedEventArgs e)
        {
            PasswordBox passwordBox = sender as PasswordBox;
            passwordBox.PasswordChanged -= PasswordChanged;
            if (!(bool)GetIsUpdating(passwordBox))
            {
                passwordBox.Password = (string)e.NewValue;
            }
            passwordBox.PasswordChanged += PasswordChanged;
        }
        private static void Attach(DependencyObject sender,
            DependencyPropertyChangedEventArgs e)
        {
            PasswordBox passwordBox = sender as PasswordBox;
            if (passwordBox == null)
                return;
            if ((bool)e.OldValue)
            {
                passwordBox.PasswordChanged -= PasswordChanged;
            }
            if ((bool)e.NewValue)
            {
                passwordBox.PasswordChanged += PasswordChanged;
            }
        }
        private static void PasswordChanged(object sender, RoutedEventArgs e)
        {
            PasswordBox passwordBox = sender as PasswordBox;
            SetIsUpdating(passwordBox, true);
            SetPassword(passwordBox, passwordBox.Password);
            SetIsUpdating(passwordBox, false);
        }
    }
}
View Code

Xmal    主要是声明命名空间和PasswordBox控件绑定

xmlns:Helper="clr-namespace:Admins.Helper" 
<Window x:Class="Admins.View.Login"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:Helper="clr-namespace:Admins.Helper"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        MouseMove="Window_MouseMove"
        WindowStyle="None" ResizeMode="NoResize"
        WindowStartupLocation="CenterScreen"
        Title="登陆界面" Height="484" Width="775" Icon="..\Asset\Images\Logo.png"
        DataContext="{Binding Login, Source={StaticResource Locator}}"
        >
    <Window.Background>
        <ImageBrush ImageSource="..\Asset\Images\LoginImage.png"/>
    </Window.Background>
    <Grid>
        <StackPanel Orientation="Horizontal">
            <Image Width="65" Margin="120,75,10,10" Source="..\Asset\Images\Logo.png" 
                   HorizontalAlignment="Left" VerticalAlignment="Top"/>
            <Label Name="labelSys" Content="后台管理系统" Width="200" Height="40" 
                   FontSize="22" FontFamily="宋体-方正超大字符集" Foreground="White"
                   Margin="0,93.5,10,10" VerticalAlignment="Top" ToolTip="当前登陆界面"/>
            <Label Name="labelUserName" Content="用户名:" Width="80" Height="30"
                   FontSize="19" Foreground="White" FontFamily="宋体"
                   Margin="-160,-60,0,0" HorizontalAlignment="Left"/>
            <Label Name="labelPwd" Content="密  码:" Width="80" Height="30" 
                   FontSize="19" Foreground="White" FontFamily="宋体"
                   Margin="-160,55,0,0" HorizontalAlignment="Left"/>
        </StackPanel>
        <StackPanel Orientation="Vertical">
            <TextBox Name="txtBoxUserName" Width="190" Height="25" 
                     VerticalContentAlignment="Center"  FontSize="16" FontFamily="宋体"
                     Margin="100,199,10,10" VerticalAlignment="Center"
                     Text="{Binding Userid}"/>
            <!--<TextBox Name="txtBoxPwd" Width="190" Height="25" FontFamily="宋体"
                    VerticalContentAlignment="Center"  FontSize="16"
                    Margin="100,25,10,10" VerticalAlignment="Center" 
                    Text="{Binding Pwd}"/>-->
            <PasswordBox Width="190" Height="25" FontFamily="宋体"
                    VerticalContentAlignment="Center"  FontSize="16"    PasswordChar="*"
                    Margin="100,25,10,10" VerticalAlignment="Center"  MaxLength="20"
                    Helper:PasswordBoxHelper.Attach="True"
                    Helper:PasswordBoxHelper.Password="{Binding Path=Password,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>

        </StackPanel>
        <StackPanel Orientation="Horizontal">
            <Button Name="btnLogin"  FontSize="21" Width="90" Height="35" IsDefault="True"
                    IsEnabled="True" BorderBrush="Transparent" 
                    Command="{Binding Login_btn}"
                    Margin="250,200,0,0" VerticalAlignment="Center" Background="Transparent"
                    MouseEnter="btnLogin_MouseEnter" MouseLeave="btnLogin_MouseLeave">
                <Image Name="imgLogin" Source="..\Asset\Images\Login.png" Stretch="UniformToFill" />
            </Button>
            <Button Name="btnCancel" FontSize="21" Width="90" Height="35"
                    IsEnabled="True" BorderBrush="Transparent" Click="btnCancel_Click"
                    Margin="100,200,0,0"  Background="Transparent"
                    MouseEnter="btnCancel_MouseEnter" MouseLeave="btnCancel_MouseLeave">
                <Image Name="imgCancel" Source="..\Asset\Images\Cancel.png"  Stretch="UniformToFill" />
            </Button>
        </StackPanel>
        <StackPanel Orientation="Vertical">
            <Label Name="userNameTip"  Margin="410,199,10,10"
                   FontSize="15" FontFamily="宋体" Foreground="Red" Height="25" Width="120"
                   HorizontalAlignment="Center" />
            <Label Name="pwdTip"  Margin="410,25,10,10"
                   FontSize="15" FontFamily="宋体" Foreground="Red" Height="25" Width="110"
                   HorizontalAlignment="Center" />
        </StackPanel>

    </Grid>
</Window>
View Code

ViewModel     用Password这个变量

private string _uerid;

        public string Userid
        {
            get => _uerid;
            set {
                _uerid = value;
                RaisePropertyChanged(() => Userid);
            }
        }

        private string _password;

        public string Password
        {
            get => _password;
            set
            {
                _password = value;
                RaisePropertyChanged(() => Password);
            }
        }
View Code

 

■ 登录/取消命令绑定

Xmal

<Button Command="{Binding Logins}"
        CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=Window}}">
</Button>

<Button Command="{Binding Close_btn}"></Button>
View Code

ViewModel

private RelayCommand<Window> _logins;

/// <summary>
/// 点击登录按钮执行命令
/// </summary>
public RelayCommand<Window> Logins
{
    get
    {
        return _logins
            ?? (_logins = new RelayCommand<Window>(
            (arg) =>
            {
                //执行逻辑,返回result,判断code状态
                if (result["code"].ToString() == "200")
                {
                    //跳转index窗体,并关闭当前login窗体
                    View.Index index = new View.Index();
                    index.Show();
                    arg.Close();
                }
            }));
    }
}

private RelayCommand _closebtn;

/// <summary>
/// 点击关闭按钮执行命令
/// </summary>
public RelayCommand Close_btn
{
    get
    {
        return _closebtn
            ?? (_closebtn = new RelayCommand(
            () =>
            {
                //关闭程序
                App.Current.Shutdown();
            }));
    }
}
View Code

 

■ 注册全局变量

AppData类

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

namespace Admins
{
    public class AppData:ObservableObject
    {
        /// <summary>
        /// 全局变量
        /// </summary>
        public static AppData Instance = new Lazy<AppData>(()=>new AppData()).Value;

        public string systemName = "后台管理系统1.0";

        public string SystemName
        {
            get => systemName;
            set
            {
                systemName = value;
                RaisePropertyChanged(() => SystemName);
            }
        }

    }
}
View Code

viewMidel注册

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

namespace Admins.ViewModel
{
    public class IndexViewModel:ViewModelBase
    {
        public AppData AppData { get; set; } = AppData.Instance;

        public IndexViewModel()
        {

        }
    }
}
View Code

xaml调用

<Window x:Class="Admins.View.Index"
        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:Admins.View"
        mc:Ignorable="d"
        DataContext="{Binding Index, Source={StaticResource Locator}}"
        Title="{Binding AppData.SystemName}" Height="450" Width="800">
    <Grid>

    </Grid>
</Window>
View Code

 

■ Loaded实现[ 页面加载后执行 ] 

xaml

<Window  x:Class="WPFSale.Views.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:prism="http://prismlibrary.com/"
        prism:ViewModelLocator.AutoWireViewModel="True"
        xmlns:Ui="clr-namespace:Hm.UI;assembly=Hm.UI"
         
        xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
        xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
        mc:Ignorable="d" Title="MainWindow">
    
<!--主要代码实现-->
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="Loaded" >
            <ei:CallMethodAction MethodName="View_Loaded" TargetObject="{Binding}" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
</Window>
View Code

ViewModel

using Prism.Mvvm;
using SqlHelp;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Linq;
using System.Windows.Controls;
 
namespace WPFSale.ViewModels
{
    public class MainWindowViewModel : BindableBase
    {
 
        public void View_Loaded(object sender,EventArgs e)
        {
          // do something here!
 
 
        }
    }
}
View Code

 

 ■ 修改默认button样式(去掉边框)

资源字典  ButtonBaseDictionary.xaml

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <Style x:Key="ButtonBaseStyle" TargetType="Button">
        <Setter Property="OverridesDefaultStyle" Value="True" />
        <Setter Property="Cursor" Value="Hand" />
        <Setter Property="FontSize" Value="10" />
        <Setter Property="FontWeight" Value="Bold" />
        <Setter Property="Padding" Value="5 3" />
        <Setter Property="Background" Value="#F7F7F7" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">
                    <Border Name="border" BorderThickness="1" CornerRadius="3,3,3,3" BorderBrush="#cccccc" Padding="{TemplateBinding Padding}" Background="{TemplateBinding Background}">
                        <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Property="Background" Value="#dddddd" />
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>
View Code

xaml

<Button Style="{StaticResource ButtonBaseStyle}"  Command="{Binding AppData.FristPrev}" Content="首页" />

 

 ■ 解析json字符串   原文地址:https://www.cnblogs.com/xiaoyao095/p/3552398.html

方法一:  
        /// <summary>
        /// Json解析
        /// </summary>
        /// <param name="JsonText">传入的Json字符串</param>
        /// <returns>返回集合List</returns>
        public List<string> JsonResult(string JsonText)
        {
            List<string> list = new List<string>();
            var json2 = (JObject)JsonConvert.DeserializeObject(JsonText);
            var vid = json2["vid"];
            var uid = json2["uid"];
            var Object = json2["object"];
            var json3 = (JObject)JsonConvert.DeserializeObject(Object.ToString());
            var result = json3["result"];
            var user = json3["user"];
            var group = json3["group"];
            var gate = json3["gate"];
            var datetime = json3["datetime"];
            list.Add(vid.ToString());
            list.Add(uid.ToString());
            list.Add(Object.ToString());
            list.Add(result.ToString());
            list.Add(user.ToString());
            list.Add(group.ToString());
            list.Add(gate.ToString());
            list.Add(datetime.ToString());
            return list;
        }
方法二:
        /// <summary>
        /// Json解析
        /// </summary>
        /// <param name="JsonText">传入的Json字符串</param>
        /// <returns>返回字符串</returns>
        public String JsonResult(string JsonText)
        {
            var json2 = (JObject)JsonConvert.DeserializeObject(JsonText);
            var vid = json2["vid"];
            var uid = json2["uid"];
            var Object = json2["object"];
            var json3 = (JObject)JsonConvert.DeserializeObject(Object.ToString());
            var result = json3["result"];
            var user = json3["user"];
            var group = json3["group"];
            var gate = json3["gate"];
            var datetime = json3["datetime"];
            string strText = vid + "
" + uid + "
" + result + "
" + user + "
" + group + "
" + gate + "
" + datetime;
            return strText;
        }
方法三:
        /// <summary>
        /// 解析Json
        /// </summary>
        /// <param name="JsonText">传入的Json字符串</param>
        /// <returns>返回数组</returns>
        public String[] JsonResult(string JsonText)
        {
            string[] str = new string[7];
            var json2 = (JObject)JsonConvert.DeserializeObject(JsonText);
            var vid = json2["vid"];
            var uid = json2["uid"];
            var Object = json2["object"];
            var json3 = (JObject)JsonConvert.DeserializeObject(Object.ToString());
            var result = json3["result"];
            var user = json3["user"];
            var group = json3["group"];
            var gate = json3["gate"];
            var datetime = json3["datetime"];
            str[0] = vid.ToString();
            str[1] = uid.ToString();
            str[2] = result.ToString();
            str[3] = user.ToString();
            str[4] = group.ToString();
            str[5] = gate.ToString();
            str[6] = datetime.ToString();
            return str;          
        }
View Code

 

 

 

 

--------------------------------

 

posted on 2022-03-26 16:29  逝年-  阅读(82)  评论(0编辑  收藏  举报