简单wpf小Demo

工作之余自己学习wpf,小demo记录一下(数据绑定),仅用于学习。

1、简单示例如下

1、界面设计如下,通过文本绑定 Name 属性 ,点击按钮修改对象类中name的值,通过通知事件修改界面的值。

2、People类设计如下

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

namespace WpfAppDemo
{
    public class People : INotifyPropertyChanged    //向客户端发出某一属性值已更改的通知
    {
        private int _age;

        public event PropertyChangedEventHandler PropertyChanged;

        private string name;

        public string Name
        {
            get { return name; }
            set
            {
                name = value;
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs("Name"));
                }
            }
        }

}

}

 

3、代码实现

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
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.Shapes;

namespace WpfAppDemo
{
    /// <summary>
    /// BindingDemo.xaml 的交互逻辑
    /// </summary>
    public partial class BindingDemo : Window
    {
        private People _people;
        public BindingDemo()
        {
            InitializeComponent();
            Init();      

        }

        private void Init()
        {
            _people = new People(1, "小红");
            //grid 绑定的对象,会先找本身绑定 textbox如果没有绑定name的值则向上找到grid绑定的对象name属性的值
            this.grid.DataContext = _people;  
        }

        /// <summary>
        /// 修改_people对象的值,界面跟着变化
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param>
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            _people.Name = "test";
        }
    }
}
 

 

2、完善示例demo

1、运行效果如下图:姓名txtbox绑定people中的Name、Age属性,通过按钮修改他们的属性值;选择txtbox绑定listbox选择

项的值,背景颜色使用listbox选择项的值。选择项2:绑定label的txt值。绑定模式Mode:TwoWay 绑定会将源数据发送到目标,如果目标属性的值发生变化,则会将它们发回给源,OneWay 则不会。

    1)使用 OneWay 绑定时,每当数据源(ListBox)发生变化时,数据就会从数据源流向目标(TextBlock)。

    2)OneTime 绑定也会将数据从源发送到目标;但是,仅当启动了应用程序或 DataContext 发生更改时才会如此操作,因此,它不会侦听源中的更改通知。

    3)OneWayToSource 绑定会将数据从目标发送到源。

    4)TwoWay 绑定会将源数据发送到目标,但如果目标属性的值发生变化,则会将它们发回给源。

2、前台xaml设置:

<Window x:Class="WpfAppDemo.BindingDemo" Background="Aqua"
        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:WpfAppDemo"
        mc:Ignorable="d"
        Title="主界面" Height="809.132" Width="790.635" WindowStartupLocation="CenterScreen">
    <Grid Name="GridInfo" Background="LightSkyBlue">
        <Button Content="修改姓名" BorderBrush="Blue" HorizontalAlignment="Left" Margin="10,60,0,0" VerticalAlignment="Top" 
                Width="75" Click="Button_Click"/>
        <TextBox Name="TxtName" BorderBrush="Aqua" HorizontalAlignment="Left" Height="23" Margin="47,32,0,0"
                 TextWrapping="Wrap" Text="{Binding Path=Name }" VerticalAlignment="Top" Width="120" />
        <Label Content="姓名" HorizontalAlignment="Left" Margin="2,28,0,0" VerticalAlignment="Top"/>
        <Label Name="LabelTxt" Content="您选择了:" HorizontalAlignment="Left" Margin="139,121,0,0" 
               VerticalAlignment="Top" RenderTransformOrigin="0.2,3.16"/>
        <TextBox HorizontalAlignment="Left" Height="23" Margin="139,214,0,0" TextWrapping="Wrap"
                 Text="{Binding LabelTxt}" VerticalAlignment="Top" Width="120"/>
        <ListBox x:Name="ListStockName" Background="AntiqueWhite" HorizontalAlignment="Left" Height="159" 
                 Margin="21,121,0,0" VerticalAlignment="Top" Width="88">
            <ListBoxItem Content="Blue"/>
            <ListBoxItem Content="Red"/>
            <ListBoxItem Content="Green"/>
            <ListBoxItem Content="Gray"/>
            <ListBoxItem Content="Cyan"/>
            <ListBoxItem Content="GreenYellow"/>
            <ListBoxItem Content="Orange"/>
        </ListBox>
        <TextBox HorizontalAlignment="Left" Height="23" Margin="139,156,0,0" TextWrapping="Wrap" 
                 Background="{Binding ElementName=ListStockName, Path= SelectedItem.Content}" 
                 Text="{Binding ElementName=ListStockName,Path= SelectedItem.Content,Mode=TwoWay}" VerticalAlignment="Top" Width="120"/>
        <Label x:Name="LabelTxt1" Content="您选择了2:" HorizontalAlignment="Left" Margin="139,189,0,0" VerticalAlignment="Top" RenderTransformOrigin="0.2,3.16"/>
        <TextBox Name="TxtName2" HorizontalAlignment="Left" Height="23" Margin="139,214,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
        <TextBox Name="TextBoxAge" HorizontalAlignment="Left" Height="23" Margin="301,28,0,0"
                 Text="{Binding Path=Age,Mode=TwoWay}" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
        <Button Name="ButtonChangeAge" Content="修改年龄" HorizontalAlignment="Left" Margin="301,61,0,0" 
                VerticalAlignment="Top" Width="75"  Click="ButtonChangeAge_Click"/>
        <Label Content="年龄" HorizontalAlignment="Left" Margin="243,28,0,0" VerticalAlignment="Top" RenderTransformOrigin="-4,0.76"/>
        <!--Text="{Binding  ElementName=LabelTxt1,Path=Content}"-->
    </Grid>
