Silverlight数据绑定故障排除
本文旨在为Silverlight中绑定不起作用的一个非常常见且耗时的问题提供所有可能的解决方案Silverlight数据绑定故障排除,silverlight,xaml,data-binding,Silverlight,Xaml,Data Binding,本文旨在为Silverlight中绑定不起作用的一个非常常见且耗时的问题提供所有可能的解决方案 <TextBox Text="{Binding TextValue}"/> public class ViewModel { // ... public string TextValue { get; set; } // ... } 假设属性或文本框无法正确刷新。目标类未实现INotifyPropertyChanged 包含绑定属性的类需要实现INotifyPr
<TextBox Text="{Binding TextValue}"/>
public class ViewModel
{
// ...
public string TextValue { get; set; }
// ...
}
假设属性或文本框无法正确刷新。目标类未实现INotifyPropertyChanged
包含绑定属性的类需要实现INotifyPropertyChanged,并在绑定属性的值更改时引发PropertyChanged
public class ViewModel : INotifyPropertyChanged
{
//...
private string textValue;
public string TextValue
{
get { return textValue; }
set
{
textValue = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("TextValue"));
}
}
}
//...
}
datacontext为空
如果没有关联datacontext,则上面的示例将永远不起作用:
public MainPage()
{
this.DataContext = new ViewModel();
}
绑定模式没有很好地指定
如果我们希望更新TextValue属性,则上面的示例需要处于双向模式:
<TextBox Text="{Binding TextValue, Mode=TwoWay}"/>
默认情况下,模式为单向,这意味着属性更改时控件内容将更新。绑定具有不同的datacontext
public class ViewModel : INotifyPropertyChanged
{
//...
private string textValue;
public string TextValue
{
get { return textValue; }
set
{
textValue = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("TextValue"));
}
}
}
//...
}
此示例不起作用,因为项模板具有不同的datacontext:
<ListBox>
<ListBox.ItemTemplate>
<TextBox Text="{Binding TextValue}"/>
</ListBox.ItemTemplate>
</ListBox>
转换器没有很好的关联
最常见的关联转换器的方法是通过静态资源。确保密钥名称写得很好
<Page.Resources>
<converters:AValueConverter x:Key="AValueConverter"/>
</Page.Resources>
<TextBox Text="{Binding TextValue, Converter={StaticResource AValueConverter}}"/>
目标属性编写得不好或不存在
在这种情况下,不会调用转换器。目标属性或包含类的路径上的某些属性为null或不可见
包含页或用户控件应具有对目标属性的访问权限。此外,如果路径上的某些属性为空,则它将以静默方式失败
如果目标属性为null,则可能会有所帮助。实际上不是答案,而是提示。在对绑定问题进行故障排除时,关联模拟转换器可能有助于识别问题。在Convert和ConvertBack方法中设置断点,可以查看是否成功调用了目标属性。如果未命中断点,则表示目标属性或路径存在问题。