日期:2014-05-18  浏览次数:20740 次

为什么这个绑定代码,只能绑定一次?
下面的代码,程序运行后,是有效的(第一次)。不过,之后就无效了。

例如,如果你修改任务栏的位置,那么,WorkArea变化了,但是,程序界面的Width和Height却没有跟着变化。

怎么解决?


XML code


<Window 其它内容省略  Height="{Binding Source={x:Static SystemParameters.WorkArea}, Path=Height}" Width="{Binding Source={x:Static SystemParameters.WorkArea}, Path=Width}">
</Window>




------解决方案--------------------
你又没有重绘......
------解决方案--------------------
你没有设置绑定的方向,默认是OneWay的

 
Height="{Binding Source={x:Static SystemParameters.WorkArea}, Path=Height,Mode=TwoWay}"
------解决方案--------------------
你先绑定到 Textblock 上,看看值有没有变化。
------解决方案--------------------
还有你绑定的是静态资源,
懂吧,
就是只绑定一次
你必须使用能改变界面的接口如INotifyProperty,附加属性等,或动态资源
界面才能改变

------解决方案--------------------
因为是static的类,没有通知机制。直接绑定的话,WPF无法接收到通知。
解决方法是
DataContext="{DynamicResource {x:Static SystemParameters.WorkAreaKey}}"
然后直接绑定数据,如
Height="{Binding Path=Height}"
------解决方案--------------------
你可以将所有需要在运行时改变的值放在一个类里,
再实现INotifyPropertyChanged接口
这样比较方便,也便于管理
数据类:
public class DemoCustomer : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;

private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
  
private string customerName;

public string CustomerName
{
get { return customerName; }
set 

customerName = value; 
NotifyPropertyChanged(CustomerName); //注意是大写写的属性
}
}
}

再在xaml后台设定数据源:
DemoCustomer customer=new DemoCustomer(); //最好调成全局变量,整个类可用,可改变属性
customer.CustomerName="xxxx";
this.DataContext=customer;

界面绑定:
Height="{Binding CustomerName}"