WPF中的属性绑定 binding

本文分享了作者使用 C# 进行 databinding 的实践经历,重点在于理解属性的概念及如何正确设置绑定路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天试着用data binding写了个小程序, 发现对c#的基本概念还是不清楚,导致走了弯路

window 1.xaml

<Window x:Class="bindtest.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Height="300" Width="300"
    xmlns:localadd ="clr-namespace:bindtest"
    >
  <DockPanel>
    <DockPanel.Resources>
      <localadd:MyData x:Key="vaav" />
    </DockPanel.Resources>

    <DockPanel.DataContext>
      <Binding Source="{StaticResource vaav}"/>
    </DockPanel.DataContext>

    <Button Click="ClickMe"  Background="{Binding Path=colorName }"  Width="150" Height="30">
      I am bound to be RED!
    </Button>

  </DockPanel>
</Window>

 

MyData.cs

using System;

namespace bindtest
{

    public class MyData
    {

        private string ColorName = "Red";
        public string colorName
        {
            get { return ColorName; }
            set { ColorName = value; }
        }
    }
}

文档中说Path=colorName , colorName是属性字段, 就是对属性这个基本概念的不清,导致我写成了

using System;    

namespace bindtest
{

    public class MyData
    {

        public string colorName = "Red";  //Error code

  }
}   

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值