WPF 数据模板、绑定

这篇文章展示了如何在WPF应用中使用XAML和C#进行数据绑定,包括控件与数据的绑定,如ListBox和DataGrid,以及控件之间的绑定,如Slider与TextBox。此外,还讨论了前后端绑定的区别以及双向绑定的操作,通过实现INotifyPropertyChanged接口来更新视图模型。
摘要由CSDN通过智能技术生成

理解:xmal和C#结合起来使用

  • 控件与数据的绑定
<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>
public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            List<Color> test = new List<Color>();

            test.Add(new Color() { Code = "#FFB6C1", Name = "浅粉红" });
            test.Add(new Color() { Code = "#FFC0CB", Name = "粉红" });
            test.Add(new Color() { Code = "#DC143C", Name = "深红" });
            test.Add(new Color() { Code = "#FFF0F5", Name = "淡紫红" });

            list.ItemsSource = test;
        }
    }

    public class Color
    {
        public string Code { get; set; }
        public string Name { get; set; }
    }

在这里插入图片描述


<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>
 public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            List<Color> test = new List<Color>();

            test.Add(new Color() { Code = "#FFB6C1", Name = "浅粉红" });
            test.Add(new Color() { Code = "#FFC0CB", Name = "粉红" });
            test.Add(new Color() { Code = "#DC143C", Name = "深红" });
            test.Add(new Color() { Code = "#FFF0F5", Name = "淡紫红" });

            grid.ItemsSource = test;
        }

    }

    public class Color
    {
        public string Code { get; set; }
        public string Name { get; set; }
    }

在这里插入图片描述


  • 控件与控件绑定
<Grid >
        <StackPanel>
            <Slider x:Name="slider" Margin="5" />
            <TextBox Text="{Binding ElementName=slider,Path=Value,Mode=OneWay}"  Margin="5" Height="30" />
            <TextBox Text="{Binding ElementName=slider,Path=Value}" Margin="5" Height="30"/>
            <TextBox Text="{Binding ElementName=slider,Path=Value}" Margin="5" Height="30"/>
        </StackPanel>
    </Grid>

实现了控件和后端的绑定

<Grid >
        <StackPanel>
            <TextBox Text="{Binding Name}"/>
        </StackPanel>
    </Grid>

后端

public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new Test()
            {
                Name = "张三"
            };
        }

其中新建的一个类

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

在这里插入图片描述


绑定案例

xmal语言

<Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="auto"/>
            <RowDefinition Height="auto"/>
            <RowDefinition Height="1*"/>
            <RowDefinition Height="9*"/>
        </Grid.RowDefinitions>

        <TextBlock Margin="5" Grid.Row="0" Grid.Column="0" Text="马鞍山市 --- 图书馆" FontSize="18" HorizontalAlignment="Center"/>

        <StackPanel Grid.Row="1" Grid.Column="0" Background="#0078d4">
            <TextBlock Text="登录" FontSize="22" HorizontalAlignment="Center" Foreground="White" Margin="5"/>
        </StackPanel>

        <Grid Grid.Row="3" Grid.Column="0" HorizontalAlignment="Center" >
            <Grid.RowDefinitions>
                <RowDefinition Height="30"/>
                <RowDefinition Height="30"/>
                <RowDefinition Height="30"/>
                <RowDefinition Height="30"/>
            </Grid.RowDefinitions>

            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="auto"/>
                <ColumnDefinition Width="200"/>
            </Grid.ColumnDefinitions>



			区别在这里,用户名使用绑定,密码没有绑定
			前者是前端依赖后端(前端绑定后端,代码写在后端)
			后者是后端依赖前端(后端绑定前端)
            <TextBlock Text="用户名" Grid.Row="0" Grid.Column="0" VerticalAlignment="Center"/>
            <TextBox Text="{Binding UserName}"  Grid.Row="0" Grid.Column="1" Margin="2"/>
            
            <TextBlock Text="密码" Grid.Row="1" Grid.Column="0" VerticalAlignment="Center"/>
            <TextBox x:Name="txtPassword" Grid.Row="1" Grid.Column="1" Margin="2"/>

            <CheckBox Grid.ColumnSpan="2" Content="记住密码" Grid.Row="2"/>

            <Button Grid.Row="3" Grid.ColumnSpan="2" Content="登录" Click="Button_Click"/>
        </Grid>
    </Grid>
public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            // 将数据绑定的必要操作
            this.DataContext = this;
        }

        public string UserName { get; set; } = "333";

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //接收账号密码
            string password = txtPassword.Text;
			
			//登录成功
            if (UserName == "wpf" && password == "666")
            {
                //弹出新的界面
                Index index = new Index();
                index.Show();

                //隐藏当前界面
                this.Hide();
            }
            else
            {
                //弹出一个警告框
                MessageBox.Show("输入的用户名或密码不正确");
                txtPassword.Text = "";
            }
        }
    }

双向绑定操作

//让属性具有通知前端的作用,需要继承  INotifyPropertyChanged
    public partial class MainWindow : Window,INotifyPropertyChanged
    {
        public MainWindow()
        {
            InitializeComponent();

            // 将数据绑定的必要操作
            this.DataContext = this;
        }

        //写法固定,想具备通知功能就可以把代码抄上去
        public event PropertyChangedEventHandler PropertyChanged;
        public event NotifyCollectionChangedEventHandler CollectionChanged;

        private void RaisePropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handle = PropertyChanged;
            if(handle != null)
            {
                handle(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        // 这里写法也固定,接收账号密码
        private string _UserName;
        public string UserName
        {
            get { return _UserName; }
            set { _UserName = value; RaisePropertyChanged("UserName"); }
        }

        private string _Password;
        public string Password
        {
            get { return _Password; }
            set { _Password = value; RaisePropertyChanged("Password"); }
        }


        private void Button_Click(object sender, RoutedEventArgs e)
        {

            if (UserName == "wpf" && Password == "666")
            {
                //弹出新的界面
                Index index = new Index();
                index.Show();

                //隐藏当前界面
                this.Hide();
            }
            else
            {
                //弹出一个警告框
                MessageBox.Show("输入的用户名或密码不正确");

                UserName = "";
                Password = "";
            }
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值