WPF C# Binding绑定不上的解决情况

使用的插件是:CommunityToolkit
Binding绑定不上的一般解决情况:

1.添加上下文

DataContext

全局绑定:

d:DataContext="{d:DesignInstance Type=local:CommSettingView}"

在某个组件上绑定:

<Grid DataContext="{Binding RelativeSource={RelativeSource AncestorType=local:SysSettingView}}">

2.添加相对资源

RelativeSource

 Command="{Binding SaveCommand, RelativeSource={RelativeSource AncestorType=UserControl}}"

3.通知模式

Mode(默认是双向通知)

<TextBox Text="{Binding PortNumber,Mode=TwoWay,RelativeSource={RelativeSource AncestorType=UserControl}}"/>

4.改变通知

将类继承INotifyPropertyChanged

public partial class SysSettingView :INotifyPropertyChanged

重写接口(复制即可):

public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
	PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

在代码里定义前端绑定的变量:ImgSaveLoc

public string ImgSaveLoc { get; set; }

前端绑定ImgSaveLoc

<TextBox Text="{Binding ImgSaveLoc,RelativeSource={RelativeSource AncestorType=UserControl},Mode=TwoWay}"/>

通知变更:

OnPropertyChanged(nameof(ImgSaveLoc));

5.重新生成项目

6.看自己绑定的对象是否实例化了

如果绑定的是引用类型(如类、数组、接口、委托等),或者引用类型中的某个成员,需要使用 new 关键字来实例化对象。

7.有没有{ get; set; }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值