</Window>
 

3、后台代码实现:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
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.Shapes;

namespace WpfAppDemo
{
    /// <summary>
    /// BindingDemo.xaml 的交互逻辑
    /// </summary>
    public partial class BindingDemo : Window
    {
        private People _people;
        public BindingDemo()
        {
            InitializeComponent();
            Init();
        }

        private void Init()
        {
            _people = new People(10, "小明");
            //grid 绑定的对象,会先找本身绑定 textbox如果没有绑定name的值则向上找到grid绑定的对象name属性的值
            GridInfo.DataContext = _people;  //姓名绑定

            TextBoxAge.DataContext = _people;  //姓名绑定,直接控件绑定

            Binding binding = new Binding(); //您选择了2 textbox绑定另一个控件的属性
            binding.Source = LabelTxt1;
            binding.Path = new PropertyPath("Content");
            this.TxtName2.SetBinding(TextBox.TextProperty, binding);   //或者在前台绑定 <!--Text="{Binding  ElementName=LabelTxt1,Path=Content}"--> 

           BindingOperations.ClearBinding(TxtName2, TextBox.TextProperty); //移除绑定BindingOperations同时还提供了ClearAllBindings方法,只需要传入要清除绑定的目标对象的名称,它就会将所有这个对象的绑定移除。
        }

        /// <summary>
        /// 修改_people对象姓名的值,界面跟着变化
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param>
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            _people.Name = "小华";
        }

        /// <summary>
        /// 改变年龄的值,界面跟着变化
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param>
        private void ButtonChangeAge_Click(object sender, RoutedEventArgs e)
        {
            _people.Age = 30;
        }
    }
}
 

4、people类

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

namespace WpfAppDemo
{
    public class People : INotifyPropertyChanged
    {
        private int _age;

        public event PropertyChangedEventHandler PropertyChanged;

        private string name;

        protected void Notify(string propName)
        {
            if (this.PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propName));
            }

        }

        public string Name
        {
            get { return name; }
            set
            {
                name = value;
                Notify("Name");
            }
        }

        public int Age
        {
            get { return _age; }
            set
            {
                if (value < 0)
                {
                    value = 0;
                }
                else
                {
                    _age = value;
                }
                Notify("Age");

            }
        }

        public People(int age, string name)
        {
            this.Age = age;
            this.Name = name;
        }

        public string Action()
        {
            if (Age < 20)
            {
                return "小学生";
            }
            else if (Age < 30 && Age > 20)
            {
                return "大学";
            }
            else
            {
                return "教学";
            }

        }
    }
}
 

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